@rudderstack/ai
v0.15.0
Published
Automatic RudderStack AI product events and MCP server events for Node.js AI apps: OpenAI, OpenAI Agents, Anthropic, Google Gen AI, Google ADK, Amazon Bedrock, Vercel AI SDK, LangChain.js, the Claude Agent SDK and Mastra
Maintainers
Readme
@rudderstack/ai
Standard AI product events for Node.js backends. Each answer your AI feature gives becomes a small set of RudderStack track events (prompt, answer with totals, feedback), sent through the RudderStack Node.js client you already use and following the AI events spec v0.4.
How it fits
your app ─ provider wrapper / framework handler ─ aiInteraction() ─ your RudderStack client ─ RudderStack ─ warehouse, destinationsOne answer is one ai_response_received, however many model calls it took, reported by provider wrappers and framework integrations, for product analytics: usage, cost, intent, outcome, feedback. This is not an observability tool: it complements Langfuse, LangSmith or your APM by putting AI usage next to the rest of your customer data; set trace_id to join the two (Advanced: OpenTelemetry export). It is private by default: no prompt or answer text is sent unless you turn content capture on, and captured text is masked.
Install
npm install --save-exact @rudderstack/ai @rudderstack/rudder-sdk-node@rudderstack/rudder-sdk-node must be 3.0.16 or later: it is an optional peer dependency with >=3.0.16, so npm stops with ERESOLVE when an older version is installed. Upgrade it in the same command.
Then the framework you use (openai, @openai/agents, @anthropic-ai/sdk, @google/genai, @aws-sdk/client-bedrock-runtime, ai, @langchain/core, @anthropic-ai/claude-agent-sdk, @modelcontextprotocol/sdk 1.x or @modelcontextprotocol/server 2.x for MCP servers; @opentelemetry/api, @opentelemetry/sdk-trace-base and @opentelemetry/sdk-trace-node, plus @ai-sdk/otel for the Vercel AI SDK, for tracing); all are optional peer dependencies. Node.js 24 or later; ESM and CommonJS builds with type declarations.
Quick start
import Analytics from '@rudderstack/rudder-sdk-node';
import OpenAI from 'openai';
import { aiInteraction, configure, flush, trackAction } from '@rudderstack/ai';
import { wrapOpenAI } from '@rudderstack/ai/openai';
configure({
analytics: new Analytics(process.env.RUDDERSTACK_WRITE_KEY!, {
dataPlaneUrl: process.env.RUDDERSTACK_DATA_PLANE_URL!,
}),
});
const openai = wrapOpenAI(new OpenAI());
// One aiInteraction per user turn: every model call inside it adds up into one answer.
const { answer, interactionId } = await aiInteraction(
{ userId, conversationId, feature: 'support_bot' },
async (interaction) => {
const res = await openai.responses.create({ model: 'gpt-4.1-mini', input: question });
return { answer: res.output_text, interactionId: interaction.id }; // send the ID to the client
},
);
// Later, from your feedback endpoint:
trackAction({
userId,
interactionId,
conversationId,
actionType: 'feedback_given',
actionDetails: { feedback_type: 'thumbs', feedback_value: 1 },
});
await flush(); // scripts, workers and serverless handlers: before exitingThis sends ai_user_prompt_created, ai_response_received (models, tokens, latency, status, cost when priced) and ai_user_action. If the events load into a warehouse, set up the cost column types first. Runnable apps for every integration are in examples/, including LangGraph interrupt and resume, Deep Agents across Claude and Gemini, Claude subagents, a cookieless bot and stream failures.
Choose your integration
| Integration | Import | Tracks |
| ---------------------------------------------------- | ---------------------------------- | --------------------------------------------------------------------- |
| OpenAI | @rudderstack/ai/openai | Chat Completions, Responses, their helpers; streaming or not |
| OpenAI Agents SDK | @rudderstack/ai/openai-agents | Agent runs, model turns, tools and handoffs; streaming or not |
| Gateways and routers | @rudderstack/ai/openai | OpenRouter, a LiteLLM proxy, the Vercel AI Gateway |
| Anthropic | @rudderstack/ai/anthropic | Messages (also Bedrock and Vertex clients), helpers, beta tool runner |
| Google Gen AI | @rudderstack/ai/google-genai | Gemini API and Vertex AI generateContent, chats, function calls |
| Google ADK | @rudderstack/ai/google-adk | Runner turns, Gemini model calls, tools and agent transfers |
| Amazon Bedrock | @rudderstack/ai/bedrock | Converse and ConverseStream, including tools and cache usage |
| Vercel AI SDK | @rudderstack/ai/vercel-ai-sdk | Every model call and tool-loop step of a wrapped model |
| LangChain and LangGraph | @rudderstack/ai/langchain | Every chat model call and tool run in a chain, agent or graph |
| Claude Agent SDK | @rudderstack/ai/claude-agent-sdk | Each turn of query(), with the SDK's own cost |
| Mastra | @rudderstack/ai/mastra | Agent/workflow answers, model steps and nested tools |
| MCP servers | @rudderstack/ai/mcp | Clients, tool calls, elicitations, resources and prompts of a server |
| Other frameworks | @rudderstack/ai | Calls you report with interaction.recordCall() |
Rules that apply to all of them, because breaking them produces wrong numbers:
- One
aiInteractionper user turn, not per conversation or per process. Pass your chat or thread ID asconversationIdso turns group into a conversation. A one-shot feature with no thread (a Generate button, a suggested fix) setsoneShot: true: without an explicit or context conversation ID,conversation_idis the interaction's ID. The default still mints a separate conversation ID. - Resending the history each turn is fine (
useChat, a LangGraph checkpointer, your own message array): each turn reports only the calls it made, and the resent messages count as that call's input tokens, as the provider bills them. - Streaming: return the stream (or a streaming
Response) from theaiInteractioncallback, or pass it throughinteraction.bind(stream). The interaction then ends when the stream does. A call that runs after its interaction ended is reported as a separate answer, with a warning. - One integration per call path: a call reported twice with the same provider response ID counts once, but do not stack a LangChain handler on a wrapped client on purpose.
- Serverless and workers:
await flush()before the handler returns (details).
Full setup, options and edge cases per integration: docs/integrations.md.
OpenAI
const openai = wrapOpenAI(new OpenAI()); // a tracked view; the original client is not modified
const stream = await aiInteraction({ userId, conversationId }, () =>
openai.chat.completions.create({ model: 'gpt-4.1-mini', messages, stream: true }),
);
for await (const chunk of stream) send(chunk); // the interaction ends when the stream doesFor streamed Chat Completions the wrapper requests usage (stream_options.include_usage) on every host, including OpenAI-compatible endpoints (Azure, Groq, OpenRouter, Ollama, vLLM). A request the host rejects (HTTP 400 or 422 naming the parameter, or with no error code) is sent once more without it, and once a host names it that client stops adding it there; streamUsage: false never adds it. Without usage, a streamed call has no token counts or cost.
OpenAI Agents SDK
import { Runner } from '@openai/agents';
import { trackedRun } from '@rudderstack/ai/openai-agents';
const result = await trackedRun(
new Runner(),
triageAgent,
question,
{ session },
{
userId,
feature: 'support_agent',
},
);One run is one interaction (trackedRunStreamed for streamed runs): every model call with the agent that made it (agent_name in usage_breakdown), function and hosted tools, handoffs, agents used as tools, guardrail trips (error_type: guardrail_trip) and failures. A run stopped at maxTurns or cut off at the output-token limit is response_status: incomplete (error_type max_turns or length, the call keeps its usage); a run waiting on a tool approval (interruptions) is paused with pause_reason: approval. A session's ID becomes conversation_id. Calls that wrapOpenAI also sees are counted once. For MCP servers, toolMetaResolver: rudderStackMcpToolMeta() sends the interaction's IDs in each tools/call _meta (MCP servers). See docs/integrations.md for what needs Agents SDK tracing.
Gateways and routers
- OpenRouter:
wrapOpenAI(new OpenAI({ baseURL: 'https://openrouter.ai/api/v1' }), { provider: 'openrouter' }). Itsusage.costis the call's cost. - LiteLLM proxy:
wrapOpenAI(new OpenAI({ baseURL: 'http://localhost:4000/v1' }), { provider: 'litellm' }). The served deployment comes from thex-litellm-model-nameheader (the body'smodelis the alias you asked for), the cost fromx-litellm-response-cost, or fromusage.costin a stream. Node.js reaches LiteLLM through its proxy only; the Python SDK also instruments the LiteLLM SDK. - Vercel AI Gateway (Node.js only):
rudderstackMiddlewareon agateway(...)model (Vercel AI SDK) readsproviderMetadata.gateway:costis the call's cost androuting.finalProviderthe provider that served it.
A gateway's call is reported under the served model's vendor (openai/gpt-4o → openai, full name in model). When a router or fallback served another model than the one asked for, requested_model (on usage_breakdown entries and ai_llm_response_received) holds the requested one; a dated version of the same model is not another model. Cost: the provider's or gateway's reported cost, then your registered price (which also matches the name after the vendor prefix: gpt-4o prices openai/gpt-4o-2024-08-06), otherwise none.
Anthropic
const anthropic = wrapAnthropic(new Anthropic()); // AnthropicBedrock: { provider: 'aws.bedrock' }; AnthropicVertex: { provider: 'gcp.vertex_ai' }
await aiInteraction({ userId, conversationId }, async () => {
const stream = anthropic.messages.stream({
model: 'claude-haiku-4-5',
max_tokens: 1024,
messages,
});
for await (const event of stream) send(event);
});A registered Claude price also prices the Bedrock and Vertex model IDs: see Cloud model IDs and pricing.
Google Gen AI (Gemini and Vertex AI)
import { GoogleGenAI } from '@google/genai';
import { wrapGoogleGenAI } from '@rudderstack/ai/google-genai';
const gemini = wrapGoogleGenAI(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }));
const vertex = wrapGoogleGenAI(
new GoogleGenAI({ vertexai: true, project, location: 'us-central1' }),
);Tracks models.generateContent, models.generateContentStream and the sendMessage / sendMessageStream of chats from chats.create, including parallel function calls and automatic function calling. Provider gcp.gemini for the Gemini API, gcp.vertex_ai for a Vertex AI client (vertexai: true); the provider option overrides it. The two are priced separately, so register each provider you call; prices registered under google and google.vertex (the labels before 0.5.0) still price gcp.gemini and gcp.vertex_ai calls.
- Thinking tokens (
thoughtsTokenCount) are output tokens andreasoning_tokens; input + output equals Google'stotalTokenCount. - Automatic function calling without streaming returns only the last request's usage: the call counts every request but is left unpriced. A stream reports every request's usage.
embedContentand every other method pass through untracked.
Details: docs/integrations.md, example: examples/google-genai.
Amazon Bedrock (Converse)
import { BedrockRuntimeClient, ConverseStreamCommand } from '@aws-sdk/client-bedrock-runtime';
import { wrapBedrock } from '@rudderstack/ai/bedrock';
const bedrock = wrapBedrock(new BedrockRuntimeClient({ region: 'us-east-1' }));
await aiInteraction({ userId, conversationId }, async () => {
const { stream } = await bedrock.send(
new ConverseStreamCommand({ modelId, messages, toolConfig }),
{ abortSignal: controller.signal }, // optional: an abort is a cancelled call
);
for await (const event of stream ?? []) send(event);
});Tracks send() of ConverseCommand and ConverseStreamCommand, and converse() / converseStream() of the aggregated BedrockRuntime client. Other commands and callback-style send(command, callback) pass through untracked. Provider aws.bedrock, integration bedrock, model the request modelId, response_id the AWS request ID.
- Usage: AWS
inputTokensexcludes cache reads and writes, soinput_tokens=inputTokens + cacheReadInputTokens + cacheWriteInputTokens. For 30 + 10 read + 5 written input and 8 output tokens at 3 / 15 / 0.3 / 3.75 USD per million:input_tokens45, cost(30×3 + 10×0.3 + 5×3.75 + 8×15) / 1e6= 0.00023175. finish_reasonfromstopReason:end_turnandstop_sequence→stop,tool_use→tool_calls,max_tokens→length,guardrail_intervenedandcontent_filtered→content_filter; other values as sent.- Tool calls from
toolUseblocks (streamed ones by content block index); outcomes from thetoolResultblocks (status: 'error'is a failure) a later request in the same interaction sends back. - Errors:
ThrottlingExceptionisrate_limit,ValidationExceptioninvalid_request,AccessDeniedExceptionauth_error, otherwise the HTTP status from$metadata. A stream that throws mid-way, or ends withoutmessageStop, is a failed call; inside your ownaiInteractionthe answer stays open, so you can retry in it. - A stream you stop early (
break, orabortSignal) is a cancelled call: tokens kept, no cost.
The Python SDK wraps boto3's converse / converse_stream instead of send().
Vercel AI SDK
const model = wrapLanguageModel({
model: anthropic('claude-haiku-4-5'),
middleware: rudderstackMiddleware(),
});
export async function POST(req: Request) {
const { id, messages } = (await req.json()) as { id: string; messages: UIMessage[] }; // useChat sends the full history
const modelMessages = await convertToModelMessages(messages);
return aiInteraction({ userId, conversationId: id }, (interaction) => {
const result = streamText({ model, messages: modelMessages, tools, stopWhen: stepCountIs(5) });
return createUIMessageStreamResponse({
headers: { 'x-interaction-id': interaction.id },
stream: toUIMessageStream({ stream: result.stream }),
});
});
}Every step of the tool loop lands in the one answer. With Express, pass interaction.bind(...) the UI message stream before piping it. A client that disconnects mid-stream produces response_status: cancelled. A step that ends on a tool-approval request ends the answer paused (pause_reason: approval) unless a later call in the interaction answers it.
LangChain and LangGraph
const handler = new RudderStackCallbackHandler({ agentName: 'support_agent' });
await aiInteraction({ userId, conversationId: threadId }, () =>
graph.invoke({ messages }, { callbacks: [handler], configurable: { thread_id: threadId } }),
);Pass the handler in the invoke / stream config, not the model constructor (it warns). Without aiInteraction, each top-level run opens its own interaction with identity from run metadata (user_id, conversation_id, else LangGraph's thread_id, ...), and is not classified. A graph stopped at interrupt() ends its answer as response_status: paused; pass the same interaction_id metadata to the resume so it reports the same turn (example).
Claude Agent SDK
for await (const message of trackedQuery(
{ prompt, options: { resume: sessionId } },
{
userId,
conversationId: sessionId,
usageBaseline: saved.baseline,
onUsageSnapshot(snapshot) {
if (snapshot === null) delete saved.baseline;
else saved.baseline = snapshot; // persist with the session ID
},
},
)) {
// consume every message before ending an outer interaction
}Without an outer interaction, each run opens its own interaction (one per turn). The interaction is taken when the stream is first read. Set requireInteraction: true on trackedQuery or trackMessages to warn once and pass the stream through untracked when no interaction is current or explicitly supplied. Default: false. End an outer interaction only after the tracked stream is fully consumed, or pass an explicit status to interaction.end({ status }); ending early without a status records an empty cancelled answer.
Pass agentName to trackedQuery or trackMessages to label a run, for example trackMessages(query(params), { agentName: 'router' }). Runs named router, main and summarizer inside one interaction produce separate usage_breakdown entries with agent_name, tokens and cost. Claude subagent names take precedence; calls and tools without a derived subagent name use the run's name. Omitting the option preserves unnamed main-loop groups. An untracked stream with requireInteraction: true ignores it.
Pass primary: true to trackedQuery or trackMessages to use that run's main model (the served model of its main-loop calls) for primary_model and primary_provider. For router (haiku) → main (sonnet, primary) → summarizer (haiku), the primary model stays sonnet. The option works with agentName; if several runs are marked, the last started marked run that records a successful call wins, regardless of result or cleanup order. It defaults to false, preserving the last-successful-call rule. A marked run that records no successful call leaves that rule in place; a successful result stays primary even if a later consumer or stream error occurs. An untracked stream ignores it.
onUsageSnapshot is called exactly once at stream close, after unfinished-turn cleanup, with the latest fresh result snapshot (the same value usageSnapshot(result) returns), or null when the run ends without a result, or its last result is cancelled or empty; an error result that reports usage is still a valid baseline. A run that throws or has an unfinished later turn also delivers null. Each accepted streaming-input prompt needs a result: the snapshot stays stale until no accepted prompts remain unanswered, even before any user message or assistant output. Save on a value and delete your persisted baseline on null. It also runs for an untracked stream with requireInteraction. Async callbacks are accepted and run without delaying stream close. Callback failures are reported through onError as user_callback, without breaking the stream. usageSnapshot(result) still works independently.
trackedQuery is a drop-in for query(). A session resumed or continued (resume, continue) in another process restores its cumulative usage, so store usageSnapshot(result) with the session ID and pass it as usageBaseline next turn; without it the turn reports its own tokens, priced with your registered prices, and no SDK cost. Turns it opens are not classified unless you pass classify: true or wrap the turn in aiInteraction. A turn stopped at maxTurns or maxBudgetUsd, or cut off at max_tokens, is response_status: incomplete; a tool deferred by a PreToolUse hook ends it paused (pause_reason: deferred_tool).
Internal Claude CLI bookkeeping calls that appear only in ResultMessage.modelUsage are excluded when the tracked message stream proves no assistant response and no subagent used that model. A standalone recordClaudeResult() has no stream to distinguish them, so it maps every reported row.
Cloud model IDs and pricing
Claude models use the same family name in primary_model, usage_breakdown.model and per-call events across adapters: global.anthropic.claude-haiku-4-5-20251001-v1:0 and claude-haiku-4-5@20251001 become claude-haiku-4-5. Pricing and credits use each deployed ID with its own usage, even when a Claude Agent SDK usage alias covers several deployed IDs; returned provider messages keep those IDs. OpenAI and Gemini names keep their existing forms.
No prices ship with the package. A registered name prices that exact model or the model plus a version suffix (-2024-08-06, -20251001, -0613, -v2, :0, @20241022, -latest), never another model of the family (gpt-4o does not price gpt-4o-mini); a router's vendor-prefixed name (openai/gpt-4o) matches the bare name on any provider. Register the base model once; cloud model IDs find it:
- Amazon Bedrock (provider
aws.bedrock, fromwrapBedrockorwrapAnthropic(client, { provider: 'aws.bedrock' })):anthropic.claude-sonnet-4-5-20250929-v1:0, inference profilesus.,us-gov.,eu.,apac.,jp.,au.,in.andglobal.in front of it, and other vendors (amazon.nova-pro-v1:0→nova-pro). The profile, then the vendor prefix, is dropped; a price registered for the full ID still wins. - Vertex AI:
claude-sonnet-4-5@20250929→claude-sonnet-4-5(an@revisionis a version suffix). - Gemini: the Gemini API (
gcp.gemini) and Vertex AI (gcp.vertex_ai) are priced separately, so register each provider you call.googleandgoogle.vertexare accepted aliases: a price forgooglepricesgcp.geminicalls, one forgoogle.vertexpricesgcp.vertex_aicalls. A price with no provider prices every provider. - Azure OpenAI deployment names are your own, so map them explicitly. Calls keep the deployment name; only the price lookup uses the base model.
const openai = wrapOpenAI(new AzureOpenAI({ deployment: 'support-prod' }), {
provider: 'azure.ai.openai',
});
configure({ azureDeploymentModels: { 'support-prod': 'gpt-4o' } });Never guessed: an Azure deployment without a mapping, a Bedrock profile or vendor. prefix on any provider but aws.bedrock, and another model of the family (anthropic.claude-sonnet-4-5-mini-v1:0 is not claude-sonnet-4-5). On equal names, a price for the call's provider beats one for its alias, which beats one with no provider. Tier multipliers, long-context rates and server-tool fees: Cost.
Other frameworks
await aiInteraction({ userId, conversationId }, async (interaction) => {
const res = await myLlm.complete(prompt);
interaction.recordCall({
provider: 'mistral_ai',
model: res.model,
inputTokens: res.usage.in,
outputTokens: res.usage.out,
});
});inputTokens includes cached and cache-write tokens; see LlmCall for every field. For frameworks with their own lifecycle hooks, startInteraction(options) creates an interaction without entering it: run the work in interaction.run(fn) and call interaction.end().
Identity
Every event needs userId or anonymousId. Pass them to aiInteraction, or set them once per request with aiContext({ userId, accountId, ... }, fn); nested contexts inherit. Runs with neither use anonymousId: 'ai_system'.
Request middleware
When the browser runs the RudderStack JavaScript SDK (v3), its cookies give server-side AI events the browser's anonymousId and session, so they join the same user journey. Add the middleware (no framework dependency):
import { aiContextMiddleware, withAiContext } from '@rudderstack/ai/middleware';
app.use(aiContextMiddleware()); // Express, Connect
export const POST = withAiContext(async (request: Request) => handle(request)); // Next.js App Router
serve({ fetch: withAiContext(app.fetch) }); // Hono, or any Fetch-style handlerWithout middleware, pass request (an IncomingMessage, a Fetch Request, anything with a cookie header) or cookies (a raw Cookie header or a name-to-value map, for queues and WebSockets) to aiInteraction, startInteraction or aiContext.
| Cookie | Becomes | Rule |
| ----------------- | ------------------- | --------------------------------------------------------------------------- |
| rl_anonymous_id | anonymousId | Unless set explicitly |
| rl_session | context.sessionId | Session ID only; none once the session has expired |
| rl_user_id | userId | Fallback only: an explicit or context userId or anonymousId always wins |
- Precedence: interaction options, then
aiContextvalues, then cookies. Acontext.sessionIdyou set wins too. rl_user_idafter logout: the cookie stays until the browser SDK'sreset()runs. If you log users out server-side without callingreset(), the next person on that device is attributed to the previous user. Callreset()on logout, or passidentityFromCookies: falseor an explicitanonymousIdfor signed-out requests.- Only
rl_anonymous_id,rl_user_idandrl_sessionare kept; unreadable cookies are skipped; legacy v1.1 (RudderEncrypt:) cookies are not supported. Opt out withconfigure({ identityFromCookies: false }).
Background agents
For LLM work with no user in front of it (a schedule, webhook, Slack mention, queue message or another agent) use aiTask instead of aiInteraction:
await aiContext({ accountId: job.workspaceId, onBehalfOf: job.createdBy }, () =>
aiTask('alert-triage', { triggerSource: 'schedule' }, async () => {
const verdict = await anthropic.messages.create({
model: 'claude-haiku-4-5',
max_tokens: 500,
messages,
});
await aiTask('draft-status-update', {}, () => draftUpdate(verdict)); // a sub-agent, chained automatically
}),
);- The system is the actor: task events have no
userId(anonymousId: 'ai_system') and never inherit the person of an enclosing interaction, context, cookie or parent span. Put the customer inaccountIdand the human the work is for inonBehalfOf. Always set a stable, scopedconversationIdfor bots and jobs; using only the sharedai_systemidentity can merge unrelated traffic (cookieless bot example). - Chaining: inside another interaction or task,
parent_interaction_id,conversation_idandtrigger_source: agentdefault from it. PassparentInteractionIdto link a run started elsewhere, ornullfor none. - Flush: a top-level task flushes every client when it ends, so a cron script or Lambda can exit; a chained sub-agent does not (
flush: true/falseoverrides). - No prompt event, and no classification unless you pass
classify: true. - Waiting for an approval or a person:
task.pause({ reason: 'approval' })sends apausedanswer for the work so far and returns a JSON snapshot; pass it asresumeto theaiTaskthat continues, in any process. The final answer carriespause_countandtotal_paused_ms(Pauses and resumes, example). configure({ emitTaskStarted: true })also sendsai_task_startedwhen a run starts, so runs in flight or abandoned show up.
pause() called from the same interaction's SDK callback returns undefined and reports pause_refused with reason: in_callback to onError (one warning without it). This includes credits/retries, analytics track, redactors, content getters/serializers, and event rules. The interaction is unchanged and credits are kept; pause never throws. onError, application/task code, and callbacks for other interactions may pause normally. The shared pricing-wait bound is 5 s (pricing_in_flight on expiry); Node's synchronous pricing cannot reach that path.
MCP servers
For an MCP server built on either MCP TypeScript SDK line, @modelcontextprotocol/sdk 1.x or @modelcontextprotocol/server 2.x (McpServer or the low-level Server), call wrapMcpServer once, before connect(). On 2.x, wrap each server your createMcpHandler or serveStdio factory returns. Tools stay untouched:
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { wrapMcpServer } from '@rudderstack/ai/mcp';
const server = new McpServer({ name: 'workspace-mcp', version: '1.4.0' });
server.registerTool('create_audience', { inputSchema }, createAudience);
wrapMcpServer(server, {
analytics,
// The OAuth subject is the user, a workspace claim the account.
identify: (auth) => ({
userId: auth?.extra?.sub as string,
accountId: auth?.extra?.workspace_id as string,
}),
eventRules: { tools: { create_audience: 'audience_created' } },
requestContext: { intents: ['debug_delivery', 'build_audience'] },
});
await server.connect(transport);- Events:
mcp_client_seen(once per client name, OAuth client and user perclientSeenWindowMs, default 24 hours),mcp_tool_called(status, error type, duration, argument names, invalid arguments, retries, result size),mcp_elicitation_completed,mcp_resource_read,mcp_prompt_usedand your declared tool events (names starting withai_ormcp_are reserved). Never arguments, results, resource contents, prompt text or elicitation answers. - Both SDK lines: 1.x serves the
initializehandshake revisions (2025-06-18, up to 2025-11-25; client details frominitialize,Mcp-Session-Idasmcp_session_id); 2.x serves those and the stateless 2026-07-28 (client details from each request's_meta,mcp_client_seenafter the first successful request, elicitation by aninput_requiredresult and the client's retry). Same options and events on both. Transport (stdio,streamable_http,sse) is detected. - Identity:
identify(authInfo)maps the transport's verified auth info touserId,accountIdand OAuth details, once per request; it may be async. If it throws, the request is anonymous (ai_system).oauth_client_idandauth_methodaccompany every request event, including declared tool events. The token and client IP are never sent. - Joins:
com.rudderstack/interaction_idand the W3Ctraceparent(elsecom.rudderstack/trace_id) in a request's_metabecomeinteraction_idandtrace_id, so a call joins the agent's answer that made it; no other_metakey is read. On the agent side, the OpenAI Agents SDK'stoolMetaResolver: rudderStackMcpToolMeta()sendscom.rudderstack/interaction_idalways,com.rudderstack/trace_idonly when the interaction has atrace_id, andtraceparentonly withlinkTraceId: trueand an active span in that trace. By default neither trace key is sent (details). - Why it was called: off by default. Opt in with
requestContext: trueor an options object such asrequestContext: { intents: ['debug_delivery'] }. This adds an optionalrequest_contextargument (intentfrom your list,user_sentiment;call_reasonwithcaptureContent, masked, at most 200 characters) to each tool's schema and removes it before the tool runs. Withfalseor no option, no schema is added and client-sentrequest_contextpasses through unchanged. A high-levelMcpServertool that declares its ownrequest_contextalways keeps it. On a low-levelServer,request_contextis a reserved argument name: a tool's ownrequest_contextis kept only once the SDK has seen the tool in atools/list; name tool arguments something else. - State is in memory, per server name, per process: the
mcp_client_seenwindow, remembered clients, the call counters and pending elicitations survive servers rebuilt per request, at most 10,000 entries each (argument hashes forretry_count: the latest 1,000 per session or interaction). Give each distinct server a unique name. Replicas and restarts each emit their ownmcp_client_seenand restart their counters. - Stateless client attribution: request events use the client name and version remembered from the latest successful
initializefor the same account, OAuth client id and user identity (userId, elseanonymousId), per server name, per process, after request metadata, connection/session state andresolveClient. SetclientInfoFallback: (ctx) => ({ name, version })to supply client details only when all earlier sources, including the remembered client, provide no name or version. Without one (or when it returns nothing), HTTP requests fall back to theUser-Agent: known clients by their own initialize name, anything else asother; the raw header is never sent. It sharesresolveClient's context, error swallowing and statelessmcp_client_seenbehavior. The TTL isclientSeenWindowMs(default 24 hours); 0 disables remembering. One user running two clients under the same OAuth client can be attributed to whichever initialized last.mcp_session_idis still absent on stateless endpoints. - Why it failed: with
captureContent, failed tool calls, resource reads and prompt gets carryerror_messagefrom the tool's error text or the JSON-RPC error message, masked, at most 200 characters, withheld if it still looks sensitive. - Opt-in:
feedbackRequests: { capabilities: [...] }addssubmit_feedback(mcp_feedback_submitted) for problems, missing capabilities and positive feedback. DeprecatedcapabilityRequests/request_capability: usefeedbackRequests; enabling both throwsTypeError.mcpEvents: trueenables the experimental MCP Events helpers (trackMcpEventSubscription,wrapMcpEventSender).
MCP event tool, prompt, argument and capability names must be registered or known, or become unknown; request IDs are decimal strings, sha256: hashes or unknown; client labels are cleaned and capped at 64 code points; and counters, remembered clients and pending continuations are isolated by the raw account, user and session.
Options, every event and both protocol revisions: docs/mcp.md. Runnable servers over stdio and Streamable HTTP: examples/mcp-server (McpServer), examples/mcp-server-lowlevel (low-level Server) and examples/mcp-server-v2 (SDK 2.x, both protocol revisions); an agent joined to its server: examples/openai-agents-mcp.
Product signals
Feedback
trackAction({ userId, interactionId, conversationId, actionType, actionDetails }) sends ai_user_action (quick start). actionType is one of feedback_given, feedback_retracted, feedback_dismissed, copied_response, shared, exported, reported, regenerated, accepted, rejected, edited (the user kept, discarded or changed an AI suggestion or artifact) and clicked_through (with card_kind and target_type in actionDetails). Send feedback_retracted with the same feedback_type when a user takes feedback back: the latest event per interaction_id is the final state. interactionId and conversationId are required (else the event is dropped with a warning); for a one-shot interaction, pass its ID as both. action_details.feedback_text is content, sent only with content capture on. When the client app (web or mobile) sends its own copy of these events (source: "client"), configure({ serverFeedback: false }) turns the server copy off; see client events.
Scores
trackScore({ interactionId, conversationId, evaluationName, scoreValue, scoreLabel, evaluator }) sends ai_interaction_scored for a score from elsewhere (a human review, an offline judge); evaluator is model, code or human. To score every successful answer as it happens, pass your own function: configure({ evaluator: async (turn) => ({ evaluationName: 'groundedness', scoreValue, evaluator: 'model' }) }). It runs after the answer is out and never blocks it. Details: docs/events.md.
classifyError(error) from @rudderstack/ai returns the same ErrorType an interaction ended by that error records: rate_limit, timeout, api_error, context_limit, cancelled, auth_error, invalid_request, connection_error, run-limit types, or app_error for ordinary application failures. Provider errors in retry/cause chains keep their type. The shared case table is classify-errors-v0.1.json.
Intent classification
trackClassification({ interactionId, conversationId, intent, outcome, classifierModel, classifierDurationMs, classifierCostUsd }) sends ai_interaction_classified from your own pipeline for any interaction, including errored, cancelled or finished turns. It uses the same identity and context options as trackScore. See Send your own classification.
Opt-in. After each successful answer of an interaction you opened (aiInteraction, startInteraction, a task with classify: true), your own model client labels it with one of your intents and an outcome, sent as ai_interaction_classified. Nothing waits for it.
configure({
classifier: {
client: new Anthropic(), // or an OpenAI client; your key, your provider; its calls are never tracked
model: 'claude-haiku-4-5',
intents: ['refund_request', 'order_status', 'bug_report'],
},
});
// Or your own function: configure({ classifier: { classify: async (turn) => ({ intent, outcome }) } })The classifier hook skips calls outside any interaction and interactions an integration opened on its own (a LangChain run or trackedQuery turn outside aiInteraction): wrap the request in aiInteraction to get labels, or pass classify: true to trackedQuery. aiInteraction({ classify: false }) skips one. intent is other and outcome is unclear when the label is not in your lists, so both values are always possible, even with your own intents and outcomes. An interaction with neither prompt nor answer text is skipped with a warning: classification needs prompt or answer text (promptText, or captureContent for the answer). Input, limits, cost and privacy: docs/events.md.
Declared tool events
Turn tool calls into your own product events (a ticket created, a memory saved):
configure({
eventRules: {
tools: {
save_memory: 'memory_captured',
create_ticket: {
event: 'ticket_created',
properties: (args) => ({ priority: (args as { priority: string }).priority }),
},
},
},
});Each call sends one track event with tool_name, tool_call_id, tool_status, tool_duration_ms, the interaction's IDs and whatever properties() returns; tool arguments and results are never sent otherwise. If properties() throws, or its output takes the event over the 30,000-byte budget, the event is sent without it; if when() throws, the event is not sent. Names starting with ai_ or mcp_ are reserved and throw at configure(). Details: docs/events.md.
Tool breakdown
configure({ toolBreakdown: true }) adds multi-agent-safe tool_breakdown entries to ai_response_received: agent and MCP identity, call/error counts by fixed category, and partial/max measured durations where observable. Nested tool durations are inclusive (details).
Multi-agent
usage_breakdown has one entry per agent, provider and model, and tool_breakdown one per agent, MCP server, tool and parent tool, so the same model or tool used by several agents stays apart. Agents are named by:
- LangChain.js / LangGraph.js:
agent_name/lc_agent_namerun metadata (Deep Agents subagents set it), anagent:<name>tag, the parent run's agent, the handler'sagentName, else the root run's name (a LangGraph graph or Deep Agents agent). A tool run inside another tool run (a Deep Agents subagent insidetask) has that tool asparent_toolintool_breakdown. - Claude Agent SDK: a subagent's calls and tools take the
subagent_typeof theTask/Agentcall that launched it, and its tools carry that call's name asparent_tool; calls and tools without a derived subagent name use the run'sagentName, when supplied. Each model's tokens and cost still add up to the SDK'smodelUsage: a subagent's answer, which is not streamed, counts from its tool result's usage; when the streamed messages still fall short, the main loop keeps the result's own usage and the subagents share the rest, and a model's cost is split between its agents by Claude's price ratios. - Vercel AI SDK middleware,
recordCallandrecordToolCall: theagentNameyou pass.
Every usage_breakdown entry has cache_write_tokens (summed in total_cache_write_tokens) and error_count (failed calls, retries included). Nested aiTasks report separately; roll a run tree up by parent_interaction_id (query).
Privacy
Sent by default: IDs, models, token counts, latency, cost, status, tool names. Never sent by default: prompt, answer and feedback text, tool arguments and results, traits.
Custom properties named prompt_text, response_text, feedback_text, intent_summary, explanation, call_reason or capability_detail are dropped while content capture is off, with one warning per name. Use another name for non-content metadata.
configure({ captureContent: true }) (or per interaction) adds prompt_text (from promptText), response_text and action_details.feedback_text, and, with emitLlmCalls, each call's input_messages, output_text and output_tool_calls. Captured text, and the classifier's intent_summary are masked before they leave the process:
| Pattern | Becomes |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| Email addresses | [email] |
| Phone numbers: + and 9-15 digits, or 10-12 digits in common groupings | [phone] |
| Payment card numbers that pass the Luhn check | [card] |
| IPv4 and IPv6 addresses | [ip] |
| PEM private keys, API keys and tokens (sk-, Stripe sk_live_/rk_live_, Google AIza and ya29., Slack, GitHub, AWS, JWTs, Bearer), passwords in connection URLs, values of api_key=, token=, password= and similar | [secret] |
| US Social Security numbers | [ssn] |
| IBANs (checksum-validated) | [iban] |
configure({
captureContent: true,
redact: (text) => text.replace(/\b(?:Mr|Mrs|Ms)\. [A-Z][a-z]+/g, '[name]'), // runs after the built-ins; synchronous
});- Limits: patterns catch fixed shapes only. Names, postal addresses and free-form IDs are not caught; some order numbers look like phone numbers and get masked. Use the hook, or leave capture off.
- Fail closed: if the hook throws or returns a non-string, the field is dropped. Text over 32,000 characters is withheld rather than masked.
redact: falseturns masking off;redact: truerestores the built-ins only. Both SDKs share the patterns (spec/fixtures/redaction-v0.1.json).maskText(text): string | undefinedapplies the built-ins to text you send yourself, such as a declared tool event'sproperties, which are sent as returned.- Keep personal data in RudderStack
identifycalls, not in AI events: theuserIdon every event joins it to that profile.
Serverless and workers
The RudderStack client batches in the background. Before a script, queue worker or serverless handler exits:
const done = await flush(); // false if it ran out of time (flush_timeout) or your client's flush failed (flush_failed)flush() waits for pending classifications and evaluations, then sends everything queued in every RudderStack client the SDK has used (configure()'s and those given to interactions, contexts, wrappers, handlers and tracing) until their queues are empty, all within one flush({ timeoutMs }) (default 10 s). A data plane that never answers cannot hang the handler. It never throws. Because it drains your client's queue, your own client.flush() afterwards has nothing left to fail on: when your client's flush fails, the SDK passes your client's error, unchanged, to onError as flush_failed (from flush(), shutdown(), aiTask and tracing forceFlush(), including an error that arrives after the deadline), so handle flush errors there. flush() and shutdown() then resolve false; aiTask keeps its own result and forceFlush() resolves undefined (Errors). A top-level aiTask flushes for you, waiting at most 2 s (aiTask(name, { flush: { timeoutMs } }, fn) changes it, flush: false skips it).
Production
- Shutdown.
shutdown({ timeoutMs })stops queueing new classifications and evaluations, ends every open interaction asresponse_status: incompletewithend_reason: shutdown, then flushes. It never closes your RudderStack client. The SDK installs no signal handlers, so call it from yours:process.once('SIGTERM', async () => { await shutdown(); process.exit(0); }). - Process exit. With
flushOnExit(on by default), a process whose event loop empties (beforeExit) with events sent since the last flush flushes for at most 2 s first.configure({ flushOnExit: false })turns it off. - Serverless. AWS Lambda:
await flush()before returning. Vercel:waitUntil(flush()). Cloud Run and containers:shutdown()on SIGTERM. - Client. Use
@rudderstack/rudder-sdk-node3.0.16 or later. Older versions slow down bursts of events (the SDK warns once, asclient_outdated). For bursty servers, setflushAtto 100–200 so each request carries more events. - Overhead. The SDK adds about 45 µs to an interaction with one wrapped model call on a 2-vCPU CI runner (17 µs on a laptop), against hundreds of milliseconds for the model call itself, and about 25 µs to an MCP
tools/call. Budget, measurements, load test and limits. - Memory and errors. Limits keep memory bounded. Errors explains
onError: nothing the SDK does throws into your code.
Events
| Event | When |
| --------------------------- | --------------------------------------------------------------------------------------------- |
| ai_user_prompt_created | A user-triggered interaction starts (sent when its first model call starts) |
| ai_response_received | The interaction ends: status, models, tokens, cost, latency, tool counts |
| ai_user_action | trackAction: feedback, copy, share, report, regenerate, accept, reject, edit, click-through |
| ai_interaction_classified | From the classifier hook or trackClassification, with intent and outcome |
| ai_interaction_scored | One per score: from your evaluator, or trackScore |
| ai_limit_reached | trackLimitReached: a user or account hit a usage limit of your AI feature |
| ai_llm_response_received | One per model call, only with emitLlmCalls: true (do not sum it with the totals) |
| Your declared tool events | One per call of a tool listed in eventRules |
| mcp_* events | From a server wrapped with wrapMcpServer (MCP servers) |
Every event carries interaction_id and, when set, conversation_id, feature and surface (where the user met the AI: web, slack, api...; set it on aiContext or the interaction), plus context.wrapperLibrary with the integration and specVersion 0.4.0. response_status is success, error, timeout, cancelled, paused (with pause_reason), blocked (the app declined to answer, with block_reason: interaction.end({ status: 'blocked', blockReason: 'guardrail' })) or incomplete (stopped at a cap: error_type max_turns, max_budget_usd or length); a last answer cut off at the output-token limit is incomplete, a filtered one (content_filter) error. trace_id is sent only when you pass one (traceId, setTraceId()) or link spans with linkTraceId: true. An event's properties are kept within 30,000 bytes (RudderStack rejects events over 32 KiB): an oversized event drops captured text first, then tool_breakdown and usage_breakdown entries from the end; a declared tool event drops its properties() output.
With emitSpans, retained provider call events also carry a matching span_id (overflow aggregates omit it). Standalone manual spans capture the start context’s identity, falling back to anonymousId: "ai_system". Raw asResponse() paths finish only the wrapper span with HTTP status, without parsed usage or content; withResponse() observes parsed data. With emitLlmCalls, every ai_llm_response_received carries call_index (1-based within the interaction). With both emitLlmCalls and captureContent it also carries input_messages (system prompt, history and tool results sent on that call), input_truncated, output_text and output_tool_calls. This is personal data: it is masked like prompt_text and the redact hook applies; an oversized input drops the oldest messages after the system prompt first. Details: docs/events.md.
Sample payloads, every property, error types and context.wrapperLibrary: docs/events.md. Schema: spec/ai-events-v0.4.schema.json; tracking plan: spec/rudderstack-catalog/.
Configuration
configure() changes only the keys you pass; an invalid eventRules, evaluator, azureDeploymentModels or redact throws and changes nothing.
| Option | Default | Meaning |
| ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| analytics | none | Default RudderStack client (anything with track(message)); a client passed to an interaction, context or wrapper wins; null clears it |
| prices | none | { model: { inputPerMtok, outputPerMtok, ... } } in USD per million tokens, merged into the registered prices (registerPrice, clearPrices) |
| azureDeploymentModels | none | Azure OpenAI deployment name → base model, for pricing only; replaces the previous map |
| captureContent | false | Send prompt, answer and feedback text (masked); or per kind, see Content capture |
| redact | true | Masking: true (built-ins), false (off), or a (text) => string hook run after the built-ins |
| identityFromCookies | true | Read identity from RudderStack JavaScript SDK cookies of a request / cookies input |
| toolBreakdown | false | Add tool_breakdown to ai_response_received |
| emitLlmCalls | false | Also send ai_llm_response_received per model call |
| emitSpans | false | Send provider wrapper chat spans and manual span() operations, independently of emitLlmCalls; see tracing. |
| eventRules | none | { tools: { name: rule } }: declared tool events; replaces earlier rules; null clears them |
| classifier | none | Intent classification: { client, model, intents, outcomes, intentSummary, timeoutMs } or { classify, ... }; null: off |
| evaluator | none | Your scoring function, run after each successful answer; null: off |
| serverFeedback | true | false: trackAction sends nothing (the client app sends ai_user_action) |
| onError | none | (error, { kind, where }) => void for failures the SDK contained; default: one console.warn per kind, never the error message |
| limits | see docs | Memory limits: maxOpenInteractions (10000), interactionTtlMs (1 h), maxCallsPerInteraction (1000), maxMapEntries (10000); see Limits |
| flushOnExit | true | Flush for at most 2 s on beforeExit when events were sent since the last flush |
| sampleRates | none | { event_name: rate }: send that share of each event, keyed on interaction_id; kept events carry sample_rate (Sampling) |
Per-interaction overrides, client precedence, cost rules, warehouse column types and the API reference: docs/configuration.md.
Advanced: OpenTelemetry export
Three setups: product only (the default), traces only (your OpenTelemetry instrumentation and registerTracing()), or both (configure({ emitSpans: true })); see choose a setup. To send each AI span from your OpenTelemetry instrumentation to RudderStack as well, or to build product events from spans instead of wrapping clients, see docs/tracing.md. With emitSpans and the span processor together, each model call is still sent as one span. The span events join ai_response_received on interaction_id; trace_id is set from the spans only when you register the processor with linkTraceId: true (the join).
Checking a migration
When you move an app's own AI events to this SDK, record what the app sends and check it. In the harness or test that drives the app, make the recorder the app's own RudderStack client, wherever the app builds it and before configure() runs, so legacy calls are recorded too:
import { configure } from '@rudderstack/ai';
import { Recorder } from '@rudderstack/ai/testing';
// instead of new Analytics(writeKey, options): every track, identify, page, screen, group and alias
// call is appended to the file as one JSON line
const analytics = new Recorder('events.jsonl');
configure({ analytics });The recorder creates the file in the current folder, where it's easy to commit by accident: record outside the repo (for example in a temp folder) or add the capture file to .gitignore.
Then drive the app and check the capture, or compare a capture with the AI events switched off (before.jsonl) with one switched on, for the PR description:
npx @rudderstack/ai check events.jsonl --expect-legacy chatTurnCompleted --feature support_bot --expect-joins
npx @rudderstack/ai what-changes before.jsonl after.jsonlcheck validates every AI event against the spec schema this package emits and the client-event schema, and checks legacy events, client and server copies of each turn, identity, content capture and MCP events. Useful flags (--help lists them all; repeat list flags once per value):
| Flag | Checks |
| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| --expect-legacy <event> / --absent <event> | A legacy event is still sent / is no longer sent (its switch is off) |
| --no-ai-events | Captured with the AI events switch off: no AI event may appear |
| --feature <value>, --surface <value>, --user-id <id>, --mcp-user-id <id> or --mcp-anonymous | Allowed feature and surface values, the userId on the user's turns and server feedback, the identity on every MCP event |
| --expect-joins, --client-surface <[feature:]surface>, --client-opt-out <copy>, --feedback-endpoint <[[feature:]surface:]type> | Every browser copy joins its server event, feedback per action type and count (only for those surfaces; opted-out copies must not be sent) |
| --failed-interaction <id> | A turn the app failed and caught reports the failure |
| --capture-content | The plan captures prompt and response text (else any text sent fails) |
Exit code 0: pass, 1: a check failed, 2: bad usage or an unreadable file. what-changes prints an event table and a redacted before/after pair per changed event (IDs, emails and traits redacted; review the rest before sharing). Both commands work on any capture, with or without an agent skill; the Python (python -m rudderstack.ai.check) and Go (aicheck) SDKs ship the same command, which prints the same lines.
Troubleshooting
| Symptom | Cause and fix |
| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No events, warning no RudderStack client | No client anywhere: call configure({ analytics }). |
| Events missing from a Lambda or script | The process exited before the client sent its batch: await flush(). |
| One answer split into many | Calls ran outside aiInteraction, a stream was read after it ended, or a LangChain handler is on the model constructor. Wrap each user turn; return or bind streams. |
| No total_cost_usd | The provider/gateway reported no cost and a model is not priced (see Cost), a call failed or was cancelled, or a streamed OpenAI-compatible call had no usage. |
| No ai_interaction_classified | No classifier, an interaction the SDK opened itself, an answer that failed, or a classifier error (logged once). |
| Cost column is an integer in the warehouse | The first loaded value was 0: see warehouse column types. |
| No trace_id | It is opt-in since 0.5.0: pass traceId / setTraceId(), or register the span processor with linkTraceId: true. |
| Prompt event arrives late | It is held until the first model call starts, so it carries that call's integration; it keeps its original timestamp. |
| Declared tool event without its properties | properties() threw, or its output took the event over the 30,000-byte budget (warning logged). |
Set RUDDERSTACK_AI_DEBUG to any non-empty value (read on every log call) to log everything tracking drops or ignores with console.debug, prefixed [rudderstack-ai]: errors by type only, never event payloads or captured text. Warnings (console.warn, same prefix) print without it, most once per process. Tracking never throws into your code: failures it contained go to configure({ onError }) when set (Errors).
Compatibility
| Package | Supported | Tested in CI |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------ |
| Node.js | >=24 | 24, 26
