How to add analytics to a local MCP server in TypeScript

Instrument a local MCP tool with Agent Analytics, exercise success, failure and cancellation, then verify the request sessions. No LLM provider account is needed.

  • Node.js
  • TypeScript
  • AI SDK 0.26.0
  • 25 min

Chris Tam · Last updated 13 November 2026

Agent analytics can record tool latency and outcomes inside an MCP server you own. I'll build a TypeScript stdio server with a doubling tool and a local MCP client. Success mode doubles a number; failure mode deliberately fails; wait mode lets the client exercise protocol cancellation. This is a tool fixture, with no model call or original LLM prompt to capture.

What you'll build

A real MCP client/server pair with one Agent Analytics session per tool request, exactly one tool event per executed callback, explicit metadata-only collection and a flush handshake before the client closes the child. The test client correlates its run ID with the JSON-RPC request IDs.

Prerequisites

  • Node.js 24.14 or later and Corepack for pnpm.
  • An existing Amplitude test project, its ingestion API key, and its US or EU data center. Open Organization settings > API Keys and select the test project.

Use an existing test project with Agent Analytics enabled and permission to view its objects. The synthetic user is for this local fixture; production identity must come from authenticated server context. No LLM key or provider signup is required.

No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. Sign up for free to get your project API key.

1. Create the standalone project

I'll install the Node.js analytics SDK and use pinned versions from the tested example.

Terminal
mkdir nodejs-mcp-analytics
cd nodejs-mcp-analytics
mkdir -p src tests
corepack enable
package.json
{
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "name": "amplitude-nodejs-mcp-analytics",
  "engines": {
    "node": ">=24.14.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "build": "tsc",
    "test": "pnpm build && node --test tests/*.test.mjs",
    "demo": "node --env-file-if-exists=.env.local dist/client.js"
  },
  "dependencies": {
    "@amplitude/ai": "0.26.0",
    "@amplitude/analytics-node": "1.5.82",
    "@modelcontextprotocol/sdk": "1.32.1",
    "zod": "4.6.6"
  },
  "devDependencies": {
    "typescript": "6.0.3",
    "@types/node": "24.9.1"
  }
}
pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
.gitignore
node_modules/
dist/
.env.local
data/
.env.example
AMPLITUDE_API_KEY=
AMPLITUDE_SERVER_ZONE=US
BUILD_MCP_USER_ID=build-mcp-local-user
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "skipLibCheck": true,
    "types": [
      "node"
    ]
  },
  "include": [
    "src/**/*.ts"
  ]
}
Terminal
corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.local

Set AMPLITUDE_API_KEY to the test-project ingestion key and AMPLITUDE_SERVER_ZONE to US or EU. The project key has the minimum scope needed to ingest data. Keep your local environment file out of source control. These examples never need an Amplitude secret key.

In an existing app, merge these additions into the current SDK entry point and business operations. Preserve authentication, consent, routes and other instrumentation; use the authenticated account ID rather than accepting an arbitrary client-supplied user ID.

2. Initialize metadata-only analytics with an awaited flush

I'll initialize the Node client first, then supply an adapter to the AI SDK. The adapter tracks real SDK event promises and makes flush await their results. Metadata-only mode removes tool input and output before those events reach the adapter.

src/analytics.ts
import { AmplitudeAI, AIConfig, type AmplitudeEvent, type AmplitudeClientLike } from '@amplitude/ai';
import { createInstance, Types } from '@amplitude/analytics-node';
export async function initializeAnalytics(env = process.env, createClient = createInstance) {
  if (!env.AMPLITUDE_API_KEY?.trim()) return null;
  const client=createClient();
  await client.init(env.AMPLITUDE_API_KEY.trim(),{serverZone:env.AMPLITUDE_SERVER_ZONE==='EU'?'EU':'US',flushQueueSize:100,flushIntervalMillis:1000,flushMaxRetries:0,requestTimeoutMillis:3000,logLevel:Types.LogLevel.None}).promise;
  const queued: Promise<{code:number}>[]=[];
  // This adapter makes flush await the Node SDK wrappers and check each result.
  const adapter: AmplitudeClientLike={
    track(event: AmplitudeEvent) { queued.push(client.track(event).promise); },
    async flush() {
      await client.flush().promise;
      const results=await Promise.all(queued.splice(0));
      if(results.some(x=>x.code!==200))throw Error('Agent telemetry was not accepted.');
    },
  };
  const ai=new AmplitudeAI({amplitude:adapter,config:new AIConfig({contentMode:'metadata_only',redactPii:true,captureStackTrace:false})});
  return {ai,agent:ai.agent('build-mcp-calculator'),async flush(){await ai.flush();}};
}
export type Analytics = Awaited<ReturnType<typeof initializeAnalytics>>;

