-
Notifications
You must be signed in to change notification settings - Fork 42
instrumentation for @modelcontextprotocol/sdk #603
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
narengogi
wants to merge
17
commits into
traceloop:main
Choose a base branch
from
narengogi:feat/instrumentation-mcp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
312ac84
sse client `onmessage` instrumentation
narengogi 11f01f4
add span attributes for mcp in semantic conventions
narengogi a01d961
support mcp instrumentation through the traceloop js sdk
narengogi 8093aa4
remove local development changes
narengogi a2af060
instrument stdio `onmessage` function as well
narengogi 996c761
remove unused config flag
narengogi e408685
refactoring
narengogi d77fe44
add instrumentation for `send` method as well
narengogi e0045d4
formatting
narengogi 3f8adab
fix types
narengogi a2295af
add test for sse
narengogi 04035cd
remove boilerplate
narengogi aa82a23
destructure imports for manual instrumentation instead of passing pos…
narengogi 0e1a63e
add sample app
narengogi 25389c7
add tests for stdio client
narengogi 66d05b2
update tsconfig
narengogi 8cfd5f0
add stdioClient as sample app
narengogi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
{ | ||
"name": "@traceloop/instrumentation-mcp", | ||
"version": "0.13.0", | ||
"description": "OpenTelemetry instrumentation for MCP", | ||
"main": "dist/index.js", | ||
"module": "dist/index.mjs", | ||
"types": "dist/index.d.ts", | ||
"repository": "traceloop/openllmetry-js", | ||
"scripts": { | ||
"build": "rollup -c", | ||
"lint": "eslint .", | ||
"lint:fix": "eslint . --fix", | ||
"test": "ts-mocha -p tsconfig.json 'test/**/*.test.ts' --timeout 20000" | ||
}, | ||
"keywords": [ | ||
"opentelemetry", | ||
"nodejs", | ||
"tracing", | ||
"attributes", | ||
"mcp" | ||
], | ||
"author": "Traceloop", | ||
"license": "Apache-2.0", | ||
"engines": { | ||
"node": ">=14" | ||
}, | ||
"files": [ | ||
"dist/**/*.js", | ||
"dist/**/*.mjs", | ||
"dist/**/*.js.map", | ||
"dist/**/*.d.ts", | ||
"doc", | ||
"LICENSE", | ||
"README.md", | ||
"package.json" | ||
], | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"dependencies": { | ||
"@opentelemetry/core": "^1.29.0", | ||
"@opentelemetry/instrumentation": "^0.56.0", | ||
"@opentelemetry/semantic-conventions": "^1.28.0", | ||
"@traceloop/ai-semantic-conventions": "^0.13.0", | ||
"tslib": "^2.8.1", | ||
"@modelcontextprotocol/sdk": "^1.12.0" | ||
}, | ||
"devDependencies": { | ||
"@modelcontextprotocol/sdk": "^1.12.0", | ||
"@pollyjs/adapter-node-http": "^6.0.6", | ||
"@pollyjs/core": "^6.0.6", | ||
"@pollyjs/persister-fs": "^6.0.6", | ||
"@types/mocha": "^10.0.10", | ||
"mocha": "^10.8.2", | ||
"ts-mocha": "^10.0.0" | ||
}, | ||
"homepage": "https://github.com/traceloop/openllmetry-js/tree/main/packages/instrumentation-mcp" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
const dts = require("rollup-plugin-dts"); | ||
const typescript = require("@rollup/plugin-typescript"); | ||
const json = require("@rollup/plugin-json"); | ||
|
||
const name = require("./package.json").main.replace(/\.js$/, ""); | ||
|
||
const bundle = (config) => ({ | ||
...config, | ||
input: "src/index.ts", | ||
external: (id) => !/^[./]/.test(id), | ||
}); | ||
|
||
exports.default = [ | ||
bundle({ | ||
plugins: [typescript.default(), json.default()], | ||
output: [ | ||
{ | ||
file: `${name}.js`, | ||
format: "cjs", | ||
sourcemap: true, | ||
}, | ||
{ | ||
file: `${name}.mjs`, | ||
format: "es", | ||
sourcemap: true, | ||
}, | ||
], | ||
}), | ||
bundle({ | ||
plugins: [dts.default()], | ||
output: { | ||
file: `${name}.d.ts`, | ||
format: "es", | ||
}, | ||
}), | ||
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from "./instrumentation"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
import { InstrumentationBase, InstrumentationModuleDefinition, safeExecuteInTheMiddle } from "@opentelemetry/instrumentation"; | ||
import { context, Span, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api"; | ||
import type * as sse from "@modelcontextprotocol/sdk/client/sse" | ||
import type * as stdio from "@modelcontextprotocol/sdk/client/stdio" | ||
|
||
import { McpInstrumentationConfig } from "./types"; | ||
import { version } from "../package.json" | ||
|
||
export class McpInstrumentation extends InstrumentationBase { | ||
declare protected _config: McpInstrumentationConfig | ||
|
||
constructor(config: McpInstrumentationConfig = {}) { | ||
super("@modelcontextprotocol/sdk", version, config) | ||
} | ||
|
||
public override setConfig(config: McpInstrumentationConfig = {}) { | ||
super.setConfig(config); | ||
} | ||
|
||
protected init(): InstrumentationModuleDefinition[]{ | ||
|
||
return [] | ||
} | ||
|
||
public manuallyInstrument(sseModule: typeof sse, stdioModule: typeof stdio) { | ||
this.wrapSSEClient(sseModule); | ||
this.wrapStdioClient(stdioModule); | ||
} | ||
|
||
private wrapSSEClient(module: typeof sse) { | ||
this._diag.debug(`Patching @modelcontextprotocol/sdk/client/sse`); | ||
|
||
// Store reference to the wrapper method | ||
const wrapperMethod = this.wrapperMethod(); | ||
|
||
Object.defineProperty(module.SSEClientTransport.prototype, 'onmessage', { | ||
get(this: any) { | ||
return this._wrappedOnMessage || this._originalOnMessage; | ||
}, | ||
set(this: any, newHandler: Function) { | ||
|
||
// Store the original handler | ||
this._originalOnMessage = newHandler; | ||
|
||
// Wrap the new handler if it's a function | ||
if (typeof newHandler === 'function') { | ||
this._wrappedOnMessage = wrapperMethod(newHandler); | ||
} else { | ||
this._wrappedOnMessage = newHandler; | ||
} | ||
}, | ||
configurable: true, | ||
enumerable: true | ||
}); | ||
|
||
// this._wrap(module.SSEClientTransport.prototype, "send", this.wrapperMethod()); | ||
|
||
} | ||
|
||
private wrapStdioClient(module: typeof stdio) { | ||
this._diag.debug(`Patching @modelcontextprotocol/sdk/client/stdio`); | ||
|
||
// Store reference to the wrapper method | ||
const wrapperMethod = this.wrapperMethod(); | ||
|
||
Object.defineProperty(module.StdioClientTransport.prototype, 'onmessage', { | ||
get(this: any) { | ||
return this._wrappedOnMessage || this._originalOnMessage; | ||
}, | ||
set(this: any, newHandler: Function) { | ||
|
||
// Store the original handler | ||
this._originalOnMessage = newHandler; | ||
|
||
// Wrap the new handler if it's a function | ||
if (typeof newHandler === 'function') { | ||
this._wrappedOnMessage = wrapperMethod(newHandler); | ||
} else { | ||
this._wrappedOnMessage = newHandler; | ||
} | ||
}, | ||
configurable: true, | ||
enumerable: true | ||
}); | ||
|
||
// this._wrap(module.SSEClientTransport.prototype, "send", this.wrapperMethod()); | ||
|
||
} | ||
|
||
|
||
|
||
private wrapperMethod() { | ||
const plugin = this; | ||
return (original: Function) => { | ||
return function method(this: any, ...args: any) { | ||
const span = plugin._startSpan({ | ||
params: args[0], | ||
}); | ||
const execContext = trace.setSpan(context.active(), span); | ||
const execPromise = safeExecuteInTheMiddle( | ||
() => { | ||
return context.with(execContext, () => { | ||
return original.apply(this, args); | ||
}); | ||
}, | ||
(e) => { | ||
if (e) { | ||
plugin._diag.error(`Error in mcp instrumentation`, e); | ||
} | ||
}, | ||
); | ||
const wrappedPromise = plugin._wrapPromise(span, execPromise); | ||
return context.bind(execContext, wrappedPromise); | ||
}; | ||
}; | ||
} | ||
|
||
private _startSpan(params: any) { | ||
const attributes = { | ||
"mcp.request.id": params.params.id, | ||
"mcp.response.value": JSON.stringify(params.result || params.params?.content || params.params?.data), | ||
"mcp.method.name": params.params.method, | ||
} | ||
return this.tracer.startSpan("mcp.client.response", { | ||
kind: SpanKind.CLIENT, | ||
attributes | ||
}); | ||
} | ||
|
||
private async _wrapPromise<T>(span: Span, promise: Promise<T>): Promise<T> { | ||
try { | ||
const result = await promise; | ||
span.end(); | ||
return result; | ||
} catch (error) { | ||
span.setStatus({ | ||
code: SpanStatusCode.ERROR, | ||
message: error.message, | ||
}); | ||
span.setAttributes({ | ||
"mcp.error.message": error.message, | ||
}); | ||
span.recordException(error); | ||
span.end(); | ||
throw error; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { InstrumentationConfig } from "@opentelemetry/instrumentation"; | ||
|
||
export interface McpInstrumentationConfig extends InstrumentationConfig { | ||
/** | ||
* A custom logger to log any exceptions that happen during span creation. | ||
*/ | ||
exceptionLogger?: (e: Error) => void; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"extends": "../../tsconfig.base.json", | ||
"compilerOptions": { | ||
"outDir": "dist", | ||
"rootDir": "." | ||
}, | ||
"files": [], | ||
"include": ["src/**/*.ts", "test/**/*.ts", "package.json"], | ||
"references": [] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid using the generic
Function
type for theonmessage
handler; use a more specific function signature to improve type safety.