-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathhandlers.ts
More file actions
169 lines (154 loc) · 6.24 KB
/
handlers.ts
File metadata and controls
169 lines (154 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/**
* Handler method wrapping for MCP server instrumentation
*
* Provides automatic error capture and span correlation for tool, resource,
* and prompt handlers.
*/
import { DEBUG_BUILD } from '../../debug-build';
import { debug } from '../../utils/debug-logger';
import { fill } from '../../utils/object';
import { captureError } from './errorCapture';
import type { MCPHandler, MCPServerInstance } from './types';
/**
* Generic function to wrap MCP server method handlers
* @internal
* @param serverInstance - MCP server instance
* @param methodName - Method name to wrap (tool, resource, prompt)
*/
function wrapMethodHandler(serverInstance: MCPServerInstance, methodName: keyof MCPServerInstance): void {
fill(serverInstance, methodName, originalMethod => {
return function (this: MCPServerInstance, name: string, ...args: unknown[]) {
const handler = args[args.length - 1];
if (typeof handler !== 'function') {
return (originalMethod as (...args: unknown[]) => unknown).call(this, name, ...args);
}
const wrappedHandler = createWrappedHandler(handler as MCPHandler, methodName, name);
return (originalMethod as (...args: unknown[]) => unknown).call(this, name, ...args.slice(0, -1), wrappedHandler);
};
});
}
/**
* Creates a wrapped handler with span correlation and error capture
* @internal
* @param originalHandler - Original handler function
* @param methodName - MCP method name
* @param handlerName - Handler identifier
* @returns Wrapped handler function
*/
function createWrappedHandler(originalHandler: MCPHandler, methodName: keyof MCPServerInstance, handlerName: string) {
return function (this: unknown, ...handlerArgs: unknown[]): unknown {
try {
return createErrorCapturingHandler.call(this, originalHandler, methodName, handlerName, handlerArgs);
} catch (error) {
DEBUG_BUILD && debug.warn('MCP handler wrapping failed:', error);
return originalHandler.apply(this, handlerArgs);
}
};
}
/**
* Creates an error-capturing wrapper for handler execution
* @internal
* @param originalHandler - Original handler function
* @param methodName - MCP method name
* @param handlerName - Handler identifier
* @param handlerArgs - Handler arguments
* @param extraHandlerData - Additional handler context
* @returns Handler execution result
*/
function createErrorCapturingHandler(
this: MCPServerInstance,
originalHandler: MCPHandler,
methodName: keyof MCPServerInstance,
handlerName: string,
handlerArgs: unknown[],
): unknown {
try {
const result = originalHandler.apply(this, handlerArgs);
if (result && typeof result === 'object' && typeof (result as { then?: unknown }).then === 'function') {
return Promise.resolve(result).catch(error => {
captureHandlerError(error, methodName, handlerName);
throw error;
});
}
return result;
} catch (error) {
captureHandlerError(error as Error, methodName, handlerName);
throw error;
}
}
/**
* Captures handler execution errors based on handler type
* @internal
* @param error - Error to capture
* @param methodName - MCP method name
* @param handlerName - Handler identifier
*/
function captureHandlerError(error: Error, methodName: keyof MCPServerInstance, handlerName: string): void {
try {
const extraData: Record<string, unknown> = {};
if (methodName === 'tool' || methodName === 'registerTool') {
extraData.tool_name = handlerName;
if (
error.name === 'ProtocolValidationError' ||
error.message.includes('validation') ||
error.message.includes('protocol')
) {
captureError(error, 'validation', extraData);
} else if (
error.name === 'ServerTimeoutError' ||
error.message.includes('timed out') ||
error.message.includes('timeout')
) {
captureError(error, 'timeout', extraData);
} else {
captureError(error, 'tool_execution', extraData);
}
} else if (methodName === 'resource' || methodName === 'registerResource') {
extraData.resource_uri = handlerName;
captureError(error, 'resource_execution', extraData);
} else if (methodName === 'prompt' || methodName === 'registerPrompt') {
extraData.prompt_name = handlerName;
captureError(error, 'prompt_execution', extraData);
}
} catch (_captureErr) {
// noop
}
}
/**
* Wraps tool handlers to associate them with request spans.
* Instruments both `tool` (legacy API) and `registerTool` (new API) if present.
* @param serverInstance - MCP server instance
*/
export function wrapToolHandlers(serverInstance: MCPServerInstance): void {
if (typeof serverInstance.tool === 'function') wrapMethodHandler(serverInstance, 'tool');
if (typeof serverInstance.registerTool === 'function') wrapMethodHandler(serverInstance, 'registerTool');
}
/**
* Wraps resource handlers to associate them with request spans.
* Instruments both `resource` (legacy API) and `registerResource` (new API) if present.
* @param serverInstance - MCP server instance
*/
export function wrapResourceHandlers(serverInstance: MCPServerInstance): void {
if (typeof serverInstance.resource === 'function') wrapMethodHandler(serverInstance, 'resource');
if (typeof serverInstance.registerResource === 'function') wrapMethodHandler(serverInstance, 'registerResource');
}
/**
* Wraps prompt handlers to associate them with request spans.
* Instruments both `prompt` (legacy API) and `registerPrompt` (new API) if present.
* @param serverInstance - MCP server instance
*/
export function wrapPromptHandlers(serverInstance: MCPServerInstance): void {
if (typeof serverInstance.prompt === 'function') wrapMethodHandler(serverInstance, 'prompt');
if (typeof serverInstance.registerPrompt === 'function') wrapMethodHandler(serverInstance, 'registerPrompt');
}
/**
* Wraps all MCP handler types for span correlation.
* Supports both the legacy API (`tool`, `resource`, `prompt`) and the newer API
* (`registerTool`, `registerResource`, `registerPrompt`), instrumenting whichever methods are present.
* @param serverInstance - MCP server instance
*/
export function wrapAllMCPHandlers(serverInstance: MCPServerInstance): void {
wrapToolHandlers(serverInstance);
wrapResourceHandlers(serverInstance);
wrapPromptHandlers(serverInstance);
}