/rudder-ai-events:rudder-ai-events-instrumentfrom rudder-ai-events
Instruments AI events using RudderStack SDKs from an approved plan: installs packages, wraps model clients and MCP servers, wires feedback and browser events.
Ships in rudder-ai-events. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Turns the approved plan into the smallest reviewable diff, for AI events spec v0.4. Recipes with exact code: references/node.md, references/python.md, references/go.md, references/client-events.md. Full API: each SDK's README (npm package, PyPI page, Go module).
ai-events.md exists at the repo root with front matter status: approved. Missing or draft: stop and run rudder-ai-events-setup; never instrument from an unapproved plan. Copy every value from the fenced yaml block under ## Config (it wins over the prose); the files you may touch are the ones under ## Files to change. Key paths below (spec.config, surfaces[], sdks[], spec.switches) are inside that block, under spec.status: instrument. Skip the rest (skipped, blocked, unsupported).ai-events.md, the working tree is clean, or the user agreed to mix changes. Work on the current branch; on the default branch, create the branch the plan's ## Summary names (feat/ai-events by default) without asking.sdks[].version (<VERSION> in the recipe files) is @rudderstack/ai / rudderstack-ai 0.8.0 or later, or ai-sdk-go v0.4.0 or later (verify needs their migration check and recorders); never a branch or pseudo-version. Older: run rudder-ai-events-setup, which re-resolves versions on resume. A user-named unreleased exact target stays in the plan, but installation waits for publication. Browser-only plans have sdks: []: skip server install/configure steps and consume the named server dependency's response contract and switch source.Before writing code, check that the pinned version installs as is:
devEngines, npm view fails with EBADDEVENGINES): npm view @rudderstack/ai version, pip index versions rudderstack-ai, go list -m -versions github.com/rudderlabs/ai-sdk-go (each Go integration module, .../rudderopenai, .../rudderotel, ..., has its own tags). Newer than the plan: say so in one line and install the plan's version.minimumReleaseAge (minutes) / minimumReleaseAgeExclude (pnpm-workspace.yaml), npm min-release-age / before (.npmrc), uv exclude-newer (pyproject.toml [tool.uv], uv.toml). A gate that blocks the version: add the exemption the plan's ## Dependencies and blockers lists (only the SDK package, with a comment that says why and the removal date); a gate the plan does not list is a plan change..npmrc, pip index-url, uv indexes, GOPROXY) must serve the version. The SDKs are public on npm, PyPI and proxy.golang.org: no GOPRIVATE, no git credentials. Expired registry auth: ask the user to log in, never write tokens.@rudderstack/ai needs @rudderstack/rudder-sdk-node >=3.0.16 (npm fails with ERESOLVE on older). When the plan's ## Dependencies and blockers approves upgrading the app's client, install that exact pin together with the SDK; an upgrade the plan does not list is a plan change for the user. Never --legacy-peer-deps or --force.sdks[].runtime (the go line of the pinned version's go.mod). An app below it gets its go line raised by go get: name that in ## What changes; a toolchain its CI cannot run is a blocker.Only the main agent runs package-manager commands. Subagent briefs forbid all of them, including commands that can install as a side effect (npx, pnpm dlx, uv run, go run of a new module, test scripts with an install step); subagents edit code only.
Do one surface at a time; after each, run the app's type check (and its tests when they are fast).
Install the SDK in each sdks[].path with an exact pin, using the repo's package manager (pinned version in packageManager / tool files):
npm install --save-exact @rudderstack/ai@<VERSION>
deno add npm:@rudderstack/ai@<VERSION> # peers: deno add npm:<package>@<approved exact version>
uv add "rudderstack-ai[<extras from the plan>]==<VERSION>" # e.g. rudderstack-ai[anthropic]==<VERSION>
go get github.com/rudderlabs/ai-sdk-go@<VERSION> # plus one module per provider at its own version
Other managers: section 1 of the recipe files. Never add a version range, and bump the app's own LLM libraries or their peers only to exact pins approved under Dependencies and blockers. Add the RudderStack server client (@rudderstack/rudder-sdk-node, rudder-sdk-python, analytics-go/v4, at its latest release) only when the plan says client: new, and upgrade an existing one only to the exact version ## Dependencies and blockers approves. Then git diff the lockfile: only the SDK, approved dependency bumps and what they pull may change. Deno uses the project's configured lockfile, if locking is enabled; install every approved peer with deno add npm:<package>@<approved exact version>. pnpm drops the tarball: URL from unrelated resolution entries (packages from a registry with a non-default tarball path, such as a private one) on every install, whatever its version: restore them rather than stopping, keyed by integrity, from a copy of the lockfile taken just before the install (not HEAD, which misses the user's uncommitted edits):
cp pnpm-lock.yaml "${TMPDIR:-/tmp}/pnpm-lock.before.yaml" # before pnpm add
# ...pnpm add --save-exact @rudderstack/ai@<VERSION>...
python3 - "${TMPDIR:-/tmp}/pnpm-lock.before.yaml" pnpm-lock.yaml <<'PY'
import re, sys
tarballs = dict(re.findall(r"integrity: (\S+?), tarball: (\S+?)\}", open(sys.argv[1]).read()))
lock = open(sys.argv[2]).read()
restore = lambda m: f"integrity: {m[1]}, tarball: {tarballs[m[1]]}}}" if m[1] in tarballs else m[0]
open(sys.argv[2], "w").write(re.sub(r"integrity: (\S+?)\}", restore, lock))
PY
Other unrelated churn (rewritten resolved URLs, reordered entries) means a different package-manager version: rerun with the repo's; if it persists, stop and show the user the churn.
Configure once in a module that runs before the first request or job: next to the RudderStack client, at module level, works when the app imports it at startup. configure({ analytics }) with the existing client (Go: rudderstackai.Configure(rudderstackai.WithAnalytics(client), ...)), plus the spec.config keys that are configure() options (Node.js camelCase, Go With* options). intents / outcomes go only into the classifier. captureContent stays false unless the plan says otherwise. Translate sample_rates to sampleRates / sample_rates / WithSampleRates, credits to the hook via credits / WithCredits, and emit_task_started to emitTaskStarted / emit_task_started / WithTaskStartedEvents; keep answers and client copies unsampled by default. Put it behind the AI events switch (step 13).
Wrap the model client or add the framework integration at its construction site, per the surface's integration. Call sites keep working unchanged. Apply planned surfaces[].call_options through the wrapper or manual-call options for call_purpose, fallback_used, byok (exact language names in the recipes); observed boundaries provide per-call timing. Calls no integration covers (Bedrock InvokeModel, other providers): recordCall / record_call / RecordCall inside the interaction (recipe section 3).
Chat surfaces: identity middleware (aiContextMiddleware, withAiContext, AIContextMiddleware, Django/Flask middleware; Go: rudderstackai.Middleware around the handlers, or rudderstackai.WithValues(ctx, ContextValues{Request: r, ...})) or request / cookies on the interaction; then one aiInteraction / ai_interaction / RunInteraction per user turn at the entry point. Wrap only the model-call part of the handler when the rest (history, legacy event, response) needs its result. Pass userId, conversationId, feature, surface, and interactionId when the plan's interaction_id_source is client (validated UUID) or app. One-shot surfaces (conversation_id_source: interaction_id): omit the explicit and context conversation ID, set oneShot: true (one_shot=True, OneShot: true) so it defaults to the interaction ID, with inputMethod: 'button' (input_method="button", InputMethod: "button"), and return it for the accept, edit and reject actions. Streams: return them from the callback or bind() them (Go: read them inside the RunInteraction function). Always return the ID the interaction used to the client.
App-detected failures (surfaces[].app_detected_failures): where an entry point catches its own failure and returns normally (an empty stream, its own deadline, a lost lease, a job runner that swallows errors), end the interaction there, inside the callback: interaction.end({ status, errorType }) (Python end(status=..., error_type=...), Go in.End(rudderstackai.EndOptions{Status, ErrorType})). Find these where the app already logs or counts the failure. At finalization on successful and failed turns, evaluate planned surfaces[].extra_properties and pass them through extraProperties / extra_properties / ExtraProperties on end() / End, inside the callback or stream before automatic finalization; preserve failure status and error type. Later ends are no-ops. Planned surfaces[].pauses with reported_by: app use pause({ reason }) / pause(reason=...) / Pause(PauseOptions{Reason: ...}); resume() / Resume() continues in process, or persist the JSON snapshot and pass resume / Resume on another worker (same configured rates). Each pause sends segment totals; the final answer adds pause_count and total_paused_ms; integration-reported pauses need no duplicate event. Planned blocked ends use blockReason / block_reason / BlockReason, without error_type; denied tool calls use tool_status: denied. Never call noteOutcome. Without planned extras, an error the app's own code throws out of the callback needs no code: it reports error_type: app_error when no model call failed and nothing in the error names a provider, and the failed call's own type (api_error, rate_limit, ...) when one did.
Feedback endpoints (the plan's surfaces[].feedback): trackAction / track_action with interactionId, conversationId, surface and the action type; the browser sends its own copy too (step 9); client_events.opt_out: [server_feedback] means serverFeedback: false / server_feedback=False in configure(), not deleting the call; when the plan lists request_changes, extend the client request and the endpoint to carry those IDs. Keep the endpoint's existing behaviour; do not copy placeholder user IDs ('anonymous') from legacy code.
Background surfaces: one aiTask / ai_task / RunTask per run at the job's entry point with task_name, trigger_source (plus trigger_event_id for mcp_event), a stable scoped conversationId, accountId / onBehalfOf from the plan, and no user ID; one child task per planned child_tasks entry. Python thread pools: propagate(fn).
MCP servers (type: mcp): one wrapMcpServer / wrap_mcp_server / rudderstackai.WrapMCPServer (go-sdk) / ruddermcpgo.WrapServer (mcp-go) per endpoint, where its server is built and before it connects (for a server factory, inside the factory), with the plan's identify mapping, request_context intents, declared tool events and capability requests. Each endpoint gets a distinct server name (state is per name, per process); identify reads what that endpoint's auth put on the request. Stateless endpoints report no client_name, client_version or mcp_session_id except on protocol 2026-07-28 (known limit mcp_stateless_no_client). Tools stay untouched.
Client surface: a trackAi helper on the existing rudderanalytics instance, or catalog entries and generated calls when client_events.tracking.mode: generated, the interaction_id sent with each chat request, then the events listed in client_events in their UI handlers. By default that includes the client copies of the prompt and answer and of feedback (source: client), sent alongside the server's, never sampled, and carrying only what the browser saw; click-through is ai_user_action with action_type: clicked_through.
Flush: servers call the SDK's shutdown() (Go rudderstackai.Shutdown(ctx)) in the existing SIGTERM / shutdown hook, before the app's own client flush or close, which stays; it ends open interactions as incomplete, flushes within one deadline (10 s default) and never closes the client. Scripts, cron jobs and serverless handlers: flush() (Go Flush(ctx)) before returning; a top-level task flushes itself (2 s default). Both return false on timeout and never throw. Go: then client.Close(). They also drain the app's client and report its flush error to onError as flush_failed: an app that logs or alerts on its client's flush errors moves that into onError / on_error / WithOnError (recipe section 7).
Cost: for Claude Agent SDK resume, use the snapshot lifecycle in references/node.md, section 4 (Python uses usage_snapshot / usage_baseline with the same app-store lifecycle), and implement surfaces[].usage_baseline_source (persist per-session snapshot and pass the baseline, mark resumed with no durable baseline, or in-memory with a resumed fallback when the snapshot is missing). Register spec.config.prices and check estimateCost / estimate_cost / EstimateCost returns a value for each, Bedrock geo-prefixed IDs (us.anthropic.claude-... with provider aws.bedrock) included. spec.config.unpriced_models never block: tokens are still recorded, a TODO naming them goes at the price config, and known limit prices_missing applies to calls with neither registered prices nor usable provider-reported cost (no total_cost_usd until the customer adds their rates; verify uses dummy prices). Never take prices from anywhere but the plan or the customer.
Intents, outcomes and optional config per the plan only: labels_set_by: classifier configures the classifier (the app's own client and model; intents without other); app calls setIntent / setOutcome (set_intent / set_outcome, SetIntent / SetOutcome) with the app's own per-turn category or outcome, mapped to the plan's lists; none wires nothing. Apply surfaces[].agent_version_source / variant_source through context, interaction or task options; confidence_source uses setConfidence / set_confidence / SetConfidence, compaction_source uses recordCompaction / record_compaction / RecordCompaction, and limit_reached uses trackLimitReached / track_limit_reached / TrackLimitReached. For each write tool, generate a result-aware when / When predicate that suppresses successful no-ops (created: false, skipped, already, blocked), inspecting all success returns; apply it at every endpoint exposing the tool. Then eventRules, scores, price options, toolBreakdown, and trace_id per the plan's tracing: when another exporter owns the OpenTelemetry provider, pass the active trace ID as traceId / trace_id / TraceID and register no SDK span processor.
Switches from spec.switches, both default on and independent. ai_events_env off: a no-op RudderStack client in configure(), and no MCP wrap, SDK tracing, classifier or evaluator; wrapped clients and interactions stay and send nothing. The browser's trackAi sends through rudderanalytics, outside configure(): use client_events.switch_source when planned, else expose the effective ai_events_env value to the page the way the app already exposes its config or feature flags, and have trackAi send nothing when it is off (recipe: references/client-events.md, "Code"); the page's legacy calls stay untouched. legacy_events_env off: the old track() calls, kept as they are, are skipped. Read both through the app's config library; with reloadable: true, call configure() again when the AI switch changes (MCP wraps and tracing follow it only on restart). Recipe: "Switches" in each language file.
Browser-only: consume the server dependency's switch and returned IDs, implement local browser/catalog changes only, and gate local legacy events independently when present; no local configure() or server SDK. Apply surfaces[].response_changes in server repos; server_dependency.response_changes are prerequisites for the backend PR.
14. Refresh references: code comments cite the maintained code constant, not planning artifacts such as ai-events.yaml or ai-events.md; update path / symbol entries in ## Config and ## Surfaces that moved within the listed files; this keeps status: approved.
## Files to change plus manifests, lockfiles and new test files; match the file's style; no refactors.## Files to change sets front matter status: draft. Update the sections and ## Config, show the user only the plan diff, and get approval again before committing.await on delivery in request paths, no new error paths. The SDKs never throw into app code.identity. If code disagrees with the plan, it is a plan change (above).request_context itself. A server on an unsupported MCP SDK stays blocked.## Known limits) are not bugs to work around in app code; note them in the final message when they apply.New server-side tests, per server surface, run the entry point against a stub RudderStack client and assert the captured AI events, including every reachable non-success path and resumed-session cost. Use the real AI SDK through the entry point, and run these tests in CI (recipe: "Tests" in each language file; detailed cases in verify's checklist).
Deno: the first instrumented PR proves AsyncLocalStorage / node: context propagation and captured events under the repo's own deno test. Browser-only: browser tests assert generated or raw client events, returned-ID joins and the consumed switch.
The app builds, type-checks and its full test suite passes.
Run rudder-ai-events-verify yourself; do not offer it. Propose a commit or PR only after it reports PASS. If the user commits first, say plainly that verify has not run.
The final message to the user carries, ready to paste into a PR description: the plan's ## What changes, updated to what the diff actually does (verify regenerates it from captured payloads); the environment variable names per environment (write key, data plane URL, ai_events_env, legacy_events_env), never their values; rollback: set ai_events_env off to stop the AI events (and legacy_events_env back on if it was turned off), then revert the PR(s) to remove the code.
With server_dependency, land the server instrumentation and response contract PR first, then the browser PR in its own repo; record that order in the plan. Suggest stacked PRs: (1) the dependency, configure(), both switches, flush and the first surface (verify fails a capture with no AI events, and go mod tidy and unused-dependency checks strip a dependency without a use); (2) one PR per remaining surface group. Agree the split with the user and record it under ## Files to change (which surfaces each PR carries); it is part of the approved plan. Verify then runs per PR on the surfaces that PR and the earlier ones instrument, the switches and the legacy events included; later surfaces are n/a (later PR) in its report, and the last PR verifies the whole plan. Each PR body carries the ## What changes table built from that PR's captured payloads.
.env files, key files or secret stores. Reference keys only through the environment variable names in the plan.spec.config.capture_content is true. The browser sends prompt and feedback text only then, masked with the server's rules; never answer text or conversation titles.interaction_id is user input: accept it only when it is a UUID.references/node.md: install, configure (lazy client, mirrored context), wrappers, recordCall, Claude Agent SDK routes, chat, streaming, app-detected failures, tracing side effects, feedback, aiTask, shutdown / flush, event rules, classifier, scores, prices, switches, wrapMcpServer, tests.references/python.md: the same for rudderstack-ai, plus middleware, propagate, wrap_mcp_server and tests.references/go.md: Configure, rudderopenai / rudderanthropic / ruddergenai / rudderbedrock, Bedrock InvokeModel through RecordCall, RunInteraction, RunTask, TrackAction, Shutdown / Flush, rudderotel, switches, tests, and MCP servers on the official go-sdk (WrapMCPServer) and mcp-go (ruddermcpgo.WrapServer).references/client-events.md: who sends what, browser code on the existing JavaScript SDK, and where the client-event schema lives.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
3 skills in this plugin
/rudder-ai-events-setupOnboards an app to RudderStack AI events, including moving existing RudderStack LLM, chat or agent events to them: discovers chat, agent, browser and MCP surfaces and drafts ai-events.md. Use when adding @rudderstack/ai, rudderstack-ai or ai-sdk-go, or replacing custom AI tracking./rudder-ai-events-verifyVerifies RudderStack AI events locally and checks a move from existing RudderStack events: validates captures against the v0.4 schema, joins, switches and legacy events. Use when testing AI events, comparing old and new tracking, or when AI or MCP events look wrong or missing.npx claudepluginhub rudderlabs/rudder-agent-skills --plugin rudder-ai-eventsOther plugins' skills for the same job