Imported from amplitude/Amplitude-AI-Node (
AGENTS.md). Install upstream withnpx skills add amplitude/Amplitude-AI-Node. Copyright stays with the author.
AGENTS.md
Package: @amplitude/ai v0.16.0
Install
pnpm add @amplitude/ai
MCP Server Setup
The SDK ships an MCP server for AI coding agents. It provides project scanning, file validation, instrumentation, test generation, and the complete API reference.
Cursor
Add to .cursor/mcp.json in your project root:
{
"mcpServers": {
"amplitude-ai": {
"command": "npx",
"args": ["amplitude-ai", "mcp"]
}
}
}
Then point the agent at the instrumentation guide: node_modules/@amplitude/ai/amplitude-ai.md
Claude Code
claude mcp add amplitude-ai -- npx amplitude-ai mcp
Then point the agent at the instrumentation guide: node_modules/@amplitude/ai/amplitude-ai.md
OpenAI Codex CLI
Add to ~/.codex/config.toml:
[mcp_servers.amplitude-ai]
command = "npx"
args = ["amplitude-ai", "mcp"]
Codex auto-reads this AGENTS.md file for context.
Generic (any MCP-compatible agent)
{ "amplitude-ai": { "command": "npx", "args": ["amplitude-ai", "mcp"] } }
Decision Tree
- Default: use
ai.agent(...).session(...)with provider wrappers — gives you every event type, per-user analytics, session enrichment, quality scoring. - Already have a provider client: use
wrap()to instrument it. - Multiple agents collaborating: use
session.runAs(childAgent, fn)for automatic identity propagation. - Need tool telemetry: use
tool(). - Need span/observability: use
observe(). - Cannot modify call sites at all: use
patch()for aggregate-only monitoring (no per-user analytics). - Already emit OTEL GenAI spans: use
AmplitudeAgentExporter({ amplitudeAI: ai })(orenableOtel()) to map them to [Agent] events. - Routing through OpenRouter / LiteLLM / Requesty: SDK-through with OpenAI
baseURL+ canonical model id; tagcontext: { ingestion_path: 'gateway', gateway: '...' }(see Works with inamplitude-ai.md/ README). - Gateway product labels only (e.g.
openrouter/auto): cost is omitted — normalize to the routed provider model id. - LiteLLM / Strands OTLP partners: ensure
gen_ai.request.model+ input/output token attrs; LiteLLM needsCAPTURE_MESSAGE_CONTENTfor bodies; Requesty has no OTLP (SDK-through only). - LangChain / LangGraph: use
AmplitudeCallbackHandler(duck-typed; implementshandleChatModelStartfor User Message). - Need agent-assistant guidance: run MCP prompt
instrument_app. - Want local verification: use
MockAmplitudeAI().summary()for fill-rate report. - Works-with partners (OpenRouter, LiteLLM, Requesty, Strands): see Works with in
amplitude-ai.mdand README.
MCP Surface
Tools:
get_event_schemaget_integration_patternvalidate_setupsuggest_instrumentationvalidate_filesearch_docsscan_projectgenerate_verify_testinstrument_file
Resources:
amplitude-ai://event-schemaamplitude-ai://integration-patternsamplitude-ai://instrument-guide
Prompt:
instrument_app— Short prompt; fetchamplitude-ai://instrument-guide(full amplitude-ai.md) before editing
Canonical Patterns
- zero-code patching —
patch({ amplitudeAI: ai }) - wrap-openai —
wrap(existingClient, ai) - bound-agent-session —
ai.agent('id').session({ userId }).run(fn) - multi-agent-runas —
s.runAs(childAgent, fn) - tool-decorator —
tool(fn, { name: 'tool_name' }) - observe-spans —
observe(fn, { name: 'span-name' }) - express-middleware —
createAmplitudeAIMiddleware({ amplitudeAI: ai, userIdResolver })
Gotchas
tool()in Node requires explicit JSON schema for robust agent input shaping.- Keep
AMPLITUDE_AI_API_KEYavailable in runtime env for telemetry delivery. - Use
MockAmplitudeAIfor deterministic tests. - Call
ai.flush()before returning from serverless handlers (Next.js, Lambda, Vercel). session.run()relies onAsyncLocalStorage; not available in Edge Runtime. Cloudflare Workers: do NOT importAmplitudeAI,AIConfig, or any runtime export from@amplitude/aiin Worker bundles — they pull innode:async_hooks/node:modulewhich break Workers Builds. Use the SDK-freeFetchAmplitudeClientpattern with direct[Agent]event construction (see "Edge Runtime / Cloudflare Workers" in amplitude-ai.md). Onlyimport type { ... } from '@amplitude/ai/types'is safe.- User message text:
trackUserMessage(content, opts?)— put human-readable intent incontent; large JSON / RAG / pipeline state inopts.context(preferred — maps to the registered[Agent] Contextproperty, always queryable in charts), not as the onlycontent, or session labels and segmentation show raw JSON. Avoidopts.eventPropertiesfor custom dimensions on[Agent]events — unregistered properties may be silently dropped by schema enforcement. - Turns vs spans:
[Agent] User Message+[Agent] AI Responsedrive turn-level analytics;observe()/trackSpan()complement them — do not use spans alone for conversation metrics. - Gateways / custom
baseURL: usetrackAiMessagewithusagefields, the real routed model id, andtotalCostUsdwhen genai-prices cannot resolve the model string (install@pydantic/genai-pricesfor automatic cost when supported). Tag gateway traffic withcontext: { ingestion_path: 'gateway', gateway: 'openrouter'|'litellm'|'requesty' }. - LangChain callbacks:
AmplitudeCallbackHandleris duck-typed (no hard@langchain/coredep). PreferhandleChatModelStartcoverage for chat models.
CLI
amplitude-ai— Print instrumentation prompt for AI coding agentsamplitude-ai --print-guide— Print the full amplitude-ai.md guide to stdoutamplitude-ai mcp— Start the MCP server for AI coding agentsamplitude-ai doctor [--json]— Validate environment, deps, and event pipelineamplitude-ai status [--json]— Show SDK version, installed providers, and env config
Testing
- Run package tests:
pnpm --filter @amplitude/ai test - Run typecheck:
pnpm --filter @amplitude/ai test:typescript - Run docs freshness:
node scripts/generate-agent-docs.mjs --check
Examples
examples/zero-code.tsexamples/wrap-openai.tsexamples/multi-agent.tsexamples/framework-integration.tsexamples/real-openai.ts(requires OPENAI_API_KEY)
Instrumentation Guide
amplitude-ai.md— Start here. Complete 4-phase instrumentation workflow + API reference. Paste into any coding agent.llms-full.txt— Extended API reference with MCP tools and patterns
Event Schema (names)
[Agent] AI Response[Agent] Embedding[Agent] Evaluator Result[Agent] Score[Agent] Session End[Agent] Session Enrichment[Agent] Session Record[Agent] Span[Agent] Tool Call[Agent] Topic Classification[Agent] User Message