The pinned AI SDK can return the underlying client's flush wrapper. My adapter returns a true promise, explicitly awaits the Node SDK's .promise, and rejects a non200 event result. This avoids treating a bare await of a wrapper as proof of delivery. The later processed-session check is still separate.

A blank key returns a disabled analytics handle. The MCP tool still works. The explicit region and Node queue/timeout/retry options belong to this example; keep an existing application's consent and ingestion configuration when merging.

Why. SDK response and process lifecycles differ. A resolved local flush isn't permanent delivery, and a child process killed before buffered work finishes can lose events.

3. Record each executed tool callback once

I'll wrap one tool request in a session and record its tool call from a finally block. The client run UUID and actual JSON-RPC request ID form the session ID. The request ID also supplies the invocation ID, so overlapping calls stay distinguishable.

src/handler.ts
import { setTimeout as delay } from 'node:timers/promises';
import type { Analytics } from './analytics.js';
export type ToolArgs = {value:number; mode:'success'|'fail'|'wait';runId:string;privateNote?:string};
export async function executeTool(args:ToolArgs,signal:AbortSignal,requestId:string,analytics:Analytics,userId:string,started:()=>Promise<void>) {
  const sessionId=args.runId+':request:'+requestId;
  const execute=async(s?:{trackToolCall:(name:string,ms:number,success:boolean,options:Record<string,unknown>)=>unknown})=>{
    const begin=performance.now();let outcome:'success'|'failure'|'cancelled'='failure';let output:unknown;
    try {
      await started();
      if(args.mode==='wait')await delay(5000,undefined,{signal});
      signal.throwIfAborted();
      if(args.mode==='fail')throw Error('Synthetic tool failure.');
      output={doubled:args.value*2};outcome='success';
      return {content:[{type:'text' as const,text:JSON.stringify(output)}]};
    }catch{
      outcome=signal.aborted?'cancelled':'failure';output={outcome};
      return {isError:true,content:[{type:'text' as const,text:outcome}]};
    }finally{
      s?.trackToolCall('double_number',performance.now()-begin,outcome==='success',{
        input:args,output,toolType:'mcp',invocationId:requestId,
      });
    }
  };
  return analytics?analytics.agent.session({userId,sessionId,autoFlush:false}).run(s=>execute(s)):execute();
}

Success returns the doubled value. Failure is an explicit fixture mode. Cancellation uses the MCP handler's AbortSignal and returns an error result locally. Both failure and cancellation record Tool Success=false; distinguish their request IDs using the client's exercise sequence rather than inventing a richer SDK outcome field.

The synthetic privateNote is deliberately included in the tool input for the privacy test. Metadata-only mode excludes input/output content. Don't add an automatic tool wrapper on top of this explicit trackToolCall call, or one execution could produce duplicate tool events.

One request is one local job here, so its session closes when its scope ends. A production multi-tool agent needs its real job/session lifecycle rather than blindly treating every tool as the whole conversation.

4. Connect stdio and flush before closing the child

I'll register the tool using the MCP TypeScript server API and drive it with the official client transport. The wait request sends a progress notification, which triggers the client's cancellation. The finish_run control waits for active handlers and flushes telemetry before transport closure.

