@agent-inspect/mcp 6.31.37 → 6.31.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,256 @@
1
+ 'use strict';
2
+
3
+ var agentInspect = require('agent-inspect');
4
+
5
+ // packages/mcp/src/summarize.ts
6
+ var DEFAULT_MAX_SUMMARY_LENGTH = 240;
7
+ function fallbackString(value) {
8
+ try {
9
+ return String(value);
10
+ } catch {
11
+ return "[unserializable]";
12
+ }
13
+ }
14
+ function summarizeMcpValue(value, maxLength = DEFAULT_MAX_SUMMARY_LENGTH) {
15
+ let text;
16
+ try {
17
+ if (typeof value === "string") {
18
+ text = value;
19
+ } else {
20
+ const serialized = JSON.stringify(value);
21
+ text = serialized === void 0 ? fallbackString(value) : serialized;
22
+ }
23
+ } catch {
24
+ text = fallbackString(value);
25
+ }
26
+ if (text.length <= maxLength) return text;
27
+ return `${text.slice(0, Math.max(0, maxLength - 3))}...`;
28
+ }
29
+ function hashServerUrl(url) {
30
+ let hash = 0;
31
+ for (let i = 0; i < url.length; i += 1) {
32
+ hash = hash * 31 + url.charCodeAt(i) >>> 0;
33
+ }
34
+ return hash.toString(16).padStart(8, "0");
35
+ }
36
+ var toolCallCounter = 0;
37
+ function resultReportsToolError(value) {
38
+ if (!value || typeof value !== "object") return false;
39
+ const record = value;
40
+ if (record.isError === true) return true;
41
+ const nested = record.toolResult;
42
+ if (!nested || typeof nested !== "object") return false;
43
+ return nested.isError === true;
44
+ }
45
+ function boundedId(value) {
46
+ if (typeof value !== "string") return void 0;
47
+ const trimmed = value.trim();
48
+ if (trimmed === "" || trimmed.length > 200) return void 0;
49
+ return trimmed;
50
+ }
51
+ async function recordToolResultOutcome(toolName, toolCallId, result, callMetadata) {
52
+ if (!resultReportsToolError(result)) return;
53
+ const operationId = boundedId(callMetadata.operationId);
54
+ const attemptId = boundedId(callMetadata.attemptId);
55
+ await agentInspect.observeOutcome(`mcp:${toolName}:tool-result`, {
56
+ expectation: "MCP tool result is not an error",
57
+ status: "failed",
58
+ method: "custom",
59
+ evidence: {
60
+ toolFailure: true,
61
+ toolName,
62
+ toolCallId,
63
+ ...operationId !== void 0 ? { operationId } : {},
64
+ ...attemptId !== void 0 ? { attemptId } : {}
65
+ }
66
+ });
67
+ }
68
+ function nextToolCallId(prefix) {
69
+ toolCallCounter += 1;
70
+ const base = prefix?.trim() || "mcp";
71
+ return `${base}-${toolCallCounter}`;
72
+ }
73
+ function baseMetadata(options, overrides = {}) {
74
+ const metadata = {
75
+ source: { type: "mcp-client" },
76
+ ...options.serverName ? { mcpServerName: options.serverName } : {},
77
+ ...options.serverUrl ? { mcpServerUrlHash: hashServerUrl(options.serverUrl) } : {},
78
+ ...options.sessionId ? { sessionId: options.sessionId } : {},
79
+ ...overrides
80
+ };
81
+ return { ...options.metadata ?? {}, ...metadata };
82
+ }
83
+ var SDK_REQUEST_OPTION_KEYS = [
84
+ "signal",
85
+ "timeout",
86
+ "onprogress",
87
+ "resetTimeoutOnProgress",
88
+ "maxTotalTimeout",
89
+ "relatedRequestId",
90
+ "resumptionToken",
91
+ "onresumptiontoken"
92
+ ];
93
+ function isSdkRequestOptions(value) {
94
+ if (!value || typeof value !== "object") return false;
95
+ const obj = value;
96
+ return SDK_REQUEST_OPTION_KEYS.some((key) => key in obj);
97
+ }
98
+ function isAgentInspectMetadataBag(value) {
99
+ if (!value || typeof value !== "object") return false;
100
+ if (isSdkRequestOptions(value)) return false;
101
+ const obj = value;
102
+ if (!("metadata" in obj)) return false;
103
+ if ("parse" in obj) return false;
104
+ return true;
105
+ }
106
+ function extractCallMetadata(bag) {
107
+ if (bag.metadata && typeof bag.metadata === "object") {
108
+ return bag.metadata;
109
+ }
110
+ return {};
111
+ }
112
+ function peelOptionsObject(value) {
113
+ if (value === null || value === void 0) {
114
+ return { callMetadata: {}, requestOptions: void 0 };
115
+ }
116
+ if (typeof value !== "object") {
117
+ return { callMetadata: {}, requestOptions: void 0 };
118
+ }
119
+ const obj = value;
120
+ const callMetadata = extractCallMetadata(obj);
121
+ if (isAgentInspectMetadataBag(value)) {
122
+ return { callMetadata, requestOptions: void 0 };
123
+ }
124
+ if (isSdkRequestOptions(value) || Object.keys(obj).length > 0) {
125
+ const { metadata: _ignored, ...rest } = obj;
126
+ return {
127
+ callMetadata,
128
+ requestOptions: rest
129
+ };
130
+ }
131
+ return { callMetadata, requestOptions: void 0 };
132
+ }
133
+ function resolveCallToolArgs(resultSchemaOrOptions, maybeOptions) {
134
+ if (maybeOptions !== void 0) {
135
+ const peeled = peelOptionsObject(maybeOptions);
136
+ return {
137
+ resultSchema: resultSchemaOrOptions,
138
+ requestOptions: peeled.requestOptions,
139
+ callMetadata: peeled.callMetadata
140
+ };
141
+ }
142
+ if (isAgentInspectMetadataBag(resultSchemaOrOptions)) {
143
+ return {
144
+ resultSchema: void 0,
145
+ requestOptions: void 0,
146
+ callMetadata: extractCallMetadata(resultSchemaOrOptions)
147
+ };
148
+ }
149
+ if (isSdkRequestOptions(resultSchemaOrOptions)) {
150
+ const peeled = peelOptionsObject(resultSchemaOrOptions);
151
+ return {
152
+ resultSchema: void 0,
153
+ requestOptions: peeled.requestOptions,
154
+ callMetadata: peeled.callMetadata
155
+ };
156
+ }
157
+ return {
158
+ resultSchema: resultSchemaOrOptions,
159
+ requestOptions: void 0,
160
+ callMetadata: {}
161
+ };
162
+ }
163
+ function invokeCallTool(callToolImpl, params, resultSchema, requestOptions) {
164
+ const fn = callToolImpl;
165
+ if (requestOptions !== void 0) {
166
+ return fn(params, resultSchema, requestOptions);
167
+ }
168
+ if (resultSchema !== void 0) {
169
+ return fn(params, resultSchema);
170
+ }
171
+ return fn(params);
172
+ }
173
+ function wrapMcpClient(client, options = {}) {
174
+ const maxSummaryLength = options.maxSummaryLength ?? 240;
175
+ const listToolsImpl = typeof client.listTools === "function" ? client.listTools.bind(client) : void 0;
176
+ const callToolImpl = client.callTool.bind(client);
177
+ const wrappedListTools = listToolsImpl ? async (params, requestOptions) => agentInspect.step(
178
+ "mcp:tools/list",
179
+ async () => {
180
+ if (requestOptions !== void 0) {
181
+ return listToolsImpl(params, requestOptions);
182
+ }
183
+ return listToolsImpl(params);
184
+ },
185
+ {
186
+ type: "tool",
187
+ metadata: baseMetadata(options, {
188
+ toolName: "tools/list",
189
+ toolCallId: nextToolCallId(options.toolCallIdPrefix)
190
+ })
191
+ }
192
+ ) : void 0;
193
+ const wrappedCallTool = async (params, resultSchemaOrOptions, maybeOptions) => {
194
+ const { resultSchema, requestOptions, callMetadata } = resolveCallToolArgs(
195
+ resultSchemaOrOptions,
196
+ maybeOptions
197
+ );
198
+ const toolCallId = nextToolCallId(options.toolCallIdPrefix);
199
+ return agentInspect.step(
200
+ `mcp:${params.name}`,
201
+ async () => {
202
+ const result = await invokeCallTool(
203
+ callToolImpl,
204
+ params,
205
+ resultSchema,
206
+ requestOptions
207
+ );
208
+ await recordToolResultOutcome(
209
+ params.name,
210
+ toolCallId,
211
+ result,
212
+ callMetadata
213
+ );
214
+ return result;
215
+ },
216
+ {
217
+ type: "tool",
218
+ metadata: baseMetadata(options, {
219
+ toolName: params.name,
220
+ toolCallId,
221
+ argumentSummary: summarizeMcpValue(
222
+ params.arguments ?? {},
223
+ maxSummaryLength
224
+ ),
225
+ ...callMetadata
226
+ })
227
+ }
228
+ );
229
+ };
230
+ return new Proxy(client, {
231
+ get(target, property, receiver) {
232
+ if (property === "listTools" && wrappedListTools !== void 0) {
233
+ return wrappedListTools;
234
+ }
235
+ if (property === "callTool") {
236
+ return wrappedCallTool;
237
+ }
238
+ const value = Reflect.get(target, property, receiver);
239
+ if (typeof value === "function") {
240
+ return value.bind(target);
241
+ }
242
+ return value;
243
+ }
244
+ });
245
+ }
246
+ function resetMcpToolCallIdsForTests() {
247
+ toolCallCounter = 0;
248
+ }
249
+
250
+ exports.hashServerUrl = hashServerUrl;
251
+ exports.resetMcpToolCallIdsForTests = resetMcpToolCallIdsForTests;
252
+ exports.resolveCallToolArgs = resolveCallToolArgs;
253
+ exports.summarizeMcpValue = summarizeMcpValue;
254
+ exports.wrapMcpClient = wrapMcpClient;
255
+ //# sourceMappingURL=index.cjs.map
256
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/summarize.ts","../src/wrap.ts"],"names":["observeOutcome","step"],"mappings":";;;;;AAAA,IAAM,0BAAA,GAA6B,GAAA;AAEnC,SAAS,eAAe,KAAA,EAAwB;AAC9C,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,kBAAA;AAAA,EACT;AACF;AAEO,SAAS,iBAAA,CACd,KAAA,EACA,SAAA,GAAY,0BAAA,EACJ;AACR,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,MAAA,IAAA,GAAO,KAAA;AAAA,IACT,CAAA,MAAO;AAIL,MAAA,MAAM,UAAA,GAAa,IAAA,CAAK,SAAA,CAAU,KAAK,CAAA;AACvC,MAAA,IAAA,GAAO,UAAA,KAAe,KAAA,CAAA,GAAY,cAAA,CAAe,KAAK,CAAA,GAAI,UAAA;AAAA,IAC5D;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,IAAA,GAAO,eAAe,KAAK,CAAA;AAAA,EAC7B;AACA,EAAA,IAAI,IAAA,CAAK,MAAA,IAAU,SAAA,EAAW,OAAO,IAAA;AACrC,EAAA,OAAO,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,IAAA,CAAK,IAAI,CAAA,EAAG,SAAA,GAAY,CAAC,CAAC,CAAC,CAAA,GAAA,CAAA;AACrD;AAEO,SAAS,cAAc,GAAA,EAAqB;AACjD,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,MAAA,EAAQ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,CAAM,KAAK,MAAM,CAAA;AAAA,MAC1B;AACA,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;AAGO,SAAS,2BAAA,GAAoC;AAClD,EAAA,eAAA,GAAkB,CAAA;AACpB","file":"index.cjs","sourcesContent":["const DEFAULT_MAX_SUMMARY_LENGTH = 240;\n\nfunction fallbackString(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[unserializable]\";\n }\n}\n\nexport function summarizeMcpValue(\n value: unknown,\n maxLength = DEFAULT_MAX_SUMMARY_LENGTH,\n): string {\n let text: string;\n try {\n if (typeof value === \"string\") {\n text = value;\n } else {\n // JSON.stringify returns undefined (not a string) for undefined,\n // functions, and symbols; falling through with undefined would crash\n // instrumentation at text.length below.\n const serialized = JSON.stringify(value);\n text = serialized === undefined ? fallbackString(value) : serialized;\n }\n } catch {\n text = fallbackString(value);\n }\n if (text.length <= maxLength) return text;\n return `${text.slice(0, Math.max(0, maxLength - 3))}...`;\n}\n\nexport function hashServerUrl(url: string): string {\n let hash = 0;\n for (let i = 0; i < url.length; i += 1) {\n hash = (hash * 31 + url.charCodeAt(i)) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n","import { observeOutcome, step } from \"agent-inspect\";\n\nimport { hashServerUrl, summarizeMcpValue } from \"./summarize.js\";\nimport type {\n McpClientLike,\n McpClientTracerOptions,\n McpRequestOptions,\n McpTraceMetadata,\n} from \"./types.js\";\n\nlet toolCallCounter = 0;\n\nfunction resultReportsToolError(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const record = value as Record<string, unknown>;\n if (record.isError === true) return true;\n const nested = record.toolResult;\n if (!nested || typeof nested !== \"object\") return false;\n return (nested as Record<string, unknown>).isError === true;\n}\n\nfunction boundedId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\" || trimmed.length > 200) return undefined;\n return trimmed;\n}\n\nasync function recordToolResultOutcome(\n toolName: string,\n toolCallId: string,\n result: unknown,\n callMetadata: Record<string, unknown>,\n): Promise<void> {\n if (!resultReportsToolError(result)) return;\n const operationId = boundedId(callMetadata.operationId);\n const attemptId = boundedId(callMetadata.attemptId);\n await observeOutcome(`mcp:${toolName}:tool-result`, {\n expectation: \"MCP tool result is not an error\",\n status: \"failed\",\n method: \"custom\",\n evidence: {\n toolFailure: true,\n toolName,\n toolCallId,\n ...(operationId !== undefined ? { operationId } : {}),\n ...(attemptId !== undefined ? { attemptId } : {}),\n },\n });\n}\n\nfunction nextToolCallId(prefix?: string): string {\n toolCallCounter += 1;\n const base = prefix?.trim() || \"mcp\";\n return `${base}-${toolCallCounter}`;\n}\n\nfunction baseMetadata(\n options: McpClientTracerOptions,\n overrides: Partial<McpTraceMetadata> = {},\n): Record<string, unknown> {\n const metadata: McpTraceMetadata = {\n source: { type: \"mcp-client\" },\n ...(options.serverName ? { mcpServerName: options.serverName } : {}),\n ...(options.serverUrl\n ? { mcpServerUrlHash: hashServerUrl(options.serverUrl) }\n : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...overrides,\n };\n return { ...(options.metadata ?? {}), ...metadata };\n}\n\n/** SDK RequestOptions keys — must never be swallowed as AgentInspect metadata. */\nconst SDK_REQUEST_OPTION_KEYS = [\n \"signal\",\n \"timeout\",\n \"onprogress\",\n \"resetTimeoutOnProgress\",\n \"maxTotalTimeout\",\n \"relatedRequestId\",\n \"resumptionToken\",\n \"onresumptiontoken\",\n] as const;\n\nfunction isSdkRequestOptions(value: unknown): value is McpRequestOptions {\n if (!value || typeof value !== \"object\") return false;\n const obj = value as Record<string, unknown>;\n return SDK_REQUEST_OPTION_KEYS.some((key) => key in obj);\n}\n\n/**\n * AgentInspect per-call metadata bag: `{ metadata: {...} }` without SDK option keys.\n * Must not consume ordinary SDK RequestOptions that happen to be objects.\n */\nfunction isAgentInspectMetadataBag(\n value: unknown,\n): value is { metadata?: Record<string, unknown> } {\n if (!value || typeof value !== \"object\") return false;\n if (isSdkRequestOptions(value)) return false;\n const obj = value as Record<string, unknown>;\n if (!(\"metadata\" in obj)) return false;\n // Zod/result schemas expose parse — never treat those as AI bags.\n if (\"parse\" in obj) return false;\n return true;\n}\n\nfunction extractCallMetadata(bag: {\n metadata?: Record<string, unknown>;\n}): Record<string, unknown> {\n if (bag.metadata && typeof bag.metadata === \"object\") {\n return bag.metadata;\n }\n return {};\n}\n\n/** Peel AgentInspect `metadata` without consuming SDK RequestOptions keys. */\nfunction peelOptionsObject(value: unknown): {\n callMetadata: Record<string, unknown>;\n requestOptions: McpRequestOptions | undefined;\n} {\n if (value === null || value === undefined) {\n return { callMetadata: {}, requestOptions: undefined };\n }\n if (typeof value !== \"object\") {\n return { callMetadata: {}, requestOptions: undefined };\n }\n const obj = value as Record<string, unknown>;\n const callMetadata = extractCallMetadata(obj);\n\n // Pure AI bag — do not forward as SDK RequestOptions.\n if (isAgentInspectMetadataBag(value)) {\n return { callMetadata, requestOptions: undefined };\n }\n\n if (isSdkRequestOptions(value) || Object.keys(obj).length > 0) {\n const { metadata: _ignored, ...rest } = obj;\n return {\n callMetadata,\n requestOptions: rest as McpRequestOptions,\n };\n }\n\n return { callMetadata, requestOptions: undefined };\n}\n\n/**\n * Resolve SDK callTool arity:\n * callTool(params, resultSchema?, requestOptions?)\n * plus AgentInspect overloads that peel `{ metadata }` without dropping RequestOptions.\n * Composed `{ timeout, metadata: { operationId, attemptId } }` keeps both sides.\n */\nexport function resolveCallToolArgs(\n resultSchemaOrOptions?: unknown,\n maybeOptions?: unknown,\n): {\n resultSchema: unknown;\n requestOptions: McpRequestOptions | undefined;\n callMetadata: Record<string, unknown>;\n} {\n // Three-arg form: (params, schema|undefined, options)\n if (maybeOptions !== undefined) {\n const peeled = peelOptionsObject(maybeOptions);\n return {\n resultSchema: resultSchemaOrOptions,\n requestOptions: peeled.requestOptions,\n callMetadata: peeled.callMetadata,\n };\n }\n\n // Two-arg form: (params, schema) OR (params, { metadata }) OR (params, RequestOptions)\n if (isAgentInspectMetadataBag(resultSchemaOrOptions)) {\n return {\n resultSchema: undefined,\n requestOptions: undefined,\n callMetadata: extractCallMetadata(resultSchemaOrOptions),\n };\n }\n\n if (isSdkRequestOptions(resultSchemaOrOptions)) {\n const peeled = peelOptionsObject(resultSchemaOrOptions);\n return {\n resultSchema: undefined,\n requestOptions: peeled.requestOptions,\n callMetadata: peeled.callMetadata,\n };\n }\n\n return {\n resultSchema: resultSchemaOrOptions,\n requestOptions: undefined,\n callMetadata: {},\n };\n}\n\nfunction invokeCallTool(\n callToolImpl: McpClientLike[\"callTool\"],\n params: Parameters<McpClientLike[\"callTool\"]>[0],\n resultSchema: unknown,\n requestOptions: McpRequestOptions | undefined,\n): Promise<unknown> {\n const fn = callToolImpl as (\n p: unknown,\n schema?: unknown,\n opts?: unknown,\n ) => Promise<unknown>;\n if (requestOptions !== undefined) {\n return fn(params, resultSchema, requestOptions);\n }\n if (resultSchema !== undefined) {\n return fn(params, resultSchema);\n }\n return fn(params);\n}\n\n/**\n * Wraps an MCP client so tools/list and tools/call emit local tool steps.\n * Telemetry only — does not proxy network behavior beyond the wrapped client.\n *\n * Uses a Proxy over the original client so prototype methods (`connect`,\n * `close`, `listResources`, …), private SDK state, and `instanceof` stay intact.\n * A shallow object spread would drop prototype methods and copy private fields.\n *\n * Forwards the real SDK argument positions, including `RequestOptions`\n * (`signal`, `timeout`, progress callbacks). Does not fake cancellation while\n * still dispatching the underlying request.\n */\nexport function wrapMcpClient<T extends McpClientLike>(\n client: T,\n options: McpClientTracerOptions = {},\n): T {\n const maxSummaryLength = options.maxSummaryLength ?? 240;\n\n const listToolsImpl =\n typeof client.listTools === \"function\"\n ? client.listTools.bind(client)\n : undefined;\n const callToolImpl = client.callTool.bind(client);\n\n const wrappedListTools = listToolsImpl\n ? async (params?: unknown, requestOptions?: McpRequestOptions) =>\n step(\n \"mcp:tools/list\",\n async () => {\n if (requestOptions !== undefined) {\n return (\n listToolsImpl as (\n p?: unknown,\n opts?: unknown,\n ) => Promise<unknown>\n )(params, requestOptions);\n }\n return listToolsImpl(params);\n },\n {\n type: \"tool\",\n metadata: baseMetadata(options, {\n toolName: \"tools/list\",\n toolCallId: nextToolCallId(options.toolCallIdPrefix),\n }),\n },\n )\n : undefined;\n\n const wrappedCallTool = async (\n params: Parameters<McpClientLike[\"callTool\"]>[0],\n resultSchemaOrOptions?: unknown,\n maybeOptions?: unknown,\n ) => {\n const { resultSchema, requestOptions, callMetadata } = resolveCallToolArgs(\n resultSchemaOrOptions,\n maybeOptions,\n );\n\n const toolCallId = nextToolCallId(options.toolCallIdPrefix);\n return step(\n `mcp:${params.name}`,\n async () => {\n const result = await invokeCallTool(\n callToolImpl,\n params,\n resultSchema,\n requestOptions,\n );\n await recordToolResultOutcome(\n params.name,\n toolCallId,\n result,\n callMetadata,\n );\n return result;\n },\n {\n type: \"tool\",\n metadata: baseMetadata(options, {\n toolName: params.name,\n toolCallId,\n argumentSummary: summarizeMcpValue(\n params.arguments ?? {},\n maxSummaryLength,\n ),\n ...callMetadata,\n }),\n },\n );\n };\n\n return new Proxy(client, {\n get(target, property, receiver) {\n if (property === \"listTools\" && wrappedListTools !== undefined) {\n return wrappedListTools;\n }\n if (property === \"callTool\") {\n return wrappedCallTool;\n }\n const value = Reflect.get(target, property, receiver);\n if (typeof value === \"function\") {\n return value.bind(target);\n }\n return value;\n },\n }) as T;\n}\n\n/** @internal resets tool call ids for deterministic tests */\nexport function resetMcpToolCallIdsForTests(): void {\n toolCallCounter = 0;\n}\n"]}
@@ -0,0 +1,106 @@
1
+ interface McpToolDescriptor {
2
+ name: string;
3
+ description?: string;
4
+ inputSchema?: unknown;
5
+ }
6
+ interface McpListToolsResult {
7
+ tools: McpToolDescriptor[];
8
+ }
9
+ interface McpCallToolParams {
10
+ name: string;
11
+ arguments?: Record<string, unknown>;
12
+ }
13
+ interface McpCallToolResult {
14
+ content?: unknown;
15
+ isError?: boolean;
16
+ structuredContent?: unknown;
17
+ }
18
+ /**
19
+ * Subset of MCP SDK `RequestOptions` forwarded by the wrapper.
20
+ * Compatible with @modelcontextprotocol/sdk without requiring it at runtime.
21
+ */
22
+ interface McpRequestOptions {
23
+ signal?: AbortSignal;
24
+ timeout?: number;
25
+ onprogress?: (...args: unknown[]) => void;
26
+ resetTimeoutOnProgress?: boolean;
27
+ maxTotalTimeout?: number;
28
+ relatedRequestId?: string;
29
+ resumptionToken?: string;
30
+ onresumptiontoken?: (...args: unknown[]) => void;
31
+ /** AgentInspect per-call metadata (optional; never consumes SDK option keys). */
32
+ metadata?: Record<string, unknown>;
33
+ [key: string]: unknown;
34
+ }
35
+ /**
36
+ * Minimal MCP client surface for local tracing. Compatible with common SDK
37
+ * client shapes without requiring @modelcontextprotocol/sdk at runtime.
38
+ *
39
+ * Method syntax (not property function types) so real SDK `Client` remains
40
+ * assignable under `strictFunctionTypes` (bivariant method parameters).
41
+ * `callTool` returns `Promise<unknown>` to accept both normal tool results and
42
+ * the SDK compatibility `{ toolResult }` branch.
43
+ *
44
+ * Matches SDK arity: `callTool(params, resultSchema?, requestOptions?)` and
45
+ * `listTools(params?, requestOptions?)`. AgentInspect also accepts a
46
+ * `{ metadata }` bag in place of schema/options when it is not RequestOptions-shaped.
47
+ */
48
+ interface McpClientLike {
49
+ listTools?(params?: unknown, options?: unknown): Promise<McpListToolsResult | unknown>;
50
+ callTool(params: McpCallToolParams, resultSchemaOrOptions?: unknown, options?: unknown): Promise<unknown>;
51
+ }
52
+ interface McpClientTracerOptions {
53
+ serverName?: string;
54
+ serverUrl?: string;
55
+ sessionId?: string;
56
+ toolCallIdPrefix?: string;
57
+ maxSummaryLength?: number;
58
+ metadata?: Record<string, unknown>;
59
+ }
60
+ interface McpTraceMetadata {
61
+ source: {
62
+ type: "mcp-client";
63
+ };
64
+ mcpServerName?: string;
65
+ mcpServerUrlHash?: string;
66
+ sessionId?: string;
67
+ toolName?: string;
68
+ toolCallId?: string;
69
+ mcpToolCallId?: string;
70
+ argumentSummary?: string;
71
+ resultSummary?: string;
72
+ durationMs?: number;
73
+ isError?: boolean;
74
+ }
75
+
76
+ declare function summarizeMcpValue(value: unknown, maxLength?: number): string;
77
+ declare function hashServerUrl(url: string): string;
78
+
79
+ /**
80
+ * Resolve SDK callTool arity:
81
+ * callTool(params, resultSchema?, requestOptions?)
82
+ * plus AgentInspect overloads that peel `{ metadata }` without dropping RequestOptions.
83
+ * Composed `{ timeout, metadata: { operationId, attemptId } }` keeps both sides.
84
+ */
85
+ declare function resolveCallToolArgs(resultSchemaOrOptions?: unknown, maybeOptions?: unknown): {
86
+ resultSchema: unknown;
87
+ requestOptions: McpRequestOptions | undefined;
88
+ callMetadata: Record<string, unknown>;
89
+ };
90
+ /**
91
+ * Wraps an MCP client so tools/list and tools/call emit local tool steps.
92
+ * Telemetry only — does not proxy network behavior beyond the wrapped client.
93
+ *
94
+ * Uses a Proxy over the original client so prototype methods (`connect`,
95
+ * `close`, `listResources`, …), private SDK state, and `instanceof` stay intact.
96
+ * A shallow object spread would drop prototype methods and copy private fields.
97
+ *
98
+ * Forwards the real SDK argument positions, including `RequestOptions`
99
+ * (`signal`, `timeout`, progress callbacks). Does not fake cancellation while
100
+ * still dispatching the underlying request.
101
+ */
102
+ declare function wrapMcpClient<T extends McpClientLike>(client: T, options?: McpClientTracerOptions): T;
103
+ /** @internal resets tool call ids for deterministic tests */
104
+ declare function resetMcpToolCallIdsForTests(): void;
105
+
106
+ export { type McpCallToolParams, type McpCallToolResult, type McpClientLike, type McpClientTracerOptions, type McpListToolsResult, type McpRequestOptions, type McpToolDescriptor, type McpTraceMetadata, hashServerUrl, resetMcpToolCallIdsForTests, resolveCallToolArgs, summarizeMcpValue, wrapMcpClient };
@@ -0,0 +1,106 @@
1
+ interface McpToolDescriptor {
2
+ name: string;
3
+ description?: string;
4
+ inputSchema?: unknown;
5
+ }
6
+ interface McpListToolsResult {
7
+ tools: McpToolDescriptor[];
8
+ }
9
+ interface McpCallToolParams {
10
+ name: string;
11
+ arguments?: Record<string, unknown>;
12
+ }
13
+ interface McpCallToolResult {
14
+ content?: unknown;
15
+ isError?: boolean;
16
+ structuredContent?: unknown;
17
+ }
18
+ /**
19
+ * Subset of MCP SDK `RequestOptions` forwarded by the wrapper.
20
+ * Compatible with @modelcontextprotocol/sdk without requiring it at runtime.
21
+ */
22
+ interface McpRequestOptions {
23
+ signal?: AbortSignal;
24
+ timeout?: number;
25
+ onprogress?: (...args: unknown[]) => void;
26
+ resetTimeoutOnProgress?: boolean;
27
+ maxTotalTimeout?: number;
28
+ relatedRequestId?: string;
29
+ resumptionToken?: string;
30
+ onresumptiontoken?: (...args: unknown[]) => void;
31
+ /** AgentInspect per-call metadata (optional; never consumes SDK option keys). */
32
+ metadata?: Record<string, unknown>;
33
+ [key: string]: unknown;
34
+ }
35
+ /**
36
+ * Minimal MCP client surface for local tracing. Compatible with common SDK
37
+ * client shapes without requiring @modelcontextprotocol/sdk at runtime.
38
+ *
39
+ * Method syntax (not property function types) so real SDK `Client` remains
40
+ * assignable under `strictFunctionTypes` (bivariant method parameters).
41
+ * `callTool` returns `Promise<unknown>` to accept both normal tool results and
42
+ * the SDK compatibility `{ toolResult }` branch.
43
+ *
44
+ * Matches SDK arity: `callTool(params, resultSchema?, requestOptions?)` and
45
+ * `listTools(params?, requestOptions?)`. AgentInspect also accepts a
46
+ * `{ metadata }` bag in place of schema/options when it is not RequestOptions-shaped.
47
+ */
48
+ interface McpClientLike {
49
+ listTools?(params?: unknown, options?: unknown): Promise<McpListToolsResult | unknown>;
50
+ callTool(params: McpCallToolParams, resultSchemaOrOptions?: unknown, options?: unknown): Promise<unknown>;
51
+ }
52
+ interface McpClientTracerOptions {
53
+ serverName?: string;
54
+ serverUrl?: string;
55
+ sessionId?: string;
56
+ toolCallIdPrefix?: string;
57
+ maxSummaryLength?: number;
58
+ metadata?: Record<string, unknown>;
59
+ }
60
+ interface McpTraceMetadata {
61
+ source: {
62
+ type: "mcp-client";
63
+ };
64
+ mcpServerName?: string;
65
+ mcpServerUrlHash?: string;
66
+ sessionId?: string;
67
+ toolName?: string;
68
+ toolCallId?: string;
69
+ mcpToolCallId?: string;
70
+ argumentSummary?: string;
71
+ resultSummary?: string;
72
+ durationMs?: number;
73
+ isError?: boolean;
74
+ }
75
+
76
+ declare function summarizeMcpValue(value: unknown, maxLength?: number): string;
77
+ declare function hashServerUrl(url: string): string;
78
+
79
+ /**
80
+ * Resolve SDK callTool arity:
81
+ * callTool(params, resultSchema?, requestOptions?)
82
+ * plus AgentInspect overloads that peel `{ metadata }` without dropping RequestOptions.
83
+ * Composed `{ timeout, metadata: { operationId, attemptId } }` keeps both sides.
84
+ */
85
+ declare function resolveCallToolArgs(resultSchemaOrOptions?: unknown, maybeOptions?: unknown): {
86
+ resultSchema: unknown;
87
+ requestOptions: McpRequestOptions | undefined;
88
+ callMetadata: Record<string, unknown>;
89
+ };
90
+ /**
91
+ * Wraps an MCP client so tools/list and tools/call emit local tool steps.
92
+ * Telemetry only — does not proxy network behavior beyond the wrapped client.
93
+ *
94
+ * Uses a Proxy over the original client so prototype methods (`connect`,
95
+ * `close`, `listResources`, …), private SDK state, and `instanceof` stay intact.
96
+ * A shallow object spread would drop prototype methods and copy private fields.
97
+ *
98
+ * Forwards the real SDK argument positions, including `RequestOptions`
99
+ * (`signal`, `timeout`, progress callbacks). Does not fake cancellation while
100
+ * still dispatching the underlying request.
101
+ */
102
+ declare function wrapMcpClient<T extends McpClientLike>(client: T, options?: McpClientTracerOptions): T;
103
+ /** @internal resets tool call ids for deterministic tests */
104
+ declare function resetMcpToolCallIdsForTests(): void;
105
+
106
+ export { type McpCallToolParams, type McpCallToolResult, type McpClientLike, type McpClientTracerOptions, type McpListToolsResult, type McpRequestOptions, type McpToolDescriptor, type McpTraceMetadata, hashServerUrl, resetMcpToolCallIdsForTests, resolveCallToolArgs, summarizeMcpValue, wrapMcpClient };
package/dist/index.mjs ADDED
@@ -0,0 +1,250 @@
1
+ import { step, observeOutcome } from 'agent-inspect';
2
+
3
+ // packages/mcp/src/summarize.ts
4
+ var DEFAULT_MAX_SUMMARY_LENGTH = 240;
5
+ function fallbackString(value) {
6
+ try {
7
+ return String(value);
8
+ } catch {
9
+ return "[unserializable]";
10
+ }
11
+ }
12
+ function summarizeMcpValue(value, maxLength = DEFAULT_MAX_SUMMARY_LENGTH) {
13
+ let text;
14
+ try {
15
+ if (typeof value === "string") {
16
+ text = value;
17
+ } else {
18
+ const serialized = JSON.stringify(value);
19
+ text = serialized === void 0 ? fallbackString(value) : serialized;
20
+ }
21
+ } catch {
22
+ text = fallbackString(value);
23
+ }
24
+ if (text.length <= maxLength) return text;
25
+ return `${text.slice(0, Math.max(0, maxLength - 3))}...`;
26
+ }
27
+ function hashServerUrl(url) {
28
+ let hash = 0;
29
+ for (let i = 0; i < url.length; i += 1) {
30
+ hash = hash * 31 + url.charCodeAt(i) >>> 0;
31
+ }
32
+ return hash.toString(16).padStart(8, "0");
33
+ }
34
+ var toolCallCounter = 0;
35
+ function resultReportsToolError(value) {
36
+ if (!value || typeof value !== "object") return false;
37
+ const record = value;
38
+ if (record.isError === true) return true;
39
+ const nested = record.toolResult;
40
+ if (!nested || typeof nested !== "object") return false;
41
+ return nested.isError === true;
42
+ }
43
+ function boundedId(value) {
44
+ if (typeof value !== "string") return void 0;
45
+ const trimmed = value.trim();
46
+ if (trimmed === "" || trimmed.length > 200) return void 0;
47
+ return trimmed;
48
+ }
49
+ async function recordToolResultOutcome(toolName, toolCallId, result, callMetadata) {
50
+ if (!resultReportsToolError(result)) return;
51
+ const operationId = boundedId(callMetadata.operationId);
52
+ const attemptId = boundedId(callMetadata.attemptId);
53
+ await observeOutcome(`mcp:${toolName}:tool-result`, {
54
+ expectation: "MCP tool result is not an error",
55
+ status: "failed",
56
+ method: "custom",
57
+ evidence: {
58
+ toolFailure: true,
59
+ toolName,
60
+ toolCallId,
61
+ ...operationId !== void 0 ? { operationId } : {},
62
+ ...attemptId !== void 0 ? { attemptId } : {}
63
+ }
64
+ });
65
+ }
66
+ function nextToolCallId(prefix) {
67
+ toolCallCounter += 1;
68
+ const base = prefix?.trim() || "mcp";
69
+ return `${base}-${toolCallCounter}`;
70
+ }
71
+ function baseMetadata(options, overrides = {}) {
72
+ const metadata = {
73
+ source: { type: "mcp-client" },
74
+ ...options.serverName ? { mcpServerName: options.serverName } : {},
75
+ ...options.serverUrl ? { mcpServerUrlHash: hashServerUrl(options.serverUrl) } : {},
76
+ ...options.sessionId ? { sessionId: options.sessionId } : {},
77
+ ...overrides
78
+ };
79
+ return { ...options.metadata ?? {}, ...metadata };
80
+ }
81
+ var SDK_REQUEST_OPTION_KEYS = [
82
+ "signal",
83
+ "timeout",
84
+ "onprogress",
85
+ "resetTimeoutOnProgress",
86
+ "maxTotalTimeout",
87
+ "relatedRequestId",
88
+ "resumptionToken",
89
+ "onresumptiontoken"
90
+ ];
91
+ function isSdkRequestOptions(value) {
92
+ if (!value || typeof value !== "object") return false;
93
+ const obj = value;
94
+ return SDK_REQUEST_OPTION_KEYS.some((key) => key in obj);
95
+ }
96
+ function isAgentInspectMetadataBag(value) {
97
+ if (!value || typeof value !== "object") return false;
98
+ if (isSdkRequestOptions(value)) return false;
99
+ const obj = value;
100
+ if (!("metadata" in obj)) return false;
101
+ if ("parse" in obj) return false;
102
+ return true;
103
+ }
104
+ function extractCallMetadata(bag) {
105
+ if (bag.metadata && typeof bag.metadata === "object") {
106
+ return bag.metadata;
107
+ }
108
+ return {};
109
+ }
110
+ function peelOptionsObject(value) {
111
+ if (value === null || value === void 0) {
112
+ return { callMetadata: {}, requestOptions: void 0 };
113
+ }
114
+ if (typeof value !== "object") {
115
+ return { callMetadata: {}, requestOptions: void 0 };
116
+ }
117
+ const obj = value;
118
+ const callMetadata = extractCallMetadata(obj);
119
+ if (isAgentInspectMetadataBag(value)) {
120
+ return { callMetadata, requestOptions: void 0 };
121
+ }
122
+ if (isSdkRequestOptions(value) || Object.keys(obj).length > 0) {
123
+ const { metadata: _ignored, ...rest } = obj;
124
+ return {
125
+ callMetadata,
126
+ requestOptions: rest
127
+ };
128
+ }
129
+ return { callMetadata, requestOptions: void 0 };
130
+ }
131
+ function resolveCallToolArgs(resultSchemaOrOptions, maybeOptions) {
132
+ if (maybeOptions !== void 0) {
133
+ const peeled = peelOptionsObject(maybeOptions);
134
+ return {
135
+ resultSchema: resultSchemaOrOptions,
136
+ requestOptions: peeled.requestOptions,
137
+ callMetadata: peeled.callMetadata
138
+ };
139
+ }
140
+ if (isAgentInspectMetadataBag(resultSchemaOrOptions)) {
141
+ return {
142
+ resultSchema: void 0,
143
+ requestOptions: void 0,
144
+ callMetadata: extractCallMetadata(resultSchemaOrOptions)
145
+ };
146
+ }
147
+ if (isSdkRequestOptions(resultSchemaOrOptions)) {
148
+ const peeled = peelOptionsObject(resultSchemaOrOptions);
149
+ return {
150
+ resultSchema: void 0,
151
+ requestOptions: peeled.requestOptions,
152
+ callMetadata: peeled.callMetadata
153
+ };
154
+ }
155
+ return {
156
+ resultSchema: resultSchemaOrOptions,
157
+ requestOptions: void 0,
158
+ callMetadata: {}
159
+ };
160
+ }
161
+ function invokeCallTool(callToolImpl, params, resultSchema, requestOptions) {
162
+ const fn = callToolImpl;
163
+ if (requestOptions !== void 0) {
164
+ return fn(params, resultSchema, requestOptions);
165
+ }
166
+ if (resultSchema !== void 0) {
167
+ return fn(params, resultSchema);
168
+ }
169
+ return fn(params);
170
+ }
171
+ function wrapMcpClient(client, options = {}) {
172
+ const maxSummaryLength = options.maxSummaryLength ?? 240;
173
+ const listToolsImpl = typeof client.listTools === "function" ? client.listTools.bind(client) : void 0;
174
+ const callToolImpl = client.callTool.bind(client);
175
+ const wrappedListTools = listToolsImpl ? async (params, requestOptions) => step(
176
+ "mcp:tools/list",
177
+ async () => {
178
+ if (requestOptions !== void 0) {
179
+ return listToolsImpl(params, requestOptions);
180
+ }
181
+ return listToolsImpl(params);
182
+ },
183
+ {
184
+ type: "tool",
185
+ metadata: baseMetadata(options, {
186
+ toolName: "tools/list",
187
+ toolCallId: nextToolCallId(options.toolCallIdPrefix)
188
+ })
189
+ }
190
+ ) : void 0;
191
+ const wrappedCallTool = async (params, resultSchemaOrOptions, maybeOptions) => {
192
+ const { resultSchema, requestOptions, callMetadata } = resolveCallToolArgs(
193
+ resultSchemaOrOptions,
194
+ maybeOptions
195
+ );
196
+ const toolCallId = nextToolCallId(options.toolCallIdPrefix);
197
+ return step(
198
+ `mcp:${params.name}`,
199
+ async () => {
200
+ const result = await invokeCallTool(
201
+ callToolImpl,
202
+ params,
203
+ resultSchema,
204
+ requestOptions
205
+ );
206
+ await recordToolResultOutcome(
207
+ params.name,
208
+ toolCallId,
209
+ result,
210
+ callMetadata
211
+ );
212
+ return result;
213
+ },
214
+ {
215
+ type: "tool",
216
+ metadata: baseMetadata(options, {
217
+ toolName: params.name,
218
+ toolCallId,
219
+ argumentSummary: summarizeMcpValue(
220
+ params.arguments ?? {},
221
+ maxSummaryLength
222
+ ),
223
+ ...callMetadata
224
+ })
225
+ }
226
+ );
227
+ };
228
+ return new Proxy(client, {
229
+ get(target, property, receiver) {
230
+ if (property === "listTools" && wrappedListTools !== void 0) {
231
+ return wrappedListTools;
232
+ }
233
+ if (property === "callTool") {
234
+ return wrappedCallTool;
235
+ }
236
+ const value = Reflect.get(target, property, receiver);
237
+ if (typeof value === "function") {
238
+ return value.bind(target);
239
+ }
240
+ return value;
241
+ }
242
+ });
243
+ }
244
+ function resetMcpToolCallIdsForTests() {
245
+ toolCallCounter = 0;
246
+ }
247
+
248
+ export { hashServerUrl, resetMcpToolCallIdsForTests, resolveCallToolArgs, summarizeMcpValue, wrapMcpClient };
249
+ //# sourceMappingURL=index.mjs.map
250
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/summarize.ts","../src/wrap.ts"],"names":[],"mappings":";;;AAAA,IAAM,0BAAA,GAA6B,GAAA;AAEnC,SAAS,eAAe,KAAA,EAAwB;AAC9C,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB,CA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AM,uBAAA;AAAA,UACJ,MAAA,CAAO,IAAA;AAAA,UACP,UAAA;AAAA,UACA,MAAA;AAAA,UACA;AAAA,SACF;AACA,QAAA,OAAO,MAAA;AAAA,MACT,CAAA;AAAA,MACA;AAAA,QACE,IAAA,EAAM,MAAA;AAAA,QACN,QAAA,EAAU,aAAa,OAAA,EAAS;AAAA,UAC9B,UAAU,MAAA,CAAO,IAAA;AAAA,UACjB,UAAA;AAAA,UACA,eAAA,EAAiB,iBAAA;AAAA,YACf,MAAA,CAAO,aAAa,EAAC;AAAA,YACrB;AAAA,WACF;AAAA,UACA,GAAG;AAAA,SACJ;AAAA;AACH,KACF;AAAA,EACF,CAAA;AAEA,EAAA,OAAO,IAAI,MAAM,MAAA,EAAQ;AAAA,IACvB,GAAA,CAAI,MAAA,EAAQ,QAAA,EAAU,QAAA,EAAU;AAC9B,MAAA,IAAI,QAAA,KAAa,WAAA,IAAe,gBAAA,KAAqB,MAAA,EAAW;AAC9D,QAAA,OAAO,gBAAA;AAAA,MACT;AACA,MAAA,IAAI,aAAa,UAAA,EAAY;AAC3B,QAAA,OAAO,eAAA;AAAA,MACT;AACA,MAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,UAAU,QAAQ,CAAA;AACpD,MAAA,IAAI,OAAO,UAAU,UAAA,EAAY;AAC/B,QAAA,OAAO,KAAA,CAAM,KAAK,MAAM,CAAA;AAAA,MAC1B;AACA,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;AAGO,SAAS,2BAAA,GAAoC;AAClD,EAAA,eAAA,GAAkB,CAAA;AACpB","file":"index.mjs","sourcesContent":["const DEFAULT_MAX_SUMMARY_LENGTH = 240;\n\nfunction fallbackString(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[unserializable]\";\n }\n}\n\nexport function summarizeMcpValue(\n value: unknown,\n maxLength = DEFAULT_MAX_SUMMARY_LENGTH,\n): string {\n let text: string;\n try {\n if (typeof value === \"string\") {\n text = value;\n } else {\n // JSON.stringify returns undefined (not a string) for undefined,\n // functions, and symbols; falling through with undefined would crash\n // instrumentation at text.length below.\n const serialized = JSON.stringify(value);\n text = serialized === undefined ? fallbackString(value) : serialized;\n }\n } catch {\n text = fallbackString(value);\n }\n if (text.length <= maxLength) return text;\n return `${text.slice(0, Math.max(0, maxLength - 3))}...`;\n}\n\nexport function hashServerUrl(url: string): string {\n let hash = 0;\n for (let i = 0; i < url.length; i += 1) {\n hash = (hash * 31 + url.charCodeAt(i)) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n","import { observeOutcome, step } from \"agent-inspect\";\n\nimport { hashServerUrl, summarizeMcpValue } from \"./summarize.js\";\nimport type {\n McpClientLike,\n McpClientTracerOptions,\n McpRequestOptions,\n McpTraceMetadata,\n} from \"./types.js\";\n\nlet toolCallCounter = 0;\n\nfunction resultReportsToolError(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const record = value as Record<string, unknown>;\n if (record.isError === true) return true;\n const nested = record.toolResult;\n if (!nested || typeof nested !== \"object\") return false;\n return (nested as Record<string, unknown>).isError === true;\n}\n\nfunction boundedId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\" || trimmed.length > 200) return undefined;\n return trimmed;\n}\n\nasync function recordToolResultOutcome(\n toolName: string,\n toolCallId: string,\n result: unknown,\n callMetadata: Record<string, unknown>,\n): Promise<void> {\n if (!resultReportsToolError(result)) return;\n const operationId = boundedId(callMetadata.operationId);\n const attemptId = boundedId(callMetadata.attemptId);\n await observeOutcome(`mcp:${toolName}:tool-result`, {\n expectation: \"MCP tool result is not an error\",\n status: \"failed\",\n method: \"custom\",\n evidence: {\n toolFailure: true,\n toolName,\n toolCallId,\n ...(operationId !== undefined ? { operationId } : {}),\n ...(attemptId !== undefined ? { attemptId } : {}),\n },\n });\n}\n\nfunction nextToolCallId(prefix?: string): string {\n toolCallCounter += 1;\n const base = prefix?.trim() || \"mcp\";\n return `${base}-${toolCallCounter}`;\n}\n\nfunction baseMetadata(\n options: McpClientTracerOptions,\n overrides: Partial<McpTraceMetadata> = {},\n): Record<string, unknown> {\n const metadata: McpTraceMetadata = {\n source: { type: \"mcp-client\" },\n ...(options.serverName ? { mcpServerName: options.serverName } : {}),\n ...(options.serverUrl\n ? { mcpServerUrlHash: hashServerUrl(options.serverUrl) }\n : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...overrides,\n };\n return { ...(options.metadata ?? {}), ...metadata };\n}\n\n/** SDK RequestOptions keys — must never be swallowed as AgentInspect metadata. */\nconst SDK_REQUEST_OPTION_KEYS = [\n \"signal\",\n \"timeout\",\n \"onprogress\",\n \"resetTimeoutOnProgress\",\n \"maxTotalTimeout\",\n \"relatedRequestId\",\n \"resumptionToken\",\n \"onresumptiontoken\",\n] as const;\n\nfunction isSdkRequestOptions(value: unknown): value is McpRequestOptions {\n if (!value || typeof value !== \"object\") return false;\n const obj = value as Record<string, unknown>;\n return SDK_REQUEST_OPTION_KEYS.some((key) => key in obj);\n}\n\n/**\n * AgentInspect per-call metadata bag: `{ metadata: {...} }` without SDK option keys.\n * Must not consume ordinary SDK RequestOptions that happen to be objects.\n */\nfunction isAgentInspectMetadataBag(\n value: unknown,\n): value is { metadata?: Record<string, unknown> } {\n if (!value || typeof value !== \"object\") return false;\n if (isSdkRequestOptions(value)) return false;\n const obj = value as Record<string, unknown>;\n if (!(\"metadata\" in obj)) return false;\n // Zod/result schemas expose parse — never treat those as AI bags.\n if (\"parse\" in obj) return false;\n return true;\n}\n\nfunction extractCallMetadata(bag: {\n metadata?: Record<string, unknown>;\n}): Record<string, unknown> {\n if (bag.metadata && typeof bag.metadata === \"object\") {\n return bag.metadata;\n }\n return {};\n}\n\n/** Peel AgentInspect `metadata` without consuming SDK RequestOptions keys. */\nfunction peelOptionsObject(value: unknown): {\n callMetadata: Record<string, unknown>;\n requestOptions: McpRequestOptions | undefined;\n} {\n if (value === null || value === undefined) {\n return { callMetadata: {}, requestOptions: undefined };\n }\n if (typeof value !== \"object\") {\n return { callMetadata: {}, requestOptions: undefined };\n }\n const obj = value as Record<string, unknown>;\n const callMetadata = extractCallMetadata(obj);\n\n // Pure AI bag — do not forward as SDK RequestOptions.\n if (isAgentInspectMetadataBag(value)) {\n return { callMetadata, requestOptions: undefined };\n }\n\n if (isSdkRequestOptions(value) || Object.keys(obj).length > 0) {\n const { metadata: _ignored, ...rest } = obj;\n return {\n callMetadata,\n requestOptions: rest as McpRequestOptions,\n };\n }\n\n return { callMetadata, requestOptions: undefined };\n}\n\n/**\n * Resolve SDK callTool arity:\n * callTool(params, resultSchema?, requestOptions?)\n * plus AgentInspect overloads that peel `{ metadata }` without dropping RequestOptions.\n * Composed `{ timeout, metadata: { operationId, attemptId } }` keeps both sides.\n */\nexport function resolveCallToolArgs(\n resultSchemaOrOptions?: unknown,\n maybeOptions?: unknown,\n): {\n resultSchema: unknown;\n requestOptions: McpRequestOptions | undefined;\n callMetadata: Record<string, unknown>;\n} {\n // Three-arg form: (params, schema|undefined, options)\n if (maybeOptions !== undefined) {\n const peeled = peelOptionsObject(maybeOptions);\n return {\n resultSchema: resultSchemaOrOptions,\n requestOptions: peeled.requestOptions,\n callMetadata: peeled.callMetadata,\n };\n }\n\n // Two-arg form: (params, schema) OR (params, { metadata }) OR (params, RequestOptions)\n if (isAgentInspectMetadataBag(resultSchemaOrOptions)) {\n return {\n resultSchema: undefined,\n requestOptions: undefined,\n callMetadata: extractCallMetadata(resultSchemaOrOptions),\n };\n }\n\n if (isSdkRequestOptions(resultSchemaOrOptions)) {\n const peeled = peelOptionsObject(resultSchemaOrOptions);\n return {\n resultSchema: undefined,\n requestOptions: peeled.requestOptions,\n callMetadata: peeled.callMetadata,\n };\n }\n\n return {\n resultSchema: resultSchemaOrOptions,\n requestOptions: undefined,\n callMetadata: {},\n };\n}\n\nfunction invokeCallTool(\n callToolImpl: McpClientLike[\"callTool\"],\n params: Parameters<McpClientLike[\"callTool\"]>[0],\n resultSchema: unknown,\n requestOptions: McpRequestOptions | undefined,\n): Promise<unknown> {\n const fn = callToolImpl as (\n p: unknown,\n schema?: unknown,\n opts?: unknown,\n ) => Promise<unknown>;\n if (requestOptions !== undefined) {\n return fn(params, resultSchema, requestOptions);\n }\n if (resultSchema !== undefined) {\n return fn(params, resultSchema);\n }\n return fn(params);\n}\n\n/**\n * Wraps an MCP client so tools/list and tools/call emit local tool steps.\n * Telemetry only — does not proxy network behavior beyond the wrapped client.\n *\n * Uses a Proxy over the original client so prototype methods (`connect`,\n * `close`, `listResources`, …), private SDK state, and `instanceof` stay intact.\n * A shallow object spread would drop prototype methods and copy private fields.\n *\n * Forwards the real SDK argument positions, including `RequestOptions`\n * (`signal`, `timeout`, progress callbacks). Does not fake cancellation while\n * still dispatching the underlying request.\n */\nexport function wrapMcpClient<T extends McpClientLike>(\n client: T,\n options: McpClientTracerOptions = {},\n): T {\n const maxSummaryLength = options.maxSummaryLength ?? 240;\n\n const listToolsImpl =\n typeof client.listTools === \"function\"\n ? client.listTools.bind(client)\n : undefined;\n const callToolImpl = client.callTool.bind(client);\n\n const wrappedListTools = listToolsImpl\n ? async (params?: unknown, requestOptions?: McpRequestOptions) =>\n step(\n \"mcp:tools/list\",\n async () => {\n if (requestOptions !== undefined) {\n return (\n listToolsImpl as (\n p?: unknown,\n opts?: unknown,\n ) => Promise<unknown>\n )(params, requestOptions);\n }\n return listToolsImpl(params);\n },\n {\n type: \"tool\",\n metadata: baseMetadata(options, {\n toolName: \"tools/list\",\n toolCallId: nextToolCallId(options.toolCallIdPrefix),\n }),\n },\n )\n : undefined;\n\n const wrappedCallTool = async (\n params: Parameters<McpClientLike[\"callTool\"]>[0],\n resultSchemaOrOptions?: unknown,\n maybeOptions?: unknown,\n ) => {\n const { resultSchema, requestOptions, callMetadata } = resolveCallToolArgs(\n resultSchemaOrOptions,\n maybeOptions,\n );\n\n const toolCallId = nextToolCallId(options.toolCallIdPrefix);\n return step(\n `mcp:${params.name}`,\n async () => {\n const result = await invokeCallTool(\n callToolImpl,\n params,\n resultSchema,\n requestOptions,\n );\n await recordToolResultOutcome(\n params.name,\n toolCallId,\n result,\n callMetadata,\n );\n return result;\n },\n {\n type: \"tool\",\n metadata: baseMetadata(options, {\n toolName: params.name,\n toolCallId,\n argumentSummary: summarizeMcpValue(\n params.arguments ?? {},\n maxSummaryLength,\n ),\n ...callMetadata,\n }),\n },\n );\n };\n\n return new Proxy(client, {\n get(target, property, receiver) {\n if (property === \"listTools\" && wrappedListTools !== undefined) {\n return wrappedListTools;\n }\n if (property === \"callTool\") {\n return wrappedCallTool;\n }\n const value = Reflect.get(target, property, receiver);\n if (typeof value === \"function\") {\n return value.bind(target);\n }\n return value;\n },\n }) as T;\n}\n\n/** @internal resets tool call ids for deterministic tests */\nexport function resetMcpToolCallIdsForTests(): void {\n toolCallCounter = 0;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-inspect/mcp",
3
- "version": "6.31.37",
3
+ "version": "6.31.39",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Local MCP client tool-call tracing for AgentInspect",
@@ -35,7 +35,7 @@
35
35
  "dist"
36
36
  ],
37
37
  "dependencies": {
38
- "agent-inspect": "6.31.37"
38
+ "agent-inspect": "6.31.39"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"