September 2026 release is live Read More

Agent Cost & UsageJavaScript TypeScript SDK Quickstart

JavaScript / TypeScript SDK Quickstart

Use this guide to connect a JavaScript or TypeScript agent application to Mavvrik, capture model usage and cost, and verify the resulting execution trace.

Requirements

You need:

  • a JavaScript or TypeScript agent application;

  • a supported runtime and AI provider or framework;

  • permission to register an agent in Mavvrik.

See Supported Agentic Stacks for compatibility.

1. Register the agent

Complete Register an Agent, then copy the tenant ID, agent ID, and API key from the Connect step.

Keep the Agent ID stable. Mavvrik uses it to attribute captured activity and cost to the agent.

2. Install the SDK

Install the core SDK:

Bash
npm install @mavvrikai/sdk

Install the instrumentation packages required by the application:

Bash
# OpenAI
npm install @mavvrikai/sdk @mvk/instr-openai

# Anthropic
npm install @mavvrikai/sdk @mvk/instr-anthropic

# LangChain
npm install @mavvrikai/sdk @mvk/instr-langchain

3. Configure the SDK

Bash
export MVK_TENANT_ID="your-tenant-id"
export MVK_AGENT_ID="your-agent-id"
export MVK_API_KEY="your-api-key"

Optional global tags:

Bash
export MVK_TAG_ENV="production"
export MVK_TAG_REGION="us-east-1"

Store the API key in the deployment environment or secret manager. Do not commit it to source control.

4. Initialize Mavvrik before supported AI calls

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({
  wrappers: { include: ['genai'] },
});

The quickstart intentionally enables only genai. Enable additional supported instrumentation only when the application needs it.

Credentials can also be passed directly for local testing:

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({
  tenantId: 'your-tenant-id',
  agentId: 'your-agent-id',
  apiKey: 'your-api-key',
  wrappers: { include: ['genai'] },
});

Environment variables take precedence over values passed in code.

5. Make a supported AI call

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({ wrappers: { include: ['genai'] } });

import OpenAI from 'openai';

const client = new OpenAI();

const response = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Summarize this claim in one sentence.' },
  ],
});

console.log(response.choices[0].message.content);

Existing provider calls do not need to be replaced with Mavvrik-specific APIs.

What Mavvrik captures automatically

For supported calls, Mavvrik records the telemetry exposed by the provider or framework, including:

  • provider and model;

  • token or equivalent usage quantities;

  • cached and reasoning token fields where available;

  • request duration;

  • success/failure and error information;

  • trace relationships;

  • pricing inputs used by Mavvrik to calculate cost.

6. Verify the integration

Run one known test request, then open:

  1. Home → Agentic → Cost — confirm the agent shows new spend.

  2. Home → Agentic → Sessions — inspect the captured operation and trace.

Allow up to 10 minutes for processed activity to appear.

Provider and framework examples

Anthropic

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({ wrappers: { include: ['genai'] } });

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

const response = await client.messages.create({
  model: 'claude-sonnet-4-5',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Summarize this claim.' }],
});

Install @mvk/instr-anthropic with the core SDK.

Amazon Bedrock

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({ wrappers: { include: ['genai'] } });

import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from '@aws-sdk/client-bedrock-runtime';

const client = new BedrockRuntimeClient({});

const response = await client.send(new InvokeModelCommand({
  modelId: 'anthropic.claude-sonnet-4-5-v1:0',
  body: JSON.stringify({
    messages: [{ role: 'user', content: 'Summarize this claim.' }],
  }),
}));

LangChain / LangGraph

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({
  wrappers: { include: ['genai', 'langchain'] },
});

import { ChatOpenAI } from '@langchain/openai';

const llm = new ChatOpenAI({ model: 'gpt-4o-mini' });
const result = await llm.invoke('Summarize this claim.');

With framework instrumentation enabled, framework activity and supported model calls are correlated in the execution trace.

Vector databases

