@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
167 lines (166 loc) • 6.86 kB
JavaScript
import { fill } from "../../utils/object.js";
import { wrapAllMCPHandlers, wrapExistingHandlers } from "./handlers.js";
import { wrapTransportError, wrapTransportOnClose, wrapTransportOnMessage, wrapTransportSend } from "./transport.js";
import { validateMcpServerInstance } from "./validation.js";
// src/integrations/mcp-server/index.ts
/**
* Maps each wrapped MCP server instance to the mutable instrumentation options that the transport
* instrumentation reads (per message). Prevents double-wrapping while still letting a later
* `wrapMcpServerWithSentry` fill in options left unset by an earlier wrap — e.g. an auto-wrap at
* construction installs no explicit options, so a manual override still applies.
* @internal
*/
const wrappedMcpServerOptions = /* @__PURE__ */ new WeakMap();
/**
* Fill in options not explicitly set by an earlier wrap. Only unset fields are written, so
* the first explicit value wins, but an auto-wrap that set no options still
* yields to a later manual override. Mutating the stored object updates the live transport
* instrumentation, which reads it per message.
*/
function applyMissingMcpOptions(target, source) {
if (!source) return;
if (target.recordInputs === void 0 && source.recordInputs !== void 0) target.recordInputs = source.recordInputs;
if (target.recordOutputs === void 0 && source.recordOutputs !== void 0) target.recordOutputs = source.recordOutputs;
if (target.getOAuthClientName === void 0 && source.getOAuthClientName !== void 0) target.getOAuthClientName = source.getOAuthClientName;
}
function instrumentTransport(transport, options) {
wrapTransportOnMessage(transport, options);
wrapTransportSend(transport, options);
wrapTransportOnClose(transport);
wrapTransportError(transport);
}
function interceptTransportStart(transport, beforeStart) {
let transportStart;
let originalDescriptor;
try {
transportStart = transport.start;
originalDescriptor = Object.getOwnPropertyDescriptor(transport, "start");
} catch {
return () => void 0;
}
if (typeof transportStart !== "function") return () => void 0;
const originalStart = transportStart;
let isInstalled = false;
const restoreStart = () => {
if (!isInstalled) return;
try {
if (Object.getOwnPropertyDescriptor(transport, "start")?.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() {
restoreStart();
beforeStart();
return originalStart.call(this);
}
const replacementDescriptor = 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 {}
return restoreStart;
}
/**
* Wraps an MCP Server instance with Sentry instrumentation.
*
* Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package (legacy `tool`/`resource`/`prompt` API)
* and `@modelcontextprotocol/server` version 2.x (`registerTool`/`registerResource`/`registerPrompt` API).
* Automatically instruments transport methods and handler functions for comprehensive monitoring.
*
* Both call orderings are supported: wrapping before or after registering tools, resources,
* and prompts. Sentry patches the registration methods for future handlers and retroactively
* wraps any already-registered ones. Wrapping at construction time is recommended by
* convention (consistent with other SDK integrations), but is not required.
*
* Calling this more than once on the same instance never patches it twice. Options behave like a
* snapshot from the first *explicit* wrap: the first value set for each option wins,
* but a field left unset can still be filled by a later call. So when the SDK auto-wraps
* the server at construction (via the `mcpServer` integration) with no explicit options, a later
* manual `wrapMcpServerWithSentry(server, { recordInputs, recordOutputs })` still applies.
*
* @example
* ```typescript
* import * as Sentry from '@sentry/core';
* import { McpServer } from '@modelcontextprotocol/server';
* import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
*
* // Wrap first, then register tools — this is the correct order
* const server = Sentry.wrapMcpServerWithSentry(
* new McpServer({ name: "my-server", version: "1.0.0" })
* );
*
* server.registerTool('my-tool', schema, handler);
*
* // Explicitly control input/output capture
* const server = Sentry.wrapMcpServerWithSentry(
* new McpServer({ name: "my-server", version: "1.0.0" }),
* { recordInputs: true, recordOutputs: false }
* );
*
* const transport = new NodeStreamableHTTPServerTransport();
* await server.connect(transport);
* ```
*
* @example
* ```typescript
* // Read application-defined metadata supplied by the authentication middleware.
* const server = Sentry.wrapMcpServerWithSentry(mcpServer, {
* getOAuthClientName: authInfo => {
* const name = authInfo?.extra?.clientName;
* return typeof name === 'string' ? name : undefined;
* },
* });
* ```
*
* @param mcpServerInstance - MCP server instance to instrument
* @param options - Optional configuration for recording inputs/outputs and OAuth client attribution
* @returns Instrumented server instance (same reference)
*/
function wrapMcpServerWithSentry(mcpServerInstance, options) {
const existingOptions = wrappedMcpServerOptions.get(mcpServerInstance);
if (existingOptions) {
applyMissingMcpOptions(existingOptions, options);
return mcpServerInstance;
}
if (!validateMcpServerInstance(mcpServerInstance)) return mcpServerInstance;
const serverInstance = mcpServerInstance;
const wrapperOptions = { ...options };
wrappedMcpServerOptions.set(mcpServerInstance, wrapperOptions);
fill(serverInstance, "connect", (originalConnect) => {
return async function(transport, ...restArgs) {
let isTransportInstrumented = false;
const instrumentTransportOnce = () => {
if (isTransportInstrumented) return;
isTransportInstrumented = true;
instrumentTransport(transport, wrapperOptions);
};
const restoreStart = interceptTransportStart(transport, instrumentTransportOnce);
try {
const result = await originalConnect.call(this, transport, ...restArgs);
instrumentTransportOnce();
return result;
} finally {
restoreStart();
}
};
});
wrapAllMCPHandlers(serverInstance);
wrapExistingHandlers(serverInstance);
return mcpServerInstance;
}
export { wrapMcpServerWithSentry };
//# sourceMappingURL=index.js.map