src/server.ts
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { initializeAnalytics } from './analytics.js';
import { executeTool } from './handler.js';
const analytics=await initializeAnalytics();
const server=new McpServer({name:'build-calculator',version:'1.0.0'});
const active=new Set<Promise<unknown>>();
const userId=process.env.BUILD_MCP_USER_ID||'build-mcp-local-user';
server.registerTool('double_number',{
  description:'Double a number locally. Failure and wait modes are explicit QA fixtures.',
  inputSchema:{value:z.number().int().min(-1000).max(1000),mode:z.enum(['success','fail','wait']),runId:z.uuid(),privateNote:z.string().max(100).optional()},
},async(args,extra)=>{
  const task=executeTool(args,extra.signal,String(extra.requestId),analytics,userId,async()=>{
    const token=extra._meta?.progressToken;
    if(token!==undefined)await extra.sendNotification({method:'notifications/progress',params:{progressToken:token,progress:1,total:2}});
  });
  active.add(task);try{return await task;}finally{active.delete(task);}
});
server.registerTool('finish_run',{description:'Wait for active fixture calls and flush their telemetry.'},async()=>{
  await Promise.allSettled([...active]);
  try{await analytics?.flush();return {content:[{type:'text' as const,text:analytics?'Telemetry accepted.':'Telemetry disabled.'}]};}
  catch{return {isError:true,content:[{type:'text' as const,text:'Telemetry failed.'}]};}
});
let closing:Promise<void>|undefined;
async function close(){
  if(!closing)closing=(async()=>{
    await Promise.allSettled([...active]);
    try {await analytics?.flush();console.error('MCP telemetry flush finished.');}
    catch {console.error('MCP telemetry flush failed.');process.exitCode=1;}
    await server.close();
  })();return closing;
}
server.server.onclose=()=>{void close();};
process.stdin.on('end',()=>{void close();});
for(const signal of ['SIGTERM','SIGINT'])process.on(signal,()=>{void close();});
await server.connect(new StdioServerTransport());
src/client.ts
import { randomUUID } from 'node:crypto';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { fileURLToPath } from 'node:url';
const runId=randomUUID();
const env=Object.fromEntries(Object.entries(process.env).filter((x):x is [string,string]=>typeof x[1]==='string'));
const transport=new StdioClientTransport({command:process.execPath,args:[fileURLToPath(new URL('./server.js',import.meta.url))],env,stderr:'pipe'});
let stderr='';transport.stderr?.on('data',d=>{stderr+=d.toString();});
const client=new Client({name:'build-local-client',version:'1.0.0'});
try{
  await client.connect(transport);
  const tools=await client.listTools();if(!tools.tools.some(x=>x.name==='double_number'))throw Error('Tool missing.');
  const call=(mode:'success'|'fail'|'wait',options={})=>client.callTool({name:'double_number',arguments:{value:7,mode,runId,privateNote:'PRIVATE_MCP_FIXTURE_20261113'}},undefined,options);
  const success=await call('success');const failed=await call('fail');
  const controller=new AbortController();let cancelled=false;
  try {await call('wait',{signal:controller.signal,onprogress:()=>controller.abort(),timeout:2000});}
  catch {cancelled=controller.signal.aborted;}
  const flushed=await client.callTool({name:'finish_run',arguments:{}},undefined,{timeout:10000});
  console.log(JSON.stringify({runId,success:!success.isError,failure:failed.isError===true,cancelled,flushed:!flushed.isError}));
}finally{
  // EOF lets the child settle cancelled work and flush before normal termination.
  await transport.close();
  if(!stderr.includes('MCP telemetry flush finished.')){
    console.error('Child did not confirm its telemetry flush.');process.exitCode=1;
  }
  await client.close();
}

Server stdout belongs to MCP JSON-RPC only. Diagnostics go to stderr. The control tool isn't a business tool and isn't itself instrumented. Transport EOF and signals also attempt a graceful flush, but a crash or SIGKILL cannot promise delivery.

The MCP client transport can terminate a child after its close grace period. The explicit finish_run handshake happens first, so the normal test client doesn't rely on that grace period to finish its upload.

5. Test and run the example

The tests use the actual AI SDK and Node SDK against a loopback receiver, then run a real stdio child/client with a blank ingestion key. These checks are separate from the live Amplitude run.

tests/mcp.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {spawn} from 'node:child_process';
import {randomUUID} from 'node:crypto';
import {createInstance} from '@amplitude/analytics-node';
import {initializeAnalytics} from '../dist/analytics.js';
import {executeTool} from '../dist/handler.js';