The JavaScript / TypeScript SDK supports selected vector databases through their corresponding instrumentation packages. See Supported Agentic Stacks for the current list.

Add business context

Use withMvkContext() once around the relevant business transaction.

TypeScript
import { instrument, withMvkContext } from '@mavvrikai/sdk';
import OpenAI from 'openai';

await instrument({ wrappers: { include: ['genai'] } });

const client = new OpenAI();

async function answerCustomer(
  customerId: string,
  userId: string,
  sessionId: string,
  message: string,
) {
  return withMvkContext(
    {
      customerId,
      userId,
      sessionId,
      useCase: 'customer_support',
      tags: { channel: 'web' },
    },
    async () => {
      const response = await client.chat.completions.create({
        model: 'gpt-4o-mini',
        messages: [{ role: 'user', content: message }],
      });

      return response.choices[0].message.content;
    },
  );
}

See Add Business Context.

Track metered non-LLM usage

Use metered usage when the workflow consumes a paid resource that Mavvrik cannot price automatically.

TypeScript
import { addMeteredUsage } from '@mavvrikai/sdk';

addMeteredUsage([
  {
    metricKind: 'eligibility_api.request',
    quantity: 1,
    uom: 'call',
    metadata: {
      rate_per_unit: 0.05,
      currency: 'USD',
      provider: 'eligibility-service',
    },
  },
]);

Add a signal when the operation should also appear as a named trace step:

TypeScript
import { createSignal, MVKStepType } from '@mavvrikai/sdk';

const signal = createSignal({
  name: 'eligibility-check',
  step_type: MVKStepType.TOOL,
  operation: 'api_call',
  vendor: 'eligibility-service',
});

try {
  await eligibilityApi.check(memberId);
} finally {
  signal.end();
}

See Track Metered Usage.

Start without application code changes

Bash
export MVK_TENANT_ID="your-tenant-id"
export MVK_AGENT_ID="your-agent-id"
export MVK_API_KEY="your-api-key"

node --import @mavvrikai/sdk/register your-app.js

To preload Mavvrik for Node processes:

Bash
export NODE_OPTIONS="--import @mavvrikai/sdk/register"

Instrument web applications

Express

TypeScript
import { instrument } from '@mavvrikai/sdk';

await instrument({ wrappers: { include: ['genai'] } });

import express from 'express';
import { mvkExpress } from '@mavvrikai/sdk/adapter-express';

const app = express();
app.use(mvkExpress());

Fastify, Koa, Hono, NestJS, and Next.js use their corresponding adapters.

Instrument serverless and short-lived processes

For AWS Lambda:

TypeScript
import { instrument } from '@mavvrikai/sdk';
import { lambdaHandler } from '@mavvrikai/sdk/serverless';

await instrument({ wrappers: { include: ['genai'] } });

export const handler = lambdaHandler(async (event) => {
  return doWork(event);
});

For an unsupported short-lived platform:

TypeScript
import { flushWithBudget } from '@mavvrikai/sdk/serverless';

export async function handler(event: unknown) {
  try {
    return await doWork(event);
  } finally {
    await flushWithBudget(1000);
  }
}

For scripts and batch jobs:

TypeScript
const mvk = await instrument({ wrappers: { include: ['genai'] } });

// work

await mvk.shutdown();

Configure operational controls

Bash
export MVK_ENABLED=false
Bash
export MVK_LOG_LEVEL=DEBUG

Verify the complete setup

  • Agent registered in Mavvrik.
  • Tenant ID, agent ID, and API key configured.
  • Core SDK installed.
  • Required @mvk/instr-* packages installed.
  • instrument() runs before supported AI calls begin.
  • One known AI request completed.
  • Cost appears in Home → Agentic → Cost.
  • Execution appears in Home → Agentic → Sessions.
  • Required business context is attached.
  • Metered non-LLM usage is recorded where it contributes to total cost.

If any item fails, use Troubleshooting Agent Data.