Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: add MCP (Model Context Protocol) instrumentation in TS SDK (#1254)

Willow Lopez7e6337b29c99
diff --git a/sdk/typescript/mcp-smoke.mjs b/sdk/typescript/mcp-smoke.mjs
new file mode 100644
index 00000000..fa50a793
--- /dev/null
+++ b/sdk/typescript/mcp-smoke.mjs
@@ -0,0 +1,156 @@
+/**
+ * MCP Instrumentation — comprehensive smoke test (99 checks).
+ * Usage: cd sdk/typescript && node mcp-smoke.mjs
+ */
+import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
+import { InMemorySpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
+import { trace } from '@opentelemetry/api';
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+
+const exporter = new InMemorySpanExporter();
+const provider = new NodeTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] });
+provider.register();
+const tracer = trace.getTracer('mcp-demo');
+const VER = '1.0.0';
+
+const wrapper = require('./dist/instrumentation/mcp/wrapper');
+const semconv = require('./dist/semantic-convention').default;
+
+const patch = (fn, factory) => factory(tracer, VER)(fn);
+const mkFn = (impl) => Object.assign(async (...a) => impl(...a), {});
+
+let passed = 0, failed = 0;
+function check(label, ok, detail) {
+ if (ok) { passed++; } else { failed++; console.log(` ❌ ${label}${detail ? ' — ' + detail : ''}`); }
+}
+function ok(msg, n) { console.log(` ✅ ${msg}${n != null ? ' (' + n + ' checks)' : ''}`); }
+function lastSpan() { const s = exporter.getFinishedSpans(); return s[s.length - 1]; }
+async function test(label, run) {
+ const before = exporter.getFinishedSpans().length;
+ try { await run(); } catch {}
+ await new Promise(r => setTimeout(r, 10));
+ const after = exporter.getFinishedSpans().length;
+ if (after > before) passed++; else { failed++; console.log(` ❌ ${label}`); }
+}
+
+console.log('=== MCP Instrumentation Smoke Test ===\n');
+
+// Client
+let n = 0;
+await test('callTool', () => patch(mkFn(() => ({ content: [] })), wrapper.patchCallTool)({ name: 'echo' })); n++;
+await test('callTool error', async () => { try { await patch(mkFn(() => { throw new Error('fail'); }), wrapper.patchCallTool)({ name: 'bad' }); } catch {} }); n++;
+await test('listTools', () => patch(mkFn(() => ({ tools: [{ name: 't1' }] })), wrapper.patchListTools)()); n++;
+await test('getPrompt', () => patch(mkFn(() => ({ messages: [] })), wrapper.patchGetPrompt)({ name: 'greet' })); n++;
+await test('listPrompts', () => patch(mkFn(() => ({ prompts: [] })), wrapper.patchListPrompts)()); n++;
+await test('readResource', () => patch(mkFn(() => ({ contents: [{ text: 'ok' }] })), wrapper.patchReadResource)({ uri: 'file:///test' })); n++;
+await test('listResources', () => patch(mkFn(() => ({ resources: [] })), wrapper.patchListResources)()); n++;
+ok('Client (callTool, listTools, getPrompt, listPrompts, readResource, listResources + error)', n);
+
+// ClientSession
+n = 0;
+await test('sendRequest', () => patch(mkFn(() => ({ jsonrpc: '2.0' })), wrapper.patchClientSessionSendRequest)({ method: 'tools/call' })); n++;
+await test('initialize', () => patch(mkFn(() => ({ protocolVersion: '2024-11-05' })), wrapper.patchClientSessionInitialize)({ protocolVersion: '2024-11-05' })); n++;
+ok('ClientSession (sendRequest, initialize)', n);
+
+// Server
+n = 0;
+await test('server.run', () => patch(mkFn(() => {}), wrapper.patchServerRun)()); n++;
+await test('server.callTool', () => patch(mkFn(() => ({ content: [] })), wrapper.patchServerCallTool)({ name: 'srv' })); n++;
+await test('server.listTools', () => patch(mkFn(() => ({ tools: [] })), wrapper.patchServerListTools)()); n++;
+await test('server.readResource', () => patch(mkFn(() => ({ contents: [] })), wrapper.patchServerReadResource)({ uri: 'file:///srv' })); n++;
+await test('server.listResources', () => patch(mkFn(() => ({ resources: [] })), wrapper.patchServerListResources)()); n++;
+ok('Server (run, callTool, listTools, readResource, listResources)', n);
+
+// Transports
+n = 0;
+for (const ep of ['transport stdio_client','transport stdio_server','transport sse_client','transport sse_server','transport http_client','transport http_server']) {
+ await test(ep, () => wrapper.patchTransport(ep, tracer, VER)(mkFn(() => {}))()); n++;
+}
+ok('Transports (stdio_client/server, sse_client/server, http_client/server)', n);
+
+// ServerSession
+n = 0;
+await test('send_request', () => { const p = wrapper.patchServerSessionOperation('send_request', tracer, VER); return p(mkFn(() => ({})))(); }); n++;
+await test('send_notification', () => { const p = wrapper.patchServerSessionOperation('send_notification', tracer, VER); return p(mkFn(() => ({})))(); }); n++;
+await test('send_log_message', () => { const p = wrapper.patchServerSessionOperation('send_log_message', tracer, VER); return p(mkFn(() => ({})))(); }); n++;
+ok('ServerSession (send_request, send_notification, send_log_message)', n);
+
+await new Promise(r => setTimeout(r, 200));
+const allSpans = exporter.getFinishedSpans();
+
+// Span names
+const names = ['mcp tools/call','mcp tools/list','mcp prompts/get','mcp prompts/list',
+ 'mcp resources/read','mcp resources/list','mcp transport/request','mcp initialize',
+ 'mcp server/run','mcp transport/stdio','mcp transport/sse','mcp transport/http',
+ 'mcp server/send_request','mcp server/send_notification','mcp server/send_log_message'];
+n = 0; names.forEach(name => { if (allSpans.find(s => s.name === name)) n++; else console.log(' ❌ span missing:', name); }); passed += n;
+ok('Span names (all 15 aligned with Python)', n);
+
+// Span kinds
+n = 0;
+check('server.callTool kind=SERVER', !!allSpans.find(s => s.name === 'mcp tools/call' && s.kind === 1)); n++;
+check('transport kind=CLIENT', !!allSpans.find(s => s.name === 'mcp transport/stdio' && s.kind === 2)); n++;
+ok('Span kinds (CLIENT/SERVER)', n);
+
+// Attributes
+n = 0;
+const ts = allSpans.find(s => s.attributes['mcp.tool.name'] === 'echo');
+const rs = allSpans.find(s => s.attributes['mcp.resource.uri'] === 'file:///test');
+const ps = allSpans.find(s => s.name === 'mcp prompts/get');
+check('mcp.tool.name = echo', ts?.attributes['mcp.tool.name'] === 'echo'); n++;
+check('mcp.operation.name = tools_call', ts?.attributes['mcp.operation.name'] === 'tools_call'); n++;
+check('mcp.resource.uri = file:///test', rs?.attributes['mcp.resource.uri'] === 'file:///test'); n++;
+check('mcp.prompt.name = greet', ps?.attributes['mcp.prompt.name'] === 'greet',
+ ps ? (ps.attributes['mcp.prompt.name'] || 'NOT SET') : 'SPAN NOT FOUND'); n++;
+check('mcp.error.message', !!allSpans.find(s => s.attributes['mcp.error.message'])); n++;
+check('mcp.transport.type = stdio', !!allSpans.find(s => s.attributes['mcp.transport.type'] === 'stdio')); n++;
+ok('Attributes (mcp.*)', n);
+
+// Namespace
+const allKeys = allSpans.flatMap(s => Object.keys(s.attributes));
+const bad = allKeys.filter(k => k.startsWith('gen_ai.') && !k.startsWith('gen_ai.system'));
+check('0 gen_ai.* keys (all mcp.*)', bad.length === 0, bad.length === 0 ? 'clean' : `BAD: ${bad}`);
+ok('Namespace', 1);
+
+// Semantic conventions (44)
+const req = ['MCP_OPERATION','MCP_SYSTEM','MCP_SDK_VERSION','MCP_METHOD','MCP_MESSAGE_ID',
+ 'MCP_JSONRPC_VERSION','MCP_PARAMS','MCP_RESULT','MCP_ERROR_CODE','MCP_ERROR_MESSAGE',
+ 'MCP_ERROR_DATA','MCP_TOOL_NAME','MCP_TOOL_DESCRIPTION','MCP_TOOL_ARGUMENTS',
+ 'MCP_TOOL_RESULT','MCP_RESOURCE_URI','MCP_RESOURCE_NAME','MCP_RESOURCE_DESCRIPTION',
+ 'MCP_RESOURCE_MIME_TYPE','MCP_RESOURCE_SIZE','MCP_TRANSPORT_TYPE','MCP_TRANSPORT_STDIO',
+ 'MCP_TRANSPORT_SSE','MCP_TRANSPORT_WEBSOCKET','MCP_CLIENT_TYPE',
+ 'GEN_AI_SYSTEM_MCP','GEN_AI_OPERATION_TYPE_MCP_TOOL_CALL','GEN_AI_OPERATION_TYPE_MCP_TOOL_LIST',
+ 'GEN_AI_OPERATION_TYPE_MCP_RESOURCE_READ','GEN_AI_OPERATION_TYPE_MCP_RESOURCE_LIST',
+ 'GEN_AI_OPERATION_TYPE_MCP_REQUEST','GEN_AI_OPERATION_TYPE_MCP_RESPONSE',
+ 'GEN_AI_OPERATION_TYPE_MCP_SERVER','GEN_AI_OPERATION_TYPE_MCP_CLIENT',
+ 'MCP_REQUESTS','MCP_CLIENT_OPERATION_DURATION','MCP_CLIENT_OPERATION_DURATION_METRIC',
+ 'MCP_RESPONSE_SIZE','MCP_RESPONSE_SIZE_METRIC','MCP_REQUEST_SIZE','MCP_TOOL_CALLS',
+ 'MCP_RESOURCE_READS','MCP_PROMPT_GETS','MCP_TRANSPORT_USAGE','MCP_ERRORS','MCP_OPERATION_SUCCESS_RATE'];
+n = 0; req.forEach(name => { if (semconv[name] != null) n++; else console.log(' ❌ semconv missing:', name); }); passed += n;
+ok('Semantic Conventions', n);
+
+// Metrics
+const Metrics = require('./dist/otel/metrics').default;
+check('Metrics class', typeof Metrics === 'function'); n = 1;
+check('initializeMetrics', typeof Metrics.initializeMetrics === 'function'); n++;
+let recOk = false;
+try { wrapper.recordMCPMetrics({ mcpOperation:'t', mcpMethod:'m', mcpTransportType:'stdio', toolName:'x', duration:0.1 }); recOk = true; } catch {}
+check('recordMCPMetrics safe', recOk); n++;
+ok('Metrics', n);
+
+// Registry
+n = 0;
+const MCP = require('./dist/instrumentation/mcp').default;
+const i = new MCP();
+check('instrumentationName "mcp"', i.instrumentationName.includes('mcp')); n++;
+check('version 1.0.0', i.instrumentationVersion === '1.0.0'); n++;
+check('registered in Instrumentations map', require('./dist/instrumentation').default.availableInstrumentations?.mcp != null); n++;
+ok('Registry', n);
+
+console.log(`\n${'─'.repeat(40)}`);
+console.log(` ${passed} passed, ${failed} failed (${passed + failed} total)`);
+console.log(`${'─'.repeat(40)}`);
+if (failed > 0) { console.log(`\n ❌ ${failed} FAILURES\n`); process.exit(1); }
+else console.log(' ✅ All checks passed.\n');
+await provider.shutdown();
diff --git a/sdk/typescript/src/instrumentation/index.ts b/sdk/typescript/src/instrumentation/index.ts
index 787189fe..2df5768d 100644
--- a/sdk/typescript/src/instrumentation/index.ts
+++ b/sdk/typescript/src/instrumentation/index.ts
@@ -29,6 +29,7 @@ import GoogleADKInstrumentation from './google-adk';
import ClaudeAgentSDKInstrumentation from './claude-agent-sdk';
import CursorSDKInstrumentation from './cursor-sdk';
import AstraInstrumentation from './astra';
+import MCPInstrumentation from './mcp';
/**
* OTel community instrumentations loaded dynamically (like Python SDK).
@@ -100,6 +101,7 @@ export default class Instrumentations {
'claude-agent-sdk': new ClaudeAgentSDKInstrumentation(),
'cursor-sdk': new CursorSDKInstrumentation(),
'astra': new AstraInstrumentation(),
+ mcp: new MCPInstrumentation(),
};
static setup(
diff --git a/sdk/typescript/src/instrumentation/mcp/index.ts b/sdk/typescript/src/instrumentation/mcp/index.ts
new file mode 100644
index 00000000..e843cb8d
--- /dev/null
+++ b/sdk/typescript/src/instrumentation/mcp/index.ts
@@ -0,0 +1,352 @@
+import { diag } from '@opentelemetry/api';
+import {
+ InstrumentationBase,
+ InstrumentationModuleDefinition,
+ InstrumentationNodeModuleDefinition,
+ isWrapped,
+} from '@opentelemetry/instrumentation';
+import { InstrumentationConfig } from '@opentelemetry/instrumentation';
+import { INSTRUMENTATION_PREFIX } from '../../constant';
+import {
+ patchCallTool,
+ patchListTools,
+ patchGetPrompt,
+ patchListPrompts,
+ patchReadResource,
+ patchListResources,
+ patchClientSessionSendRequest,
+ patchClientSessionInitialize,
+ patchServerRun,
+ patchServerCallTool,
+ patchServerListTools,
+ patchServerReadResource,
+ patchServerListResources,
+ patchTransport,
+ patchServerSessionOperation,
+} from './wrapper';
+
+export interface MCPInstrumentationConfig extends InstrumentationConfig {}
+
+export default class MCPInstrumentation extends InstrumentationBase {
+ private _mcpVersion = 'unknown';
+
+ constructor(config: MCPInstrumentationConfig = {}) {
+ super(`${INSTRUMENTATION_PREFIX}/instrumentation-mcp`, '1.0.0', config);
+ }
+
+ protected init():
+ | void
+ | InstrumentationModuleDefinition
+ | InstrumentationModuleDefinition[] {
+ // Main MCP SDK module — covers Client, Server, and FastMCP
+ const mainModule = new InstrumentationNodeModuleDefinition(
+ '@modelcontextprotocol/sdk',
+ ['>=1.0.0'],
+ (moduleExports, moduleVersion) => {
+ if (moduleVersion) this._mcpVersion = String(moduleVersion);
+ this._patchMain(moduleExports);
+ return moduleExports;
+ },
+ (moduleExports) => {
+ if (moduleExports !== undefined) {
+ this._unpatchMain(moduleExports);
+ }
+ },
+ );
+
+ return [mainModule];
+ }
+
+ public manualPatch(mcpSdk: any): void {
+ this._patchMain(mcpSdk);
+ }
+
+ // -----------------------------------------------------------------------
+ // Main module patching — Client, Server, FastMCP, and transport classes
+ // -----------------------------------------------------------------------
+
+ private _patchMain(moduleExports: any): void {
+ try {
+ this._patchClient(moduleExports);
+ this._patchServer(moduleExports);
+ this._patchTransports(moduleExports);
+ this._patchFastMCP(moduleExports);
+ } catch (e) {
+ diag.error('Error in MCP _patchMain method', e as Error);
+ }
+ }
+
+ private _unpatchMain(moduleExports: any): void {
+ try {
+ this._unpatchClient(moduleExports);
+ this._unpatchServer(moduleExports);
+ this._unpatchTransports(moduleExports);
+ this._unpatchFastMCP(moduleExports);
+ } catch {
+ /* ignore unpatch errors */
+ }
+ }
+
+ // -----------------------------------------------------------------------
+ // Client + ClientSession
+ // -----------------------------------------------------------------------
+
+ private _patchClient(moduleExports: any): void {
+ const Client = moduleExports.Client;
+ if (!Client?.prototype) return;
+
+ const clientMethods: Array<[string, (...args: any[]) => any]> = [
+ ['callTool', patchCallTool(this.tracer, this._mcpVersion)],
+ ['listTools', patchListTools(this.tracer, this._mcpVersion)],
+ ['getPrompt', patchGetPrompt(this.tracer, this._mcpVersion)],
+ ['listPrompts', patchListPrompts(this.tracer, this._mcpVersion)],
+ ['readResource', patchReadResource(this.tracer, this._mcpVersion)],
+ ['listResources', patchListResources(this.tracer, this._mcpVersion)],
+ ];
+
+ for (const [method, patcher] of clientMethods) {
+ if (typeof Client.prototype[method] === 'function') {
+ if (isWrapped(Client.prototype[method])) {
+ this._unwrap(Client.prototype, method);
+ }
+ this._wrap(Client.prototype, method, patcher);
+ }
+ }
+
+ // ClientSession (low-level)
+ const ClientSession = moduleExports.ClientSession;
+ if (ClientSession?.prototype) {
+ const sessionMethods: Array<[string, (...args: any[]) => any]> = [
+ ['sendRequest', patchClientSessionSendRequest(this.tracer, this._mcpVersion)],
+ ['initialize', patchClientSessionInitialize(this.tracer, this._mcpVersion)],
+ ['callTool', patchCallTool(this.tracer, this._mcpVersion)],
+ ['listTools', patchListTools(this.tracer, this._mcpVersion)],
+ ['readResource', patchReadResource(this.tracer, this._mcpVersion)],
+ ['listResources', patchListResources(this.tracer, this._mcpVersion)],
+ ];
+
+ for (const [method, patcher] of sessionMethods) {
+ if (typeof ClientSession.prototype[method] === 'function') {
+ if (isWrapped(ClientSession.prototype[method])) {
+ this._unwrap(ClientSession.prototype, method);
+ }
+ this._wrap(ClientSession.prototype, method, patcher);
+ }
+ }
+ }
+ }
+
+ private _unpatchClient(moduleExports: any): void {
+ const Client = moduleExports.Client;
+ if (Client?.prototype) {
+ for (const method of [
+ 'callTool', 'listTools', 'getPrompt', 'listPrompts', 'readResource', 'listResources',
+ ]) {
+ if (isWrapped(Client.prototype[method])) {
+ this._unwrap(Client.prototype, method);
+ }
+ }
+ }
+
+ const ClientSession = moduleExports.ClientSession;
+ if (ClientSession?.prototype) {
+ for (const method of [
+ 'sendRequest', 'initialize', 'callTool', 'listTools', 'readResource', 'listResources',
+ ]) {
+ if (isWrapped(ClientSession.prototype[method])) {
+ this._unwrap(ClientSession.prototype, method);
+ }
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------------
+ // Server
+ // -----------------------------------------------------------------------
+
+ private _patchServer(moduleExports: any): void {
+ const Server = moduleExports.Server;
+ if (!Server?.prototype) return;
+
+ const serverMethods: Array<[string, (...args: any[]) => any]> = [
+ ['run', patchServerRun(this.tracer, this._mcpVersion)],
+ ['callTool', patchServerCallTool(this.tracer, this._mcpVersion)],
+ ['listTools', patchServerListTools(this.tracer, this._mcpVersion)],
+ ['readResource', patchServerReadResource(this.tracer, this._mcpVersion)],
+ ['listResources', patchServerListResources(this.tracer, this._mcpVersion)],
+ ];
+
+ for (const [method, patcher] of serverMethods) {
+ if (typeof Server.prototype[method] === 'function') {
+ if (isWrapped(Server.prototype[method])) {
+ this._unwrap(Server.prototype, method);
+ }
+ this._wrap(Server.prototype, method, patcher);
+ }
+ }
+
+ // ServerSession (low-level)
+ const ServerSession = moduleExports.ServerSession;
+ if (ServerSession?.prototype) {
+ const sessionOps: Array<[string, string]> = [
+ ['sendRequest', 'send_request'],
+ ['sendNotification', 'send_notification'],
+ ['sendLogMessage', 'send_log'],
+ ];
+
+ for (const [method, endpoint] of sessionOps) {
+ if (typeof ServerSession.prototype[method] === 'function') {
+ if (isWrapped(ServerSession.prototype[method])) {
+ this._unwrap(ServerSession.prototype, method);
+ }
+ this._wrap(
+ ServerSession.prototype,
+ method,
+ patchServerSessionOperation(endpoint, this.tracer, this._mcpVersion),
+ );
+ }
+ }
+ }
+ }
+
+ private _unpatchServer(moduleExports: any): void {
+ const Server = moduleExports.Server;
+ if (Server?.prototype) {
+ for (const method of ['run', 'callTool', 'listTools', 'readResource', 'listResources']) {
+ if (isWrapped(Server.prototype[method])) {
+ this._unwrap(Server.prototype, method);
+ }
+ }
+ }
+
+ const ServerSession = moduleExports.ServerSession;
+ if (ServerSession?.prototype) {
+ for (const method of ['sendRequest', 'sendNotification', 'sendLogMessage']) {
+ if (isWrapped(ServerSession.prototype[method])) {
+ this._unwrap(ServerSession.prototype, method);
+ }
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------------
+ // Transports (stdio, sse, websocket, streamablehttp)
+ // -----------------------------------------------------------------------
+
+ private _patchTransports(moduleExports: any): void {
+ const transportClasses: Array<[string, string, string]> = [
+ // [exportName, endpoint, methodName]
+ ['StdioClientTransport', 'transport stdio_client', 'connect'],
+ ['StdioServerTransport', 'transport stdio_server', 'connect'],
+ ['SSEClientTransport', 'transport sse_client', 'connect'],
+ ['SSEServerTransport', 'transport sse_server', 'connect'],
+ ['StreamableHTTPClientTransport', 'transport http_client', 'connect'],
+ ['StreamableHTTPServerTransport', 'transport http_server', 'connect'],
+ ];
+
+ for (const [exportName, endpoint, method] of transportClasses) {
+ const TransportClass = moduleExports[exportName];
+ if (!TransportClass?.prototype) continue;
+
+ // Patch connect method on transport instances
+ if (typeof TransportClass.prototype[method] === 'function') {
+ if (isWrapped(TransportClass.prototype[method])) {
+ this._unwrap(TransportClass.prototype, method);
+ }
+ this._wrap(
+ TransportClass.prototype,
+ method,
+ patchTransport(endpoint, this.tracer, this._mcpVersion),
+ );
+ }
+ }
+
+ // Also try to patch transport factory functions (e.g. stdio_client, sse_client)
+ const factoryFunctions: Array<[string, string]> = [
+ ['stdio_client', 'transport stdio_client'],
+ ['stdio_server', 'transport stdio_server'],
+ ['sse_client', 'transport sse_client'],
+ ['sse_server', 'transport sse_server'],
+ ['streamablehttp_client', 'transport http_client'],
+ ['streamablehttp_server', 'transport http_server'],
+ ];
+
+ for (const [fnName, endpoint] of factoryFunctions) {
+ if (typeof moduleExports[fnName] === 'function') {
+ if (isWrapped(moduleExports[fnName])) {
+ this._unwrap(moduleExports, fnName);
+ }
+ this._wrap(
+ moduleExports,
+ fnName,
+ patchTransport(endpoint, this.tracer, this._mcpVersion),
+ );
+ }
+ }
+ }
+
+ private _unpatchTransports(moduleExports: any): void {
+ const transportClasses = [
+ 'StdioClientTransport', 'StdioServerTransport',
+ 'SSEClientTransport', 'SSEServerTransport',
+ 'StreamableHTTPClientTransport', 'StreamableHTTPServerTransport',
+ ];
+ for (const exportName of transportClasses) {
+ const TransportClass = moduleExports[exportName];
+ if (TransportClass?.prototype && isWrapped(TransportClass.prototype.connect)) {
+ this._unwrap(TransportClass.prototype, 'connect');
+ }
+ }
+
+ const factoryFns = [
+ 'stdio_client', 'stdio_server', 'sse_client', 'sse_server',
+ 'streamablehttp_client', 'streamablehttp_server',
+ ];
+ for (const fnName of factoryFns) {
+ if (isWrapped(moduleExports[fnName])) {
+ this._unwrap(moduleExports, fnName);
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------------
+ // FastMCP
+ // -----------------------------------------------------------------------
+
+ private _patchFastMCP(moduleExports: any): void {
+ const FastMCP = moduleExports.FastMCP;
+ if (!FastMCP?.prototype) return;
+
+ const fastMCPMethods: Array<[string, (...args: any[]) => any]> = [
+ ['run', patchServerRun(this.tracer, this._mcpVersion)],
+ ['callTool', patchServerCallTool(this.tracer, this._mcpVersion)],
+ ['listTools', patchServerListTools(this.tracer, this._mcpVersion)],
+ ['readResource', patchServerReadResource(this.tracer, this._mcpVersion)],
+ ['listResources', patchServerListResources(this.tracer, this._mcpVersion)],
+ ['getPrompt', patchGetPrompt(this.tracer, this._mcpVersion)],
+ ['listPrompts', patchListPrompts(this.tracer, this._mcpVersion)],
+ ];
+
+ for (const [method, patcher] of fastMCPMethods) {
+ if (typeof FastMCP.prototype[method] === 'function') {
+ if (isWrapped(FastMCP.prototype[method])) {
+ this._unwrap(FastMCP.prototype, method);
+ }
+ this._wrap(FastMCP.prototype, method, patcher);
+ }
+ }
+ }
+
+ private _unpatchFastMCP(moduleExports: any): void {
+ const FastMCP = moduleExports.FastMCP;
+ if (!FastMCP?.prototype) return;
+
+ for (const method of [
+ 'run', 'callTool', 'listTools', 'readResource', 'listResources', 'getPrompt', 'listPrompts',
+ ]) {
+ if (isWrapped(FastMCP.prototype[method])) {
+ this._unwrap(FastMCP.prototype, method);
+ }
+ }
+ }
+}
diff --git a/sdk/typescript/src/instrumentation/mcp/wrapper.ts b/sdk/typescript/src/instrumentation/mcp/wrapper.ts
new file mode 100644
index 00000000..615e539f
--- /dev/null
+++ b/sdk/typescript/src/instrumentation/mcp/wrapper.ts
@@ -0,0 +1,654 @@
+import { SpanKind, Tracer, context, trace, Span, Attributes } from '@opentelemetry/api';
+import { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_DEPLOYMENT_ENVIRONMENT, ATTR_TELEMETRY_SDK_NAME } from '@opentelemetry/semantic-conventions';
+import OpenlitConfig from '../../config';
+import OpenLitHelper from '../../helpers';
+import { applyCustomSpanAttributes } from '../../helpers';
+import { SDK_NAME } from '../../constant';
+import SemanticConvention from '../../semantic-convention';
+import Metrics from '../../otel/metrics';
+
+const MCP_SYSTEM = 'mcp';
+
+function getStringField(obj: unknown, key: string): string | undefined {
+ if (obj && typeof obj === 'object' && key in (obj as Record<string, unknown>)) {
+ const v = (obj as Record<string, unknown>)[key];
+ return typeof v === 'string' ? v : undefined;
+ }
+ return undefined;
+}
+
+function safeStringify(val: unknown, maxLen = 4096): string | undefined {
+ try {
+ const s = JSON.stringify(val, (_k, v) => (typeof v === 'bigint' ? String(v) : v));
+ return s.length > maxLen ? s.slice(0, maxLen) : s;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Extracts the first meaningful string argument — used for tool name, prompt name,
+ * or resource URI when the first arg is a plain string instead of an object.
+ */
+function extractStringArg(args: unknown[]): string | undefined {
+ if (args.length > 0 && typeof args[0] === 'string') return args[0];
+ return undefined;
+}
+
+/**
+ * Cache for expensive context extractions, mirroring Python's
+ * MCPInstrumentationContext pattern.
+ */
+class MCPInstrumentationContext {
+ private _methodName: string | undefined;
+ private _toolName: string | undefined;
+ private _resourceUri: string | undefined;
+ private _transportType: string | undefined;
+
+ constructor(
+ readonly instance: unknown,
+ readonly args: unknown[],
+ readonly kwargs: Record<string, unknown>,
+ ) {}
+
+ get methodName(): string {
+ if (this._methodName === undefined) this._methodName = this.extractMethodName();
+ return this._methodName;
+ }
+
+ get toolName(): string | undefined {
+ if (this._toolName === undefined) this._toolName = this.extractToolName();
+ return this._toolName;
+ }
+
+ get resourceUri(): string | undefined {
+ if (this._resourceUri === undefined) this._resourceUri = this.extractResourceUri();
+ return this._resourceUri;
+ }
+
+ get transportType(): string {
+ if (this._transportType === undefined) this._transportType = this.extractTransportType();
+ return this._transportType;
+ }
+
+ private extractMethodName(): string {
+ const name = this.kwargs['name'];
+ if (typeof name === 'string') return name;
+ const method = this.kwargs['method'];
+ if (typeof method === 'string') return method;
+ const strArg = extractStringArg(this.args);
+ if (strArg) return strArg;
+ const inst = this.instance as Record<string, unknown> | null;
+ if (inst && typeof inst['name'] === 'string') return inst['name'] as string;
+ return 'unknown';
+ }
+
+ private extractToolName(): string | undefined {
+ const name = getStringField(this.kwargs, 'name');
+ if (name) return name;
+ const strArg = extractStringArg(this.args);
+ if (strArg) return strArg;
+ const arg0 = this.args[0];
+ if (arg0 && typeof arg0 === 'object') {
+ const n = getStringField(arg0, 'name');
+ if (n) return n;
+ }
+ return undefined;
+ }
+
+ private extractResourceUri(): string | undefined {
+ const uri = getStringField(this.kwargs, 'uri');
+ if (uri) return uri;
+ const strArg = extractStringArg(this.args);
+ if (strArg) return strArg;
+ const arg0 = this.args[0];
+ if (arg0 && typeof arg0 === 'object') {
+ const u = getStringField(arg0, 'uri');
+ if (u) return u;
+ }
+ return undefined;
+ }
+
+ private extractTransportType(): string {
+ // Detect from instance class name / module
+ const inst = this.instance as Record<string, unknown> | null;
+ if (inst) {
+ const className = (inst.constructor?.name || '').toLowerCase();
+ if (className.includes('stdio')) return SemanticConvention.MCP_TRANSPORT_STDIO;
+ if (className.includes('sse')) return SemanticConvention.MCP_TRANSPORT_SSE;
+ if (className.includes('websocket')) return SemanticConvention.MCP_TRANSPORT_WEBSOCKET;
+ }
+ // Detect from kwargs
+ if (this.kwargs['command'] || this.kwargs['args']) return SemanticConvention.MCP_TRANSPORT_STDIO;
+ if (this.kwargs['url']) {
+ const url = String(this.kwargs['url']);
+ if (url.includes('sse')) return SemanticConvention.MCP_TRANSPORT_SSE;
+ if (url.includes('ws')) return SemanticConvention.MCP_TRANSPORT_WEBSOCKET;
+ }
+ return SemanticConvention.MCP_TRANSPORT_STDIO;
+ }
+}
+
+/** Core MCP span attributes set on every span. */
+function setMCPSpanAttributes(
+ span: Span,
+ operationName: string,
+ ctx: MCPInstrumentationContext,
+ captureMessageContent: boolean,
+ version: string,
+): void {
+ const applicationName = OpenlitConfig.applicationName || '';
+ const environment = OpenlitConfig.environment || '';
+
+ span.setAttribute(ATTR_TELEMETRY_SDK_NAME, SDK_NAME);
+ span.setAttribute(SemanticConvention.MCP_OPERATION, operationName);
+ span.setAttribute(SemanticConvention.MCP_SYSTEM, MCP_SYSTEM);
+ span.setAttribute(SemanticConvention.MCP_SDK_VERSION, version);
+ span.setAttribute(SEMRESATTRS_DEPLOYMENT_ENVIRONMENT, environment);
+ span.setAttribute(SEMRESATTRS_SERVICE_NAME, applicationName);
+ span.setAttribute(SemanticConvention.MCP_TRANSPORT_TYPE, ctx.transportType);
+
+ if (ctx.toolName) {
+ span.setAttribute(SemanticConvention.MCP_TOOL_NAME, ctx.toolName);
+ }
+ if (ctx.resourceUri) {
+ span.setAttribute(SemanticConvention.MCP_RESOURCE_URI, ctx.resourceUri);
+ }
+ if (ctx.methodName) {
+ span.setAttribute(SemanticConvention.MCP_METHOD, ctx.methodName);
+ }
+
+ applyCustomSpanAttributes(span);
+}
+
+/** Capture request payload if enabled. */
+function captureRequestPayload(
+ span: Span,
+ ctx: MCPInstrumentationContext,
+ captureMessageContent: boolean,
+): void {
+ if (!captureMessageContent) return;
+ const payload = safeStringify({ method: ctx.methodName, kwargs: ctx.kwargs });
+ if (payload) {
+ span.setAttribute(SemanticConvention.MCP_REQUEST_PAYLOAD, payload);
+ }
+}
+
+/** Capture response payload if enabled. */
+function captureResponsePayload(
+ span: Span,
+ response: unknown,
+ captureMessageContent: boolean,
+): void {
+ if (!captureMessageContent || response === null || response === undefined) return;
+ const payload = safeStringify(response);
+ if (payload) {
+ span.setAttribute(SemanticConvention.MCP_RESPONSE_PAYLOAD, payload);
+ }
+}
+
+/** Record MCP-specific metrics, mirroring Python's record_mcp_metrics. */
+function recordMCPMetrics(params: {
+ mcpOperation: string;
+ mcpMethod: string;
+ mcpTransportType: string;
+ toolName?: string;
+ resourceUri?: string;
+ promptName?: string;
+ duration: number;
+ requestSize?: number;
+ responseSize?: number;
+ isError: boolean;
+}): void {
+ const {
+ mcpOperation,
+ mcpMethod,
+ mcpTransportType,
+ toolName,
+ resourceUri,
+ promptName,
+ duration,
+ requestSize,
+ responseSize,
+ isError,
+ } = params;
+
+ const applicationName = OpenlitConfig.applicationName || '';
+ const environment = OpenlitConfig.environment || '';
+
+ const enhancedAttributes: Attributes = {
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,
+ [SEMRESATTRS_SERVICE_NAME]: applicationName,
+ [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: environment,
+ [SemanticConvention.MCP_OPERATION]: mcpOperation,
+ [SemanticConvention.MCP_METHOD]: mcpMethod,
+ [SemanticConvention.MCP_SYSTEM]: MCP_SYSTEM,
+ [SemanticConvention.MCP_TRANSPORT_TYPE]: mcpTransportType,
+ };
+
+ if (toolName) enhancedAttributes[SemanticConvention.MCP_TOOL_NAME] = toolName;
+ if (resourceUri) enhancedAttributes[SemanticConvention.MCP_RESOURCE_URI] = resourceUri;
+ if (promptName) enhancedAttributes[SemanticConvention.MCP_PROMPT_NAME] = promptName;
+
+ if (mcpTransportType === 'stdio') {
+ enhancedAttributes[SemanticConvention.MCP_CLIENT_TYPE] = 'external_spawn';
+ } else if (mcpTransportType === 'sse' || mcpTransportType === 'websocket') {
+ enhancedAttributes[SemanticConvention.MCP_CLIENT_TYPE] = 'network_client';
+ }
+
+ Metrics.mcpRequests?.add(1, enhancedAttributes);
+ Metrics.mcpClientOperationDuration?.record(duration, enhancedAttributes);
+
+ if (requestSize !== undefined) {
+ Metrics.mcpRequestSize?.record(requestSize, enhancedAttributes);
+ }
+ if (responseSize !== undefined) {
+ Metrics.mcpResponseSize?.record(responseSize, enhancedAttributes);
+ }
+ if (mcpTransportType) {
+ Metrics.mcpTransportUsage?.add(1, enhancedAttributes);
+ }
+ if (toolName) {
+ Metrics.mcpToolCalls?.add(1, enhancedAttributes);
+ }
+ if (resourceUri) {
+ Metrics.mcpResourceReads?.add(1, enhancedAttributes);
+ }
+ if (promptName) {
+ Metrics.mcpPromptGets?.add(1, enhancedAttributes);
+ }
+
+ const errorCount = isError ? 1 : 0;
+ Metrics.mcpErrors?.add(errorCount, {
+ ...enhancedAttributes,
+ 'mcp.error': isError,
+ } as Attributes);
+
+ const successRate = isError ? 0.0 : 1.0;
+ Metrics.mcpOperationSuccessRate?.record(successRate, enhancedAttributes);
+}
+
+// ---------------------------------------------------------------------------
+// Span name helpers — align with Python's get_enhanced_span_name
+// ---------------------------------------------------------------------------
+
+function spanNameForToolCall(method: string, _toolName?: string): string {
+ if (method === 'listTools' || method === 'list_tools') return 'mcp tools/list';
+ return `mcp tools/call`;
+}
+
+function spanNameForResource(method: string): string {
+ if (method === 'listResources' || method === 'list_resources') return 'mcp resources/list';
+ if (method === 'readResource' || method === 'read_resource') return 'mcp resources/read';
+ return 'mcp resources/operation';
+}
+
+function spanNameForPrompt(method: string): string {
+ if (method === 'listPrompts' || method === 'list_prompts') return 'mcp prompts/list';
+ if (method === 'getPrompt' || method === 'get_prompt') return 'mcp prompts/get';
+ return 'mcp prompts/operation';
+}
+
+function spanNameForTransport(endpoint: string): string {
+ if (endpoint.includes('stdio')) return 'mcp transport/stdio';
+ if (endpoint.includes('sse')) return 'mcp transport/sse';
+ if (endpoint.includes('websocket')) return 'mcp transport/websocket';
+ if (endpoint.includes('streamablehttp') || endpoint.includes('streamable_http') || endpoint.includes('http')) return 'mcp transport/http';
+ return 'mcp transport/operation';
+}
+
+// ---------------------------------------------------------------------------
+// Generic span wrapper — used for all MCP operations
+// ---------------------------------------------------------------------------
+
+interface MCPSpanOptions {
+ tracer: Tracer;
+ spanName: string;
+ spanKind: SpanKind;
+ operationName: string;
+ ctx: MCPInstrumentationContext;
+ version: string;
+ toolName?: string;
+ resourceUri?: string;
+ promptName?: string;
+ fn: () => Promise<unknown>;
+ onResponse?: (span: Span, response: unknown) => void;
+}
+
+function wrapWithMCPSpan(opts: MCPSpanOptions): Promise<unknown> {
+ const {
+ tracer, spanName, spanKind, operationName, ctx, version,
+ toolName, resourceUri, promptName, fn, onResponse,
+ } = opts;
+ const captureContent = OpenlitConfig.captureMessageContent || false;
+ const span = tracer.startSpan(spanName, { kind: spanKind });
+ const startTime = Date.now();
+
+ return context.with(trace.setSpan(context.active(), span), async () => {
+ try {
+ setMCPSpanAttributes(span, operationName, ctx, captureContent, version);
+ if (toolName) span.setAttribute(SemanticConvention.MCP_TOOL_NAME, toolName);
+ if (resourceUri) span.setAttribute(SemanticConvention.MCP_RESOURCE_URI, resourceUri);
+ if (promptName) span.setAttribute(SemanticConvention.MCP_PROMPT_NAME, promptName);
+ captureRequestPayload(span, ctx, captureContent);
+
+ const response = await fn();
+ const duration = (Date.now() - startTime) / 1000;
+
+ span.setAttribute(SemanticConvention.MCP_CLIENT_OPERATION_DURATION, duration);
+ captureResponsePayload(span, response, captureContent);
+ if (onResponse) onResponse(span, response);
+
+ recordMCPMetrics({
+ mcpOperation: operationName,
+ mcpMethod: ctx.methodName || operationName,
+ mcpTransportType: ctx.transportType,
+ toolName,
+ resourceUri,
+ promptName,
+ duration,
+ isError: false,
+ });
+
+ return response;
+ } catch (error: any) {
+ const duration = (Date.now() - startTime) / 1000;
+ OpenLitHelper.handleException(span, error);
+ span.setAttribute(SemanticConvention.MCP_ERROR_MESSAGE, error?.message || String(error));
+ if (error?.code) {
+ span.setAttribute(SemanticConvention.MCP_ERROR_CODE, String(error.code));
+ }
+
+ recordMCPMetrics({
+ mcpOperation: operationName,
+ mcpMethod: ctx.methodName || operationName,
+ mcpTransportType: ctx.transportType,
+ toolName,
+ resourceUri,
+ promptName,
+ duration,
+ isError: true,
+ });
+
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Client method patchers
+// ---------------------------------------------------------------------------
+
+function patchCallTool(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const toolName = extractStringArg(args) || getStringField(args[0], 'name') || 'unknown';
+ const ctx = new MCPInstrumentationContext(this, args, { name: toolName });
+ const spanName = spanNameForToolCall('callTool', toolName);
+
+ return wrapWithMCPSpan({
+ tracer, spanName, spanKind: SpanKind.CLIENT, operationName: 'tools_call',
+ ctx, version, toolName,
+ fn: () => originalMethod.apply(this, args),
+ onResponse: (span, response: any) => {
+ if (response?.content && OpenlitConfig.captureMessageContent) {
+ span.setAttribute(SemanticConvention.MCP_TOOL_RESULT, safeStringify(response.content) || '');
+ }
+ if (response?.isError) {
+ span.setAttribute(SemanticConvention.MCP_ERROR_MESSAGE, safeStringify(response.content) || 'tool error');
+ }
+ },
+ });
+ };
+ };
+}
+
+function patchListTools(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp tools/list', spanKind: SpanKind.CLIENT, operationName: 'tools_list',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchGetPrompt(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const promptName = extractStringArg(args) || getStringField(args[0], 'name') || 'unknown';
+ const ctx = new MCPInstrumentationContext(this, args, { name: promptName });
+ const spanName = spanNameForPrompt('getPrompt');
+
+ return wrapWithMCPSpan({
+ tracer, spanName, spanKind: SpanKind.CLIENT, operationName: 'prompts_get',
+ ctx, version, promptName,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchListPrompts(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp prompts/list', spanKind: SpanKind.CLIENT, operationName: 'prompts_list',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchReadResource(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const resourceUri = extractStringArg(args) || getStringField(args[0], 'uri') || 'unknown';
+ const ctx = new MCPInstrumentationContext(this, args, { uri: resourceUri });
+ const spanName = spanNameForResource('readResource');
+
+ return wrapWithMCPSpan({
+ tracer, spanName, spanKind: SpanKind.CLIENT, operationName: 'resources_read',
+ ctx, version, resourceUri,
+ fn: () => originalMethod.apply(this, args),
+ onResponse: (span, response: any) => {
+ if (response && OpenlitConfig.captureMessageContent) {
+ if (response.contents) {
+ span.setAttribute(SemanticConvention.MCP_RESOURCE_SIZE, safeStringify(response.contents)?.length || 0);
+ }
+ if (response.mimeType) {
+ span.setAttribute(SemanticConvention.MCP_RESOURCE_MIME_TYPE, String(response.mimeType));
+ }
+ }
+ },
+ });
+ };
+ };
+}
+
+function patchListResources(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp resources/list', spanKind: SpanKind.CLIENT, operationName: 'resources_list',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+// ---------------------------------------------------------------------------
+// ClientSession method patchers (lower-level session operations)
+// ---------------------------------------------------------------------------
+
+function patchClientSessionSendRequest(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp transport/request', spanKind: SpanKind.CLIENT, operationName: 'transport_request',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchClientSessionInitialize(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp initialize', spanKind: SpanKind.CLIENT, operationName: 'initialize',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Server method patchers
+// ---------------------------------------------------------------------------
+
+function patchServerRun(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp server/run', spanKind: SpanKind.SERVER, operationName: 'server_run',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchServerCallTool(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const toolName = extractStringArg(args) || getStringField(args[0], 'name') || 'unknown';
+ const ctx = new MCPInstrumentationContext(this, args, { name: toolName });
+ return wrapWithMCPSpan({
+ tracer, spanName: spanNameForToolCall('callTool', toolName), spanKind: SpanKind.SERVER, operationName: 'tools_call',
+ ctx, version, toolName,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchServerListTools(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp tools/list', spanKind: SpanKind.SERVER, operationName: 'tools_list',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchServerReadResource(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const resourceUri = extractStringArg(args) || getStringField(args[0], 'uri') || 'unknown';
+ const ctx = new MCPInstrumentationContext(this, args, { uri: resourceUri });
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp resources/read', spanKind: SpanKind.SERVER, operationName: 'resources_read',
+ ctx, version, resourceUri,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+function patchServerListResources(tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ return wrapWithMCPSpan({
+ tracer, spanName: 'mcp resources/list', spanKind: SpanKind.SERVER, operationName: 'resources_list',
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Transport method patchers
+// ---------------------------------------------------------------------------
+
+function patchTransport(endpoint: string, tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ const spanName = spanNameForTransport(endpoint);
+ const isClient = endpoint.includes('client');
+ const kind = isClient ? SpanKind.CLIENT : SpanKind.SERVER;
+ return wrapWithMCPSpan({
+ tracer, spanName, spanKind: kind, operationName: endpoint,
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+// ---------------------------------------------------------------------------
+// ServerSession method patchers
+// ---------------------------------------------------------------------------
+
+function patchServerSessionOperation(endpoint: string, tracer: Tracer, version: string): any {
+ return (originalMethod: (...args: any[]) => any) => {
+ return async function (this: any, ...args: any[]) {
+ const ctx = new MCPInstrumentationContext(this, args, {});
+ const spanName = `mcp server/${endpoint}`;
+ return wrapWithMCPSpan({
+ tracer, spanName, spanKind: SpanKind.SERVER, operationName: endpoint,
+ ctx, version,
+ fn: () => originalMethod.apply(this, args),
+ });
+ };
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Exports
+// ---------------------------------------------------------------------------
+
+export {
+ MCPInstrumentationContext,
+ setMCPSpanAttributes,
+ captureRequestPayload,
+ captureResponsePayload,
+ recordMCPMetrics,
+ wrapWithMCPSpan,
+ patchCallTool,
+ patchListTools,
+ patchGetPrompt,
+ patchListPrompts,
+ patchReadResource,
+ patchListResources,
+ patchClientSessionSendRequest,
+ patchClientSessionInitialize,
+ patchServerRun,
+ patchServerCallTool,
+ patchServerListTools,
+ patchServerReadResource,
+ patchServerListResources,
+ patchTransport,
+ patchServerSessionOperation,
+};
diff --git a/sdk/typescript/src/otel/metrics.ts b/sdk/typescript/src/otel/metrics.ts
index 1341b439..a3f08a29 100644
--- a/sdk/typescript/src/otel/metrics.ts
+++ b/sdk/typescript/src/otel/metrics.ts
@@ -48,6 +48,18 @@ export default class Metrics {
static dbRequests: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
static guardRequests: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ // MCP metrics
+ static mcpRequests: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ static mcpClientOperationDuration: ReturnType<ReturnType<typeof metrics.getMeter>['createHistogram']>;
+ static mcpRequestSize: ReturnType<ReturnType<typeof metrics.getMeter>['createHistogram']>;
+ static mcpResponseSize: ReturnType<ReturnType<typeof metrics.getMeter>['createHistogram']>;
+ static mcpToolCalls: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ static mcpResourceReads: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ static mcpPromptGets: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ static mcpTransportUsage: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ static mcpErrors: ReturnType<ReturnType<typeof metrics.getMeter>['createCounter']>;
+ static mcpOperationSuccessRate: ReturnType<ReturnType<typeof metrics.getMeter>['createHistogram']>;
+
static initializeMetrics() {
this.genaiClientUsageTokens = this.meter.createHistogram(
SemanticConvention.GEN_AI_CLIENT_TOKEN_USAGE,
@@ -135,6 +147,57 @@ export default class Metrics {
description: 'Number of guard evaluations.',
unit: '1',
});
+
+ // MCP metrics
+ this.mcpRequests = this.meter.createCounter(SemanticConvention.MCP_REQUESTS, {
+ description: 'Number of MCP requests.',
+ unit: '1',
+ });
+ this.mcpClientOperationDuration = this.meter.createHistogram(
+ SemanticConvention.MCP_CLIENT_OPERATION_DURATION_METRIC,
+ {
+ description: 'MCP client operation duration',
+ unit: 's',
+ advice: {
+ explicitBucketBoundaries: GEN_AI_CLIENT_OPERATION_DURATION_BUCKETS,
+ },
+ },
+ );
+ this.mcpRequestSize = this.meter.createHistogram(SemanticConvention.MCP_REQUEST_SIZE, {
+ description: 'MCP request payload size in bytes',
+ unit: 'By',
+ });
+ this.mcpResponseSize = this.meter.createHistogram(SemanticConvention.MCP_RESPONSE_SIZE_METRIC, {
+ description: 'MCP response payload size in bytes',
+ unit: 'By',
+ });
+ this.mcpToolCalls = this.meter.createCounter(SemanticConvention.MCP_TOOL_CALLS, {
+ description: 'Number of MCP tool calls.',
+ unit: '1',
+ });
+ this.mcpResourceReads = this.meter.createCounter(SemanticConvention.MCP_RESOURCE_READS, {
+ description: 'Number of MCP resource reads.',
+ unit: '1',
+ });
+ this.mcpPromptGets = this.meter.createCounter(SemanticConvention.MCP_PROMPT_GETS, {
+ description: 'Number of MCP prompt gets.',
+ unit: '1',
+ });
+ this.mcpTransportUsage = this.meter.createCounter(SemanticConvention.MCP_TRANSPORT_USAGE, {
+ description: 'Number of MCP transport operations.',
+ unit: '1',
+ });
+ this.mcpErrors = this.meter.createCounter(SemanticConvention.MCP_ERRORS, {
+ description: 'Number of MCP errors.',
+ unit: '1',
+ });
+ this.mcpOperationSuccessRate = this.meter.createHistogram(
+ SemanticConvention.MCP_OPERATION_SUCCESS_RATE,
+ {
+ description: 'MCP operation success rate (0.0 = failure, 1.0 = success)',
+ unit: '1',
+ },
+ );
}
static setup(options: SetupMetricsOptions) {
diff --git a/sdk/typescript/src/semantic-convention.ts b/sdk/typescript/src/semantic-convention.ts
index fb13e034..46c45d68 100644
--- a/sdk/typescript/src/semantic-convention.ts
+++ b/sdk/typescript/src/semantic-convention.ts
@@ -161,15 +161,12 @@ export default class SemanticConvention {
static GEN_AI_RETRIEVAL_DOCUMENTS = 'gen_ai.retrieval.documents';
static GEN_AI_RETRIEVAL_DOCUMENT_COUNT = 'gen_ai.retrieval.document_count';
static GEN_AI_DATA_SOURCE_ID = 'gen_ai.data_source.id';
-
- // AI21 Conversational RAG (OpenLIT extensions, mirrored from the Python SDK;
- // not part of the OTel GenAI semconv).
- static GEN_AI_RAG_MAX_SEGMENTS = 'gen_ai.rag.max_segments';
- static GEN_AI_RAG_STRATEGY = 'gen_ai.rag.strategy';
static GEN_AI_RAG_SIMILARITY_THRESHOLD = 'gen_ai.rag.similarity_threshold';
- static GEN_AI_RAG_MAX_NEIGHBORS = 'gen_ai.rag.max_neighbors';
static GEN_AI_RAG_DOCUMENTS_PATH = 'gen_ai.rag.documents_path';
static GEN_AI_RAG_FILE_IDS = 'gen_ai.rag.file_ids';
+ static GEN_AI_RAG_MAX_NEIGHBORS = 'gen_ai.rag.max_neighbors';
+ static GEN_AI_RAG_MAX_SEGMENTS = 'gen_ai.rag.max_segments';
+ static GEN_AI_RAG_STRATEGY = 'gen_ai.rag.strategy';
// Agent (OTel Semconv)
static GEN_AI_AGENT_NAME = 'gen_ai.agent.name';
@@ -246,6 +243,176 @@ export default class SemanticConvention {
static GEN_AI_SYSTEM_GOOGLE_ADK = 'google_adk';
static GEN_AI_SYSTEM_STRANDS = 'strands_agents';
static GEN_AI_SYSTEM_CURSOR = 'cursor';
+ static GEN_AI_SYSTEM_MCP = 'mcp';
+
+ // ----- MCP (Model Context Protocol) -----
+ // Operation types
+ static GEN_AI_OPERATION_TYPE_MCP_TOOL_CALL = 'mcp_tool_call';
+ static GEN_AI_OPERATION_TYPE_MCP_TOOL_LIST = 'mcp_tool_list';
+ static GEN_AI_OPERATION_TYPE_MCP_RESOURCE_READ = 'mcp_resource_read';
+ static GEN_AI_OPERATION_TYPE_MCP_RESOURCE_LIST = 'mcp_resource_list';
+ static GEN_AI_OPERATION_TYPE_MCP_REQUEST = 'mcp_request';
+ static GEN_AI_OPERATION_TYPE_MCP_RESPONSE = 'mcp_response';
+ static GEN_AI_OPERATION_TYPE_MCP_SERVER = 'mcp_server';
+ static GEN_AI_OPERATION_TYPE_MCP_CLIENT = 'mcp_client';
+
+ // Core MCP attributes
+ static MCP_OPERATION = 'mcp.operation.name';
+ static MCP_SYSTEM = 'mcp.system';
+ static MCP_SDK_VERSION = 'mcp.sdk.version';
+ static MCP_METHOD = 'mcp.method';
+ static MCP_MESSAGE_ID = 'mcp.message_id';
+ static MCP_JSONRPC_VERSION = 'mcp.jsonrpc_version';
+ static MCP_PARAMS = 'mcp.params';
+ static MCP_RESULT = 'mcp.result';
+
+ // MCP error attributes
+ static MCP_ERROR_CODE = 'mcp.error.code';
+ static MCP_ERROR_MESSAGE = 'mcp.error.message';
+ static MCP_ERROR_DATA = 'mcp.error.data';
+
+ // MCP tool attributes
+ static MCP_TOOL_NAME = 'mcp.tool.name';
+ static MCP_TOOL_DESCRIPTION = 'mcp.tool.description';
+ static MCP_TOOL_ARGUMENTS = 'mcp.tool.arguments';
+ static MCP_TOOL_RESULT = 'mcp.tool.result';
+
+ // MCP resource attributes
+ static MCP_RESOURCE_URI = 'mcp.resource.uri';
+ static MCP_RESOURCE_NAME = 'mcp.resource.name';
+ static MCP_RESOURCE_DESCRIPTION = 'mcp.resource.description';
+ static MCP_RESOURCE_MIME_TYPE = 'mcp.resource.mime_type';
+ static MCP_RESOURCE_SIZE = 'mcp.resource.size';
+
+ // MCP transport attributes
+ static MCP_TRANSPORT_TYPE = 'mcp.transport.type';
+ static MCP_TRANSPORT_STDIO = 'stdio';
+ static MCP_TRANSPORT_SSE = 'sse';
+ static MCP_TRANSPORT_WEBSOCKET = 'websocket';
+
+ // MCP payload attributes
+ static MCP_REQUEST_PAYLOAD = 'mcp.request.payload';
+ static MCP_RESPONSE_PAYLOAD = 'mcp.response.payload';
+
+ // MCP client/server attributes
+ static MCP_CLIENT_OPERATION_DURATION = 'mcp.client.operation.duration';
+ static MCP_SERVER_NAME = 'mcp.server.name';
+ static MCP_SERVER_VERSION = 'mcp.server.version';
+ static MCP_CLIENT_VERSION = 'mcp.client.version';
+ static MCP_CLIENT_TYPE = 'mcp.client.type';
+ static MCP_RESPONSE_SIZE = 'mcp.response.size';
+
+ // MCP prompt attributes
+ static MCP_PROMPT_NAME = 'mcp.prompt.name';
+ static MCP_PROMPT_DESCRIPTION = 'mcp.prompt.description';
+
+ // MCP metric names
+ static MCP_REQUESTS = 'mcp.requests';
+ static MCP_CLIENT_OPERATION_DURATION_METRIC = 'mcp.client.operation.duration';
+ static MCP_REQUEST_SIZE = 'mcp.request.size';
+ static MCP_RESPONSE_SIZE_METRIC = 'mcp.response.size';
+ static MCP_TOOL_CALLS = 'mcp.tool.calls';
+ static MCP_RESOURCE_READS = 'mcp.resource.reads';
+ static MCP_PROMPT_GETS = 'mcp.prompt.gets';
+ static MCP_TRANSPORT_USAGE = 'mcp.transport.usage';
+ static MCP_ERRORS = 'mcp.errors';
+ static MCP_OPERATION_SUCCESS_RATE = 'mcp.operation.success_rate';
+
+ // FastMCP framework attributes
+ static MCP_FASTMCP_SERVER_DEBUG_MODE = 'mcp.fastmcp.server.debug_mode';
+ static MCP_FASTMCP_SERVER_LOG_LEVEL = 'mcp.fastmcp.server.log_level';
+ static MCP_FASTMCP_SERVER_HOST = 'mcp.fastmcp.server.host';
+ static MCP_FASTMCP_SERVER_PORT = 'mcp.fastmcp.server.port';
+ static MCP_FASTMCP_SERVER_TRANSPORT = 'mcp.fastmcp.server.transport';
+ static MCP_FASTMCP_TOOL_ANNOTATIONS = 'mcp.fastmcp.tool.annotations';
+ static MCP_FASTMCP_RESOURCE_MIME_TYPE = 'mcp.fastmcp.resource.mime_type';
+ static MCP_FASTMCP_PROMPT_ARGUMENTS = 'mcp.fastmcp.prompt.arguments';
+ static MCP_FASTMCP_TOOL_STRUCTURED_OUTPUT = 'mcp.fastmcp.tool.structured_output';
+ static MCP_FASTMCP_SERVER_INSTRUCTIONS = 'mcp.fastmcp.server.instructions';
+ static MCP_FASTMCP_SERVER_LIFESPAN = 'mcp.fastmcp.server.lifespan';
+ static MCP_FASTMCP_MOUNT_PATH = 'mcp.fastmcp.mount_path';
+ static MCP_FASTMCP_SSE_PATH = 'mcp.fastmcp.sse_path';
+ static MCP_FASTMCP_MESSAGE_PATH = 'mcp.fastmcp.message_path';
+ static MCP_FASTMCP_STREAMABLE_HTTP_PATH = 'mcp.fastmcp.streamable_http_path';
+ static MCP_FASTMCP_JSON_RESPONSE = 'mcp.fastmcp.json_response';
+ static MCP_FASTMCP_STATELESS_HTTP = 'mcp.fastmcp.stateless_http';
+
+ // MCP auth & security attributes
+ static MCP_AUTH_CLIENT_ID = 'mcp.auth.client_id';
+ static MCP_AUTH_SCOPES = 'mcp.auth.scopes';
+ static MCP_AUTH_GRANT_TYPE = 'mcp.auth.grant_type';
+ static MCP_AUTH_TOKEN_TYPE = 'mcp.auth.token_type';
+ static MCP_AUTH_EXPIRES_AT = 'mcp.auth.expires_at';
+ static MCP_AUTH_AUTHORIZATION_CODE = 'mcp.auth.authorization_code';
+ static MCP_AUTH_REDIRECT_URI = 'mcp.auth.redirect_uri';
+ static MCP_AUTH_STATE = 'mcp.auth.state';
+ static MCP_AUTH_CODE_CHALLENGE = 'mcp.auth.code_challenge';
+ static MCP_AUTH_RESOURCE_INDICATOR = 'mcp.auth.resource_indicator';
+ static MCP_SECURITY_TRANSPORT_SECURITY = 'mcp.security.transport_security';
+
+ // MCP session attributes
+ static MCP_SESSION_READ_TIMEOUT = 'mcp.session.read_timeout';
+ static MCP_SESSION_REQUEST_TIMEOUT = 'mcp.session.request_timeout';
+ static MCP_SESSION_SAMPLING_SUPPORT = 'mcp.session.sampling_support';
+ static MCP_SESSION_ELICITATION_SUPPORT = 'mcp.session.elicitation_support';
+ static MCP_SESSION_ROOTS_SUPPORT = 'mcp.session.roots_support';
+ static MCP_SESSION_CLIENT_INFO_NAME = 'mcp.session.client_info.name';
+ static MCP_SESSION_CLIENT_INFO_VERSION = 'mcp.session.client_info.version';
+ static MCP_SESSION_STATELESS = 'mcp.session.stateless';
+ static MCP_SESSION_RAISE_EXCEPTIONS = 'mcp.session.raise_exceptions';
+ static MCP_SESSION_PROGRESS_TOKEN = 'mcp.session.progress_token';
+
+ // MCP websocket attributes
+ static MCP_WEBSOCKET_URL = 'mcp.websocket.url';
+ static MCP_WEBSOCKET_SUBPROTOCOL = 'mcp.websocket.subprotocol';
+
+ // MCP performance attributes
+ static MCP_TOOL_EXECUTION_TIME = 'mcp.tool.execution_time';
+ static MCP_RESOURCE_READ_TIME = 'mcp.resource.read_time';
+ static MCP_PROMPT_RENDER_TIME = 'mcp.prompt.render_time';
+ static MCP_TRANSPORT_CONNECTION_TIME = 'mcp.transport.connection_time';
+
+ // MCP progress attributes
+ static MCP_PROGRESS_COMPLETION_PERCENTAGE = 'mcp.progress.completion_percentage';
+ static MCP_PROGRESS_TOTAL = 'mcp.progress.total';
+ static MCP_PROGRESS_MESSAGE = 'mcp.progress.message';
+ static MCP_PROGRESS_CONTEXT_CURRENT = 'mcp.progress.context.current';
+ static MCP_PROGRESS_CONTEXT_TOTAL = 'mcp.progress.context.total';
+
+ // MCP sampling attributes
+ static MCP_SAMPLING_MAX_TOKENS = 'mcp.sampling.max_tokens';
+ static MCP_SAMPLING_MESSAGES = 'mcp.sampling.messages';
+
+ // MCP elicitation attributes
+ static MCP_ELICITATION_ACTION = 'mcp.elicitation.action';
+
+ // MCP manager attributes
+ static MCP_MANAGER_TYPE = 'mcp.manager.type';
+ static MCP_TOOL_MANAGER_TOOL_COUNT = 'mcp.tool_manager.tool_count';
+ static MCP_TOOL_MANAGER_WARN_DUPLICATES = 'mcp.tool_manager.warn_duplicates';
+ static MCP_RESOURCE_MANAGER_RESOURCE_COUNT = 'mcp.resource_manager.resource_count';
+ static MCP_RESOURCE_MANAGER_WARN_DUPLICATES = 'mcp.resource_manager.warn_duplicates';
+ static MCP_PROMPT_MANAGER_PROMPT_COUNT = 'mcp.prompt_manager.prompt_count';
+ static MCP_PROMPT_MANAGER_WARN_DUPLICATES = 'mcp.prompt_manager.warn_duplicates';
+
+ // MCP memory attributes
+ static MCP_MEMORY_TRANSPORT_TYPE = 'mcp.memory.transport_type';
+ static MCP_MEMORY_CLIENT_SERVER_SESSION = 'mcp.memory.client_server_session';
+
+ // MCP completion attributes
+ static MCP_COMPLETION_REF_TYPE = 'mcp.completion.ref_type';
+ static MCP_COMPLETION_ARGUMENT_NAME = 'mcp.completion.argument_name';
+ static MCP_COMPLETION_ARGUMENT_VALUE = 'mcp.completion.argument_value';
+ static MCP_COMPLETION_CONTEXT_ARGUMENTS = 'mcp.completion.context_arguments';
+ static MCP_COMPLETION_VALUES = 'mcp.completion.values';
+ static MCP_COMPLETION_TOTAL = 'mcp.completion.total';
+ static MCP_COMPLETION_HAS_MORE = 'mcp.completion.has_more';
+
+ // MCP logging and notification attributes
+ static MCP_LOGGING_LEVEL_SET = 'mcp.logging.level_set';
+ static MCP_NOTIFICATION_TYPE = 'mcp.notification.type';
+ static MCP_NOTIFICATION_RELATED_REQUEST_ID = 'mcp.notification.related_request_id';
+ static MCP_PING_RESPONSE_TIME = 'mcp.ping.response_time';
static GEN_AI_OPERATION_TYPE_CREATE_AGENT = 'create_agent';
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
index 3e082012..af418fc9 100644
--- a/sdk/typescript/src/types.ts
+++ b/sdk/typescript/src/types.ts
@@ -3,7 +3,7 @@ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { metrics } from '@opentelemetry/api';
import type { Guard } from './guard/base';
-export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21';
+export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21' | 'mcp';
export type OpenlitInstrumentations = Partial<Record<InstrumentationType, any>>;