test('actual AI and Node SDKs: success/failure/cancel exactly once, metadata-only payloads and delivery-code checks',async()=>{
 const uploads=[];let status=200;
 const server=createServer(async(req,res)=>{let raw='';for await(const c of req)raw+=c;uploads.push(JSON.parse(raw).events);res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify({code:status,events_ingested:status===200?uploads.at(-1).length:0}));});await new Promise(r=>server.listen(0,'127.0.0.1',r));
 try{
  const factory=()=>{const c=createInstance(),init=c.init;return {...c,init:(key,opts)=>init(key,{...opts,serverUrl:`http://127.0.0.1:${server.address().port}`})};};
  const analytics=await initializeAnalytics({AMPLITUDE_API_KEY:'fake-key'},factory);const runId=randomUUID();
  for(const [index,mode] of ['success','fail','wait'].entries()){
    const controller=new AbortController();const result=await executeTool({value:7,mode,runId,privateNote:'PRIVATE_MCP_FIXTURE_20261113'},controller.signal,String(index),analytics,'build-mcp-test-user',async()=>{if(mode==='wait')controller.abort();});
    assert.equal(result.isError===true,mode!=='success');
  }
  await analytics.flush();const events=uploads.flat(),tools=events.filter(x=>x.event_type==='[Agent] Tool Call');
  assert.equal(tools.length,3);assert.equal(new Set(tools.map(x=>x.event_properties['[Agent] Session ID'])).size,3);
  assert.ok(!JSON.stringify(events).includes('PRIVATE_MCP_FIXTURE_20261113'));
  assert.deepEqual(tools.map(x=>x.event_properties['[Agent] Tool Success']),[true,false,false]);
  assert.deepEqual(tools.map(x=>x.event_properties['[Agent] Invocation ID']),['0','1','2']);
  status=500;await executeTool({value:7,mode:'success',runId:randomUUID()},new AbortController().signal,'4',analytics,'build-mcp-test-user',async()=>{});
  await assert.rejects(analytics.flush(),/not accepted/);
 }finally{await new Promise(r=>server.close(r));}
});
test('real stdio client discovers tool, succeeds, fails, cancels after progress, and completes flush handshake with blank key',async()=>{
 const result=await new Promise((resolve,reject)=>{const c=spawn(process.execPath,['dist/client.js'],{cwd:new URL('../',import.meta.url),env:{...process.env,AMPLITUDE_API_KEY:''},stdio:['ignore','pipe','pipe']});let out='',err='';c.stdout.on('data',d=>out+=d);c.stderr.on('data',d=>err+=d);c.on('error',reject);c.on('exit',code=>resolve({out,err,code}));});
 assert.equal(result.code,0,result.err);const summary=JSON.parse(result.out.trim());assert.ok(summary.success&&summary.failure&&summary.cancelled&&summary.flushed);
 assert.ok(!result.out.includes('PRIVATE_MCP_FIXTURE'));assert.ok(!result.out.includes('telemetry flush finished'));
});
Terminal
pnpm test
pnpm demo

Verify it worked

Run the local client with your existing Agent Analytics test key. Retain its printed runId.

  1. Protocol paths: Confirm the client reports success=true, failure=true, cancelled=true and flushed=true. It discovers the tool, receives the successful result, handles the explicit error, cancels the wait after progress and completes the flush control before closing transport.
  2. Actual event bodies: Confirm three [Agent] Tool Call events and three Session End events for that run. Tool Success is true for success and false for failure/cancel. Session IDs include the same runId and different request IDs; tool invocation IDs match the requests. The finish_run control adds no tool event.
  3. Metadata privacy: Scan every event in the actual upload for PRIVATE_MCP_FIXTURE_20261113. It must be absent, along with Tool Input and Tool Output content. The events should retain tool name, latency, agent ID and session correlation. Test custom properties separately; metadata mode is not a general policy for arbitrary fields you add.
  4. Processed sessions: In Agent Analytics, find the sessions by the recorded IDs and agent build-mcp-calculator. Verify three closed tool-request sessions:one without errors and two with an error. No model, token usage, cost or prompt content is expected because this fixture makes no model call.
  5. Failure and disabled mode: Run pnpm test. The real SDK loopback500 fails the flush result check. Blank-key protocol operation still succeeds; do not label that run as verified ingestion.

Troubleshooting

The server prints non-JSON text to stdout

Move logs to stderr. MCP stdio reserves stdout for protocol messages; a console.log diagnostic can corrupt the client connection.

A tool event appears twice

Use the explicit trackToolCall path once. Do not combine it with tool() or another automatic wrapper for the same callback.

The cancelled call is missing

Wait for the cancellation handler to settle before flushing or terminating the process. The finish_run control waits for active tasks; abrupt process termination still cannot guarantee telemetry.

The session has no model or token counts

That is expected here. The MCP server executes a local tool and does not call an LLM. Add provider instrumentation separately if your own server actually makes model calls.

Metadata-only removes the context I expected

This example relies on fixed SDK metadata and real IDs, not free-text context. Pinned0.26 also excludes context in metadata-only mode. Do not copy tool values into custom properties to work around the privacy choice.

