Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as Sentry from '@sentry/node';
import { loggingTransport } from '@sentry-internal/node-integration-tests';

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0',
tracesSampleRate: 1.0,
transport: loggingTransport,
enableOpenTelemetrySetup: true,
});

let initializeSpansStarted = 0;
Sentry.getClient()?.on('spanStart', span => {
const attributes = Sentry.spanToJSON(span).attributes;
if (attributes['sentry.op'] === 'mcp.server' && attributes['mcp.method.name'] === 'initialize') {
initializeSpansStarted += 1;
span.setAttribute('test.mcp.initialize_spans_started', initializeSpansStarted);
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,12 @@ Sentry.init({
tracesSampleRate: 1.0,
transport: loggingTransport,
});

let initializeSpansStarted = 0;
Sentry.getClient()?.on('spanStart', span => {
const attributes = Sentry.spanToJSON(span).attributes;
if (attributes['sentry.op'] === 'mcp.server' && attributes['mcp.method.name'] === 'initialize') {
initializeSpansStarted += 1;
span.setAttribute('test.mcp.initialize_spans_started', initializeSpansStarted);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Client } from '@modelcontextprotocol/client';
import { InMemoryTransport, McpServer } from '@modelcontextprotocol/server';
import { wrapMcpServerWithSentry } from '@sentry/node';

const server = wrapMcpServerWithSentry(new McpServer({ name: 'Echo', version: '1.0.0' }));

async function run() {
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'test-client', version: '1.0.0' }, { versionNegotiation: { mode: 'legacy' } });
const originalSend = clientTransport.send.bind(clientTransport);
const requestQueued = new Promise(resolve => {
clientTransport.send = async (...args) => {
const result = await originalSend(...args);
if (args[0]?.method === 'initialize') {
resolve();
}
return result;
};
});

const clientConnection = client.connect(clientTransport);
await requestQueued;
await server.connect(serverTransport);
await clientConnection;

await client.close();
await server.close();
}

run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { wrapMcpServerWithSentry } from '@sentry/node';

const server = wrapMcpServerWithSentry(new McpServer({ name: 'Echo', version: '1.0.0' }));

async function run() {
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'test-client', version: '1.0.0' });
const originalSend = clientTransport.send.bind(clientTransport);
const requestQueued = new Promise(resolve => {
clientTransport.send = async (...args) => {
const result = await originalSend(...args);
if (args[0]?.method === 'initialize') {
resolve();
}
return result;
};
});

const clientConnection = client.connect(clientTransport);
await requestQueued;
await server.connect(serverTransport);
await clientConnection;

await client.close();
await server.close();
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ function mcpSpans(container: SerializedStreamedSpanContainer): SerializedStreame
return container.items.filter(item => item.attributes['sentry.op']?.value === 'mcp.server');
}

function assertInitializeSpan(container: SerializedStreamedSpanContainer): void {
const initializeSpans = mcpSpans(container).filter(
span => span.attributes['mcp.method.name']?.value === 'initialize',
);

expect(initializeSpans).toHaveLength(1);
const initializeSpan = initializeSpans[0]!;
expect(initializeSpan.name).toBe('initialize');
expect(initializeSpan.status).toBe('ok');
expect(initializeSpan.attributes['sentry.op']).toEqual({ type: 'string', value: 'mcp.server' });
expect(initializeSpan.attributes['sentry.origin']).toEqual({ type: 'string', value: 'auto.function.mcp_server' });
expect(initializeSpan.attributes['test.mcp.initialize_spans_started']).toEqual({ type: 'integer', value: 1 });
}

describe('MCP server spans (streamed)', () => {
afterAll(() => {
cleanupChildProcesses();
Expand Down Expand Up @@ -43,4 +57,28 @@ describe('MCP server spans (streamed)', () => {
.completed();
});
});

createEsmAndCjsTests(__dirname, 'scenario-start-v2.mjs', 'instrument.mjs', (createTestRunner, test) => {
test('captures an MCP v2 initialize request queued before transport start once', async () => {
await createTestRunner().expect({ span: assertInitializeSpan }).start().completed();
});
});

createEsmAndCjsTests(
__dirname,
'scenario-v1.mjs',
'instrument.mjs',
(createTestRunner, test) => {
test('captures an MCP v1 initialize request queued before transport start once', async () => {
await createTestRunner().expect({ span: assertInitializeSpan }).start().completed();
});
},
{ additionalDependencies: { '@modelcontextprotocol/sdk': '1.30.0' } },
);

createEsmAndCjsTests(__dirname, 'scenario-start-v2.mjs', 'instrument-otel.mjs', (createTestRunner, test) => {
test('captures the queued request with Sentry OpenTelemetry setup enabled', async () => {
await createTestRunner().expect({ span: assertInitializeSpan }).start().completed();
});
});
});
109 changes: 97 additions & 12 deletions packages/core/src/integrations/mcp-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,79 @@ import { validateMcpServerInstance } from './validation';
*/
const wrappedMcpServerInstances = new WeakSet();

function instrumentTransport(transport: MCPTransport, options: McpServerWrapperOptions): void {
wrapTransportOnMessage(transport, options);
wrapTransportSend(transport, options);
wrapTransportOnClose(transport);
wrapTransportError(transport);
}

function interceptTransportStart(transport: MCPTransport, beforeStart: () => void): () => void {
let transportStart: MCPTransport['start'];
let originalDescriptor: PropertyDescriptor | undefined;

try {
transportStart = transport.start;
originalDescriptor = Object.getOwnPropertyDescriptor(transport, 'start');
} catch {
return () => undefined;
}

if (typeof transportStart !== 'function') {
return () => undefined;
}

const originalStart = transportStart;
let isInstalled = false;

const restoreStart = (): void => {
if (!isInstalled) {
return;
}

try {
const currentDescriptor = Object.getOwnPropertyDescriptor(transport, 'start');
if (currentDescriptor?.value !== interceptedStart) {
isInstalled = false;
return;
}

if (originalDescriptor) {
Object.defineProperty(transport, 'start', originalDescriptor);
isInstalled = false;
} else if (Reflect.deleteProperty(transport, 'start')) {
isInstalled = false;
}
} catch {}
};

function interceptedStart(this: MCPTransport): Promise<void> {
// Restoring first keeps recursive calls and user-observed method identity identical to the original transport.
restoreStart();
beforeStart();
return originalStart.call(this);
}

const replacementDescriptor: PropertyDescriptor =
originalDescriptor && 'value' in originalDescriptor
? { ...originalDescriptor, value: interceptedStart }
: {
configurable: originalDescriptor?.configurable ?? true,
enumerable: originalDescriptor?.enumerable ?? false,
writable: true,
value: interceptedStart,
};

try {
Object.defineProperty(transport, 'start', replacementDescriptor);
isInstalled = true;
} catch {
// The post-connect fallback preserves the previous behavior for transports which cannot be patched.
}

return restoreStart;
}

/**
* Wraps an MCP Server instance with Sentry instrumentation.
*
Expand Down Expand Up @@ -63,18 +136,30 @@ export function wrapMcpServerWithSentry<S extends object>(mcpServerInstance: S,

fill(serverInstance, 'connect', originalConnect => {
return async function (this: MCPServerInstance, transport: MCPTransport, ...restArgs: unknown[]) {
const result = await (originalConnect as (...args: unknown[]) => Promise<unknown>).call(
this,
transport,
...restArgs,
);

wrapTransportOnMessage(transport, captureOptions);
wrapTransportSend(transport, captureOptions);
wrapTransportOnClose(transport);
wrapTransportError(transport);

return result;
let isTransportInstrumented = false;
const instrumentTransportOnce = (): void => {
if (isTransportInstrumented) {
return;
}

isTransportInstrumented = true;
instrumentTransport(transport, captureOptions);
};
const restoreStart = interceptTransportStart(transport, instrumentTransportOnce);

try {
const result = await (originalConnect as (...args: unknown[]) => Promise<unknown>).call(
this,
transport,
...restArgs,
);

instrumentTransportOnce();

return result;
} finally {
restoreStart();
}
};
});

Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/integrations/mcp-server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ export interface JsonRpcNotification {
* @description Abstraction for MCP communication transport layer
*/
export interface MCPTransport {
/** Starts the transport lifecycle. */
start?: () => Promise<void>;

/**
* Message handler for incoming JSON-RPC messages
* The first argument is a JSON RPC message
Expand Down
Loading
Loading