Full code reference

The complete runnable example includes the lockfile. These are the complete setup, application and test files.

Full code reference
===== package.json =====
{
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "name": "amplitude-nodejs-mcp-analytics",
  "engines": {
    "node": ">=24.14.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "build": "tsc",
    "test": "pnpm build && node --test tests/*.test.mjs",
    "demo": "node --env-file-if-exists=.env.local dist/client.js"
  },
  "dependencies": {
    "@amplitude/ai": "0.26.0",
    "@amplitude/analytics-node": "1.5.82",
    "@modelcontextprotocol/sdk": "1.32.1",
    "zod": "4.6.6"
  },
  "devDependencies": {
    "typescript": "6.0.3",
    "@types/node": "24.9.1"
  }
}

===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade

===== .gitignore =====
node_modules/
dist/
.env.local
data/

===== .env.example =====
AMPLITUDE_API_KEY=
AMPLITUDE_SERVER_ZONE=US
BUILD_MCP_USER_ID=build-mcp-local-user

===== tsconfig.json =====
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "skipLibCheck": true,
    "types": [
      "node"
    ]
  },
  "include": [
    "src/**/*.ts"
  ]
}

===== src/analytics.ts =====
import { AmplitudeAI, AIConfig, type AmplitudeEvent, type AmplitudeClientLike } from '@amplitude/ai';
import { createInstance, Types } from '@amplitude/analytics-node';
export async function initializeAnalytics(env = process.env, createClient = createInstance) {
  if (!env.AMPLITUDE_API_KEY?.trim()) return null;
  const client=createClient();
  await client.init(env.AMPLITUDE_API_KEY.trim(),{serverZone:env.AMPLITUDE_SERVER_ZONE==='EU'?'EU':'US',flushQueueSize:100,flushIntervalMillis:1000,flushMaxRetries:0,requestTimeoutMillis:3000,logLevel:Types.LogLevel.None}).promise;
  const queued: Promise<{code:number}>[]=[];
  // This adapter makes flush await the Node SDK wrappers and check each result.
  const adapter: AmplitudeClientLike={
    track(event: AmplitudeEvent) { queued.push(client.track(event).promise); },
    async flush() {
      await client.flush().promise;
      const results=await Promise.all(queued.splice(0));
      if(results.some(x=>x.code!==200))throw Error('Agent telemetry was not accepted.');
    },
  };
  const ai=new AmplitudeAI({amplitude:adapter,config:new AIConfig({contentMode:'metadata_only',redactPii:true,captureStackTrace:false})});
  return {ai,agent:ai.agent('build-mcp-calculator'),async flush(){await ai.flush();}};
}
export type Analytics = Awaited<ReturnType<typeof initializeAnalytics>>;

===== src/handler.ts =====
import { setTimeout as delay } from 'node:timers/promises';
import type { Analytics } from './analytics.js';
export type ToolArgs = {value:number; mode:'success'|'fail'|'wait';runId:string;privateNote?:string};
export async function executeTool(args:ToolArgs,signal:AbortSignal,requestId:string,analytics:Analytics,userId:string,started:()=>Promise<void>) {
  const sessionId=args.runId+':request:'+requestId;
  const execute=async(s?:{trackToolCall:(name:string,ms:number,success:boolean,options:Record<string,unknown>)=>unknown})=>{
    const begin=performance.now();let outcome:'success'|'failure'|'cancelled'='failure';let output:unknown;
    try {
      await started();
      if(args.mode==='wait')await delay(5000,undefined,{signal});
      signal.throwIfAborted();
      if(args.mode==='fail')throw Error('Synthetic tool failure.');
      output={doubled:args.value*2};outcome='success';
      return {content:[{type:'text' as const,text:JSON.stringify(output)}]};
    }catch{
      outcome=signal.aborted?'cancelled':'failure';output={outcome};
      return {isError:true,content:[{type:'text' as const,text:outcome}]};
    }finally{
      s?.trackToolCall('double_number',performance.now()-begin,outcome==='success',{
        input:args,output,toolType:'mcp',invocationId:requestId,
      });
    }
  };
  return analytics?analytics.agent.session({userId,sessionId,autoFlush:false}).run(s=>execute(s)):execute();
}

===== src/server.ts =====
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { initializeAnalytics } from './analytics.js';
import { executeTool } from './handler.js';
const analytics=await initializeAnalytics();
const server=new McpServer({name:'build-calculator',version:'1.0.0'});
const active=new Set<Promise<unknown>>();
const userId=process.env.BUILD_MCP_USER_ID||'build-mcp-local-user';
server.registerTool('double_number',{
  description:'Double a number locally. Failure and wait modes are explicit QA fixtures.',
  inputSchema:{value:z.number().int().min(-1000).max(1000),mode:z.enum(['success','fail','wait']),runId:z.uuid(),privateNote:z.string().max(100).optional()},
},async(args,extra)=>{
  const task=executeTool(args,extra.signal,String(extra.requestId),analytics,userId,async()=>{
    const token=extra._meta?.progressToken;
    if(token!==undefined)await extra.sendNotification({method:'notifications/progress',params:{progressToken:token,progress:1,total:2}});
  });
  active.add(task);try{return await task;}finally{active.delete(task);}
});
server.registerTool('finish_run',{description:'Wait for active fixture calls and flush their telemetry.'},async()=>{
  await Promise.allSettled([...active]);
  try{await analytics?.flush();return {content:[{type:'text' as const,text:analytics?'Telemetry accepted.':'Telemetry disabled.'}]};}
  catch{return {isError:true,content:[{type:'text' as const,text:'Telemetry failed.'}]};}
});
let closing:Promise<void>|undefined;
async function close(){
  if(!closing)closing=(async()=>{
    await Promise.allSettled([...active]);
    try {await analytics?.flush();console.error('MCP telemetry flush finished.');}
    catch {console.error('MCP telemetry flush failed.');process.exitCode=1;}
    await server.close();
  })();return closing;
}
server.server.onclose=()=>{void close();};
process.stdin.on('end',()=>{void close();});
for(const signal of ['SIGTERM','SIGINT'])process.on(signal,()=>{void close();});
await server.connect(new StdioServerTransport());

===== src/client.ts =====
import { randomUUID } from 'node:crypto';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { fileURLToPath } from 'node:url';
const runId=randomUUID();
const env=Object.fromEntries(Object.entries(process.env).filter((x):x is [string,string]=>typeof x[1]==='string'));
const transport=new StdioClientTransport({command:process.execPath,args:[fileURLToPath(new URL('./server.js',import.meta.url))],env,stderr:'pipe'});
let stderr='';transport.stderr?.on('data',d=>{stderr+=d.toString();});
const client=new Client({name:'build-local-client',version:'1.0.0'});
try{
  await client.connect(transport);
  const tools=await client.listTools();if(!tools.tools.some(x=>x.name==='double_number'))throw Error('Tool missing.');
  const call=(mode:'success'|'fail'|'wait',options={})=>client.callTool({name:'double_number',arguments:{value:7,mode,runId,privateNote:'PRIVATE_MCP_FIXTURE_20261113'}},undefined,options);
  const success=await call('success');const failed=await call('fail');
  const controller=new AbortController();let cancelled=false;
  try {await call('wait',{signal:controller.signal,onprogress:()=>controller.abort(),timeout:2000});}
  catch {cancelled=controller.signal.aborted;}
  const flushed=await client.callTool({name:'finish_run',arguments:{}},undefined,{timeout:10000});
  console.log(JSON.stringify({runId,success:!success.isError,failure:failed.isError===true,cancelled,flushed:!flushed.isError}));
}finally{
  // EOF lets the child settle cancelled work and flush before normal termination.
  await transport.close();
  if(!stderr.includes('MCP telemetry flush finished.')){
    console.error('Child did not confirm its telemetry flush.');process.exitCode=1;
  }
  await client.close();
}

===== tests/mcp.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {spawn} from 'node:child_process';
import {randomUUID} from 'node:crypto';
import {createInstance} from '@amplitude/analytics-node';
import {initializeAnalytics} from '../dist/analytics.js';
import {executeTool} from '../dist/handler.js';

test('actual AI and Node SDKs: success/failure/cancel exactly once, metadata-only payloads and delivery-code checks',async()=>{
 const uploads=[];let status=200;
 const server=createServer(async(req,res)=>{let raw='';for await(const c of req)raw+=c;uploads.push(JSON.parse(raw).events);res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify({code:status,events_ingested:status===200?uploads.at(-1).length:0}));});await new Promise(r=>server.listen(0,'127.0.0.1',r));
 try{
  const factory=()=>{const c=createInstance(),init=c.init;return {...c,init:(key,opts)=>init(key,{...opts,serverUrl:`http://127.0.0.1:${server.address().port}`})};};
  const analytics=await initializeAnalytics({AMPLITUDE_API_KEY:'fake-key'},factory);const runId=randomUUID();
  for(const [index,mode] of ['success','fail','wait'].entries()){
    const controller=new AbortController();const result=await executeTool({value:7,mode,runId,privateNote:'PRIVATE_MCP_FIXTURE_20261113'},controller.signal,String(index),analytics,'build-mcp-test-user',async()=>{if(mode==='wait')controller.abort();});
    assert.equal(result.isError===true,mode!=='success');
  }
  await analytics.flush();const events=uploads.flat(),tools=events.filter(x=>x.event_type==='[Agent] Tool Call');
  assert.equal(tools.length,3);assert.equal(new Set(tools.map(x=>x.event_properties['[Agent] Session ID'])).size,3);
  assert.ok(!JSON.stringify(events).includes('PRIVATE_MCP_FIXTURE_20261113'));
  assert.deepEqual(tools.map(x=>x.event_properties['[Agent] Tool Success']),[true,false,false]);
  assert.deepEqual(tools.map(x=>x.event_properties['[Agent] Invocation ID']),['0','1','2']);
  status=500;await executeTool({value:7,mode:'success',runId:randomUUID()},new AbortController().signal,'4',analytics,'build-mcp-test-user',async()=>{});
  await assert.rejects(analytics.flush(),/not accepted/);
 }finally{await new Promise(r=>server.close(r));}
});
test('real stdio client discovers tool, succeeds, fails, cancels after progress, and completes flush handshake with blank key',async()=>{
 const result=await new Promise((resolve,reject)=>{const c=spawn(process.execPath,['dist/client.js'],{cwd:new URL('../',import.meta.url),env:{...process.env,AMPLITUDE_API_KEY:''},stdio:['ignore','pipe','pipe']});let out='',err='';c.stdout.on('data',d=>out+=d);c.stderr.on('data',d=>err+=d);c.on('error',reject);c.on('exit',code=>resolve({out,err,code}));});
 assert.equal(result.code,0,result.err);const summary=JSON.parse(result.out.trim());assert.ok(summary.success&&summary.failure&&summary.cancelled&&summary.flushed);
 assert.ok(!result.out.includes('PRIVATE_MCP_FIXTURE'));assert.ok(!result.out.includes('telemetry flush finished'));
});

Hand it to your agent

Implementation prompt
Use https://amplitude.com/build/nodejs-mcp-analytics and its linked source.
Inspect the existing application and SDK entry point first. Preserve auth, consent,
and other instrumentation. Read the installed SDK's current docs through Docs MCP.

Use a real MCP stdio client/server and request AbortSignal. Correlate an actual
client job ID with the JSON-RPC request ID. Track exactly one explicit tool call
per executed callback, preserving success and failed/cancelled status semantics.
Set metadata_only and scan full real payloads with a synthetic input marker.
Reserve stdout for protocol messages. Settle active tasks and await checked
SDK event promises before normal transport closure. Keep real auth/job identity
when adapting, and do not claim original prompts or model cost without model calls.

Run local failure and success checks. Verify real HTTP acceptance and processed
history separately. Keep environment secrets and synthetic fixture data local.
Report changed files and remaining coverage limits.

MCP. The Docs MCP server reads public documentation. It cannot inspect this project's events or run the application for you.

What this unlocks

Agent analytics can compare tool latency and failure by the actual request/session identity.

Product analytics can connect server tool activity to separately instrumented product outcomes when identities are aligned.

Session replay applies to a separately instrumented browser interface; stdio produces no browser replay.

Feature flags can control a later tool implementation while request outcomes measure its behavior.

Frequently asked questions

Do I need an OpenAI or Anthropic account for this example?

No. The official MCP client calls a local deterministic tool. Only an existing Amplitude test project is used for ingestion.

Can the MCP server capture the user's original prompt?

MCP tool requests do not include the originating LLM prompt. This fixture records request/tool metadata and deliberately removes tool input/output content.

Does every tool request need a new agent session?

This fixture treats each request as one local job. A production conversation spanning tools should use its actual shared job/session ID and close it at the real lifecycle boundary.

Next steps

Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.

Connect the next event

Make the outcome and identity explicit, then verify them in your test project.