agentrail-node 0.2.0 → 0.3.0

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/mcp.js CHANGED
@@ -1,45 +1,712 @@
1
- import { context, trace, SpanStatusCode } from '@opentelemetry/api';
1
+ import { context, createContextKey, SpanStatusCode } from '@opentelemetry/api';
2
+ import { createParser } from 'eventsource-parser';
3
+ import { MCP_PAYLOAD_BYTES } from './limits.js';
4
+ import { CaptureError } from './options.js';
2
5
  import { boundedText } from './privacy.js';
6
+ import { internalOf } from './runtime.js';
7
+ /** The transport spans a request's handlers run under, by JSON-RPC id. */
8
+ const callsKey = createContextKey('agentrail.mcp.calls');
9
+ const CLIENT_INFO = 'io.modelcontextprotocol/clientInfo';
10
+ const PROTOCOL_VERSION = 'io.modelcontextprotocol/protocolVersion';
11
+ /**
12
+ * The most of a request body the handler wrapper reads to see its messages:
13
+ * createMcpHandler's own default (`DEFAULT_MAX_REQUEST_BODY_SIZE`), past
14
+ * which it refuses the body unread.
15
+ */
16
+ const MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;
17
+ /**
18
+ * The most of a request's header names a span carries, cut between names.
19
+ * The collector keeps 40 names in 512 characters, counted after it leaves
20
+ * out what a proxy added, so the SDK sends far more and leaves that to it.
21
+ */
22
+ const HEADER_NAMES_CHARACTERS = 4096;
3
23
  function record(value) {
4
24
  return typeof value === 'object' && value !== null
5
25
  ? value
6
26
  : undefined;
7
27
  }
8
- /** Wrap the callbacks passed to public registerTool/registerResource/registerPrompt APIs. No transport is patched. */
28
+ /** A JSON-RPC id as a map key: 1 and "1" stay apart. */
29
+ function idKey(id) {
30
+ return typeof id === 'string' || typeof id === 'number'
31
+ ? JSON.stringify(id)
32
+ : undefined;
33
+ }
34
+ /** A JSON-RPC id as text, a number in decimal; undefined where there is none. */
35
+ function idText(id) {
36
+ return typeof id === 'string'
37
+ ? id
38
+ : typeof id === 'number' && Number.isFinite(id)
39
+ ? String(id)
40
+ : undefined;
41
+ }
42
+ /** Names comma-joined, whole names only, within HEADER_NAMES_CHARACTERS. */
43
+ function joinedNames(names) {
44
+ let text = '';
45
+ for (const name of names) {
46
+ const grown = text === '' ? name : `${text},${name}`;
47
+ if (grown.length > HEADER_NAMES_CHARACTERS)
48
+ break;
49
+ text = grown;
50
+ }
51
+ return text;
52
+ }
53
+ /** JSON text as the MCP SDK encodes a message; undefined for what JSON cannot hold. */
54
+ function jsonText(value) {
55
+ try {
56
+ // JSON.stringify gives undefined for undefined, a function or a symbol.
57
+ const text = JSON.stringify(value);
58
+ return text;
59
+ }
60
+ catch (error) {
61
+ // A cycle or a BigInt: an in-process transport can carry either.
62
+ if (error instanceof TypeError)
63
+ return undefined;
64
+ throw error;
65
+ }
66
+ }
67
+ /** JSON text of what the redact hook returned; a cycle or a BigInt throws to the hook's failure. */
68
+ function jsonOf(value) {
69
+ const text = JSON.stringify(value);
70
+ return text;
71
+ }
72
+ /** A value as JSON gives it back; undefined where JSON cannot hold it. */
73
+ function copyOf(value) {
74
+ const text = jsonText(value);
75
+ return text === undefined ? undefined : JSON.parse(text);
76
+ }
77
+ function jsonBytes(value) {
78
+ const text = jsonText(value);
79
+ return text === undefined ? undefined : Buffer.byteLength(text);
80
+ }
81
+ function parseJson(text) {
82
+ try {
83
+ return JSON.parse(text);
84
+ }
85
+ catch (error) {
86
+ if (error instanceof SyntaxError)
87
+ return undefined;
88
+ throw error;
89
+ }
90
+ }
91
+ /**
92
+ * A resource URI as a span names it: without its query and fragment, nor the
93
+ * userinfo of its authority, which can carry credentials. Cut as text, so
94
+ * the rest stays as the client wrote it.
95
+ */
96
+ function resourceName(uri) {
97
+ const bare = uri.replace(/[?#].*$/su, '');
98
+ return bare.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/]*@/u, '$1');
99
+ }
100
+ function nameOf(method, params) {
101
+ const uri = params?.uri;
102
+ const name = method === 'resources/read'
103
+ ? typeof uri === 'string'
104
+ ? resourceName(uri)
105
+ : undefined
106
+ : method === 'tools/call' || method === 'prompts/get'
107
+ ? params?.name
108
+ : undefined;
109
+ // An empty name is no name: the span is mcp.<method>, with no colon.
110
+ return typeof name === 'string' && name !== '' ? name : null;
111
+ }
112
+ function spanName(method, name) {
113
+ return boundedText(name === null ? `mcp.${method}` : `mcp.${method}:${name}`, 256);
114
+ }
115
+ function kindOf(method) {
116
+ return method === 'tools/call'
117
+ ? 'tool.call'
118
+ : boundedText(`mcp.${method}`, 256);
119
+ }
120
+ function failed(span, type) {
121
+ span.setStatus({ code: SpanStatusCode.ERROR });
122
+ if (type !== undefined)
123
+ span.setAttribute('error.type', type);
124
+ }
125
+ /** The type a span gives a thrown value: an Error's name, nothing for anything else. */
126
+ function thrownType(error) {
127
+ return error instanceof Error ? error.name : undefined;
128
+ }
129
+ /**
130
+ * Self-reported client facts. The protocol is what this message carried
131
+ * (initialize params, its envelope, the header), never negotiated nor
132
+ * remembered; the client's name and version are its envelope's, else what
133
+ * it declared in initialize.
134
+ */
135
+ function clientOf(method, params, header, declared) {
136
+ const meta = record(params?._meta);
137
+ const info = (method === 'initialize' ? record(params?.clientInfo) : undefined) ??
138
+ record(meta?.[CLIENT_INFO]);
139
+ const client = boundedText(info?.name, 128) ?? declared.client;
140
+ const clientVersion = boundedText(info?.version, 128) ?? declared.clientVersion;
141
+ const protocol = boundedText((method === 'initialize' ? params?.protocolVersion : undefined) ??
142
+ meta?.[PROTOCOL_VERSION] ??
143
+ header, 64);
144
+ return {
145
+ ...(client === undefined ? {} : { client }),
146
+ ...(clientVersion === undefined ? {} : { clientVersion }),
147
+ ...(protocol === undefined ? {} : { protocol }),
148
+ };
149
+ }
150
+ /** Cut UTF-8 text to at most `limit` bytes on a character boundary, so it stays well-formed. */
151
+ function truncated(text, limit) {
152
+ const bytes = Buffer.from(text, 'utf8');
153
+ let end = limit;
154
+ // A continuation byte (10xxxxxx) at the cut belongs to a character it would split.
155
+ while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80)
156
+ end--;
157
+ return bytes.subarray(0, end).toString('utf8');
158
+ }
159
+ /** Payloads as one span carries them: cut only when together they cannot fit one export. */
160
+ function fitted(request, response) {
161
+ const requestBytes = request === undefined ? 0 : Buffer.byteLength(request);
162
+ const responseBytes = response === undefined ? 0 : Buffer.byteLength(response);
163
+ const facts = {};
164
+ if (requestBytes + responseBytes <= MCP_PAYLOAD_BYTES) {
165
+ if (request !== undefined)
166
+ facts.requestPayload = request;
167
+ if (response !== undefined)
168
+ facts.responsePayload = response;
169
+ return facts;
170
+ }
171
+ // Each gets half; one that needs less leaves the rest to the other.
172
+ const half = Math.floor(MCP_PAYLOAD_BYTES / 2);
173
+ const requestLimit = requestBytes <= half
174
+ ? requestBytes
175
+ : Math.max(half, MCP_PAYLOAD_BYTES - responseBytes);
176
+ const responseLimit = MCP_PAYLOAD_BYTES - requestLimit;
177
+ if (request !== undefined)
178
+ if (requestBytes > requestLimit) {
179
+ facts.requestPayload = truncated(request, requestLimit);
180
+ facts.requestTruncated = true;
181
+ }
182
+ else
183
+ facts.requestPayload = request;
184
+ if (response !== undefined)
185
+ if (responseBytes > responseLimit) {
186
+ facts.responsePayload = truncated(response, responseLimit);
187
+ facts.responseTruncated = true;
188
+ }
189
+ else
190
+ facts.responsePayload = response;
191
+ return facts;
192
+ }
193
+ /** A JSON media type, as createMcpHandler takes one. */
194
+ function isJson(type) {
195
+ const media = (type ?? '').split(';')[0]?.trim().toLowerCase() ?? '';
196
+ return media === 'application/json' || media.endsWith('+json');
197
+ }
198
+ /**
199
+ * Reads a copy of a body the handler would read too, up to its bound;
200
+ * undefined for one it refuses unread (not JSON, or declared too large),
201
+ * past the bound, or when it cannot be read.
202
+ */
203
+ async function bodyText(request, limit) {
204
+ const declared = Number(request.headers.get('content-length') ?? 0);
205
+ if (!isJson(request.headers.get('content-type')) ||
206
+ !(declared <= limit) ||
207
+ request.bodyUsed)
208
+ return undefined;
209
+ const copy = request.clone().body;
210
+ if (copy === null)
211
+ return undefined;
212
+ const reader = copy.getReader();
213
+ const chunks = [];
214
+ let total = 0;
215
+ try {
216
+ for (;;) {
217
+ const { done, value } = await reader.read();
218
+ if (done)
219
+ return Buffer.concat(chunks).toString('utf8');
220
+ total += value.byteLength;
221
+ if (total > limit) {
222
+ // Not awaited: a tee'd copy's cancel settles only once the other
223
+ // copy, the handler's, is done too.
224
+ reader.cancel().catch(ended);
225
+ return undefined;
226
+ }
227
+ chunks.push(value);
228
+ }
229
+ }
230
+ catch (error) {
231
+ // The handler reads its own copy and answers a body that cannot be read
232
+ // (the client went away mid-upload); this copy only goes without spans.
233
+ if (error instanceof Error)
234
+ return undefined;
235
+ throw error;
236
+ }
237
+ }
238
+ /**
239
+ * Captures MCP calls through public APIs only; no transport is patched.
240
+ *
241
+ * - `transport(t)` wraps a transport you own before `server.connect`: one
242
+ * step per JSON-RPC message the server receives.
243
+ * - `handler(h)` wraps what `createMcpHandler` returns, the same way.
244
+ * - `tool`, `resource` and `prompt` wrap the callbacks you register: inside a
245
+ * wrapped transport, each is the call's child span; alone, it is the step.
246
+ */
9
247
  export function mcp(options) {
10
- function wrap(method, name, handler) {
248
+ const internal = internalOf(options.client);
249
+ const { runtime } = internal;
250
+ /**
251
+ * What the HTTP request that carried a message says of itself. Its header
252
+ * names as Node's HTTP server received them, in their order and case,
253
+ * where the SDK's HTTP instrumentation saw the request being answered;
254
+ * otherwise as the Fetch `Headers` hold them, lower-cased and sorted.
255
+ */
256
+ function requestFactsOf(request) {
257
+ const { headers } = request;
258
+ const names = joinedNames(runtime.state(context.active())?.headerNames ?? headers.keys());
259
+ const userAgent = headers.get('user-agent');
260
+ const accept = headers.get('accept');
261
+ const acceptEncoding = headers.get('accept-encoding');
262
+ return {
263
+ method: request.method,
264
+ url: request.url,
265
+ ...(names === '' ? {} : { headerNames: names }),
266
+ ...(userAgent === null ? {} : { userAgent }),
267
+ ...(accept === null ? {} : { accept }),
268
+ ...(acceptEncoding === null ? {} : { acceptEncoding }),
269
+ };
270
+ }
271
+ /** Request facts and the JSON-RPC id, for a message that came by HTTP only. */
272
+ function carried(facts, id, request) {
273
+ if (request === undefined)
274
+ return;
275
+ facts.request = request;
276
+ const text = idText(id);
277
+ if (text !== undefined)
278
+ facts.jsonrpcId = text;
279
+ }
280
+ function begin(message, header, declared,
281
+ /** Undefined for a message that did not come by HTTP, as over stdio. */
282
+ request) {
283
+ const { method } = message;
284
+ // A response the client sent back to a server request is not a call.
285
+ if (typeof method !== 'string')
286
+ return undefined;
287
+ const params = record(message.params);
288
+ const name = nameOf(method, params);
289
+ const facts = { layer: 'transport', method };
290
+ carried(facts, message.id, request);
291
+ const bytes = jsonBytes(message);
292
+ if (bytes !== undefined)
293
+ facts.requestBytes = bytes;
294
+ const client = clientOf(method, params, header, declared);
295
+ if (method === 'initialize') {
296
+ if (client.client !== undefined)
297
+ declared.client = client.client;
298
+ if (client.clientVersion !== undefined)
299
+ declared.clientVersion = client.clientVersion;
300
+ }
301
+ const { span, ctx } = internal.start(spanName(method, name), {
302
+ surface: 'mcp',
303
+ kind: kindOf(method),
304
+ mcp: { method, ...(name === null ? {} : { name }), ...client },
305
+ }, { mcpFacts: facts });
306
+ return {
307
+ id: 'id' in message ? message.id : undefined,
308
+ method,
309
+ name,
310
+ params: message.params,
311
+ span,
312
+ ctx,
313
+ facts,
314
+ };
315
+ }
316
+ function capture(hook, call, response) {
317
+ let request;
318
+ let result;
319
+ try {
320
+ // Copies, so a hook that redacts in place never changes the real
321
+ // request or the answer the client is about to get.
322
+ const redacted = hook.redact({
323
+ method: call.method,
324
+ name: call.name,
325
+ request: copyOf(call.params),
326
+ response: copyOf(response),
327
+ });
328
+ if (redacted === null)
329
+ return;
330
+ request = jsonOf(redacted.request);
331
+ result = jsonOf(redacted.response);
332
+ }
333
+ catch (error) {
334
+ // The application's hook, or what it returned, failed: the call goes
335
+ // on unaffected, and its span goes without payloads.
336
+ runtime.options.report(new CaptureError('payload_redact_failed', 'traces', 1, error instanceof Error ? error : new Error(String(error))));
337
+ return;
338
+ }
339
+ Object.assign(call.facts, fitted(request, result));
340
+ }
341
+ function finish(call, response, sessionId) {
342
+ const { span, facts, threw } = call;
343
+ if (typeof sessionId === 'string' && sessionId !== '')
344
+ facts.sessionHash = runtime.hash(sessionId);
345
+ const error = record(response?.error);
346
+ if (response !== undefined) {
347
+ const bytes = jsonBytes(response);
348
+ if (bytes !== undefined)
349
+ facts.responseBytes = bytes;
350
+ if (error !== undefined) {
351
+ // The collector keeps a 32-bit code and refuses an export with any
352
+ // other; the span is still an error without it.
353
+ if (typeof error.code === 'number' &&
354
+ Number.isInteger(error.code) &&
355
+ error.code >= -2_147_483_648 &&
356
+ error.code <= 2_147_483_647)
357
+ facts.errorCode = error.code;
358
+ failed(span, 'McpJsonRpcError');
359
+ }
360
+ else if (call.method === 'tools/call' &&
361
+ record(response.result)?.isError === true) {
362
+ facts.isError = true;
363
+ if (threw === undefined)
364
+ failed(span, 'tool_error');
365
+ }
366
+ if (options.capturePayloads !== undefined)
367
+ capture(options.capturePayloads, call, error ?? response.result);
368
+ }
369
+ else if (options.capturePayloads !== undefined)
370
+ // A notification, or a request never answered: its request still goes.
371
+ capture(options.capturePayloads, call, undefined);
372
+ // A handler that threw is a failed call, though the server answered the
373
+ // throw with an isError result of its own (result.is_error stays); a
374
+ // JSON-RPC error answer is that error, whatever raised it.
375
+ if (threw !== undefined && error === undefined)
376
+ failed(span, threw.type);
377
+ span.end();
378
+ }
379
+ /** Wraps a transport you own; pass the result to `server.connect`. */
380
+ function transport(inner) {
381
+ const pending = new Map();
382
+ // One transport is one connection: its initialize names the client.
383
+ const declared = {};
384
+ let onmessage = inner.onmessage;
385
+ let onclose = inner.onclose;
386
+ const received = (message, extra) => {
387
+ const deliver = () => {
388
+ onmessage?.(message, extra);
389
+ };
390
+ const call = begin(message, extra?.request?.headers.get('mcp-protocol-version'), declared, extra?.request === undefined
391
+ ? undefined
392
+ : requestFactsOf(extra.request));
393
+ if (call === undefined) {
394
+ deliver();
395
+ return;
396
+ }
397
+ const key = idKey(call.id);
398
+ if (key === undefined) {
399
+ try {
400
+ context.with(call.ctx, deliver);
401
+ }
402
+ finally {
403
+ finish(call, undefined, inner.sessionId);
404
+ // A request the client gave up on gets no response.
405
+ if (call.method === 'notifications/cancelled') {
406
+ const cancelled = idKey(record(call.params)?.requestId);
407
+ const gone = cancelled === undefined ? undefined : pending.get(cancelled);
408
+ if (cancelled !== undefined && gone !== undefined) {
409
+ pending.delete(cancelled);
410
+ finish(gone, undefined, inner.sessionId);
411
+ }
412
+ }
413
+ }
414
+ return;
415
+ }
416
+ pending.set(key, call);
417
+ context.with(call.ctx.setValue(callsKey, pending), deliver);
418
+ };
419
+ const send = (message, sendOptions) => {
420
+ const sent = message;
421
+ const key = 'method' in sent || !('result' in sent || 'error' in sent)
422
+ ? undefined
423
+ : idKey(sent.id);
424
+ const call = key === undefined ? undefined : pending.get(key);
425
+ if (key !== undefined && call !== undefined) {
426
+ pending.delete(key);
427
+ finish(call, sent, inner.sessionId);
428
+ }
429
+ return inner.send(message, sendOptions);
430
+ };
431
+ const closed = () => {
432
+ for (const call of pending.values())
433
+ finish(call, undefined, inner.sessionId);
434
+ pending.clear();
435
+ onclose?.();
436
+ };
437
+ // Everything else reaches the transport itself, so its own methods
438
+ // (`handleRequest`) work through the wrapper too.
439
+ return new Proxy(inner, {
440
+ get(target, property) {
441
+ if (property === 'send')
442
+ return send;
443
+ if (property === 'onmessage')
444
+ return onmessage;
445
+ if (property === 'onclose')
446
+ return onclose;
447
+ const value = Reflect.get(target, property, target);
448
+ return typeof value === 'function'
449
+ ? value.bind(target)
450
+ : value;
451
+ },
452
+ set(target, property, value) {
453
+ if (property === 'onmessage') {
454
+ onmessage = value;
455
+ target.onmessage = onmessage === undefined ? undefined : received;
456
+ return true;
457
+ }
458
+ if (property === 'onclose') {
459
+ onclose = value;
460
+ target.onclose = closed;
461
+ return true;
462
+ }
463
+ return Reflect.set(target, property, value, target);
464
+ },
465
+ });
466
+ }
467
+ /** Ends each call as its answer comes; returns the response to serve. */
468
+ function observe(request, response, calls) {
469
+ // Only an id the server issued; one a request alone carried is not a session.
470
+ const session = response.headers.get('mcp-session-id');
471
+ for (const call of calls)
472
+ call.facts.httpStatus = response.status;
473
+ const waiting = new Map();
474
+ for (const call of calls) {
475
+ const key = idKey(call.id);
476
+ if (key === undefined)
477
+ finish(call, undefined, session);
478
+ else
479
+ waiting.set(key, call);
480
+ }
481
+ if (waiting.size === 0)
482
+ return response;
483
+ // Left without a JSON-RPC answer: refused, where the status says so.
484
+ const rest = () => {
485
+ for (const call of waiting.values()) {
486
+ if (response.status >= 400)
487
+ failed(call.span, 'McpTransportRejected');
488
+ finish(call, undefined, session);
489
+ }
490
+ waiting.clear();
491
+ };
492
+ const answered = (value) => {
493
+ for (const item of Array.isArray(value) ? value : [value]) {
494
+ const message = record(item);
495
+ if (message === undefined ||
496
+ 'method' in message ||
497
+ !('result' in message || 'error' in message))
498
+ continue;
499
+ // A request refused before its id was read is answered with id null.
500
+ const key = idKey(message.id) ??
501
+ (message.id === null && waiting.size === 1
502
+ ? [...waiting.keys()][0]
503
+ : undefined);
504
+ const call = key === undefined ? undefined : waiting.get(key);
505
+ if (key === undefined || call === undefined)
506
+ continue;
507
+ waiting.delete(key);
508
+ finish(call, message, session);
509
+ }
510
+ };
511
+ const type = response.headers.get('content-type') ?? '';
512
+ const { body } = response;
513
+ // A subscriptions/listen stream lasts as long as the client listens:
514
+ // never read, so nothing here holds its subscription open.
515
+ if (body === null ||
516
+ calls.some((call) => call.method === 'subscriptions/listen'))
517
+ rest();
518
+ else if (type.includes('text/event-stream')) {
519
+ // A tee'd copy: the client's copy is never delayed or changed. A tee
520
+ // cancels its source only once both copies are, so the client's copy
521
+ // lets go of this one too.
522
+ const [delivered, copy] = body.tee();
523
+ const reader = copy.pipeThrough(new TextDecoderStream()).getReader();
524
+ const abandon = () => {
525
+ reader.cancel().catch(ended);
526
+ };
527
+ void events(reader, request.signal, answered, abandon, () => waiting.size === 0).then(rest);
528
+ return new Response(following(delivered, abandon), {
529
+ status: response.status,
530
+ statusText: response.statusText,
531
+ headers: response.headers,
532
+ });
533
+ }
534
+ else if (type.includes('json'))
535
+ void response
536
+ .clone()
537
+ .text()
538
+ .then((text) => {
539
+ answered(parseJson(text));
540
+ }, ended)
541
+ .then(rest);
542
+ else
543
+ rest();
544
+ return response;
545
+ }
546
+ /** Wraps what `createMcpHandler` returns; serve the result in its place. */
547
+ function handler(inner, handlerOptions = {}) {
548
+ const limit = handlerOptions.maxRequestBodySize ?? MAX_REQUEST_BODY_BYTES;
549
+ const fetch = async (request, requestOptions) => {
550
+ if (request.method.toUpperCase() !== 'POST')
551
+ return inner.fetch(request, requestOptions);
552
+ let body = requestOptions?.parsedBody;
553
+ if (body === undefined) {
554
+ const text = await bodyText(request, limit);
555
+ body = text === undefined ? undefined : parseJson(text);
556
+ }
557
+ const header = request.headers.get('mcp-protocol-version');
558
+ // Every message of a batch came by this one request.
559
+ const carrier = requestFactsOf(request);
560
+ // A stateless request is its own connection: only an initialize in it declares the client.
561
+ const declared = {};
562
+ const calls = (Array.isArray(body) ? body : [body]).flatMap((item) => {
563
+ const message = record(item);
564
+ const call = message === undefined
565
+ ? undefined
566
+ : begin(message, header, declared, carrier);
567
+ return call === undefined ? [] : [call];
568
+ });
569
+ const [only] = calls;
570
+ if (only === undefined)
571
+ return inner.fetch(request, requestOptions);
572
+ const byId = new Map();
573
+ for (const call of calls) {
574
+ const key = idKey(call.id);
575
+ if (key !== undefined)
576
+ byId.set(key, call);
577
+ }
578
+ // One message runs under its span; a batch's handlers find theirs by id.
579
+ const ctx = (calls.length === 1 ? only.ctx : context.active()).setValue(callsKey, byId);
580
+ let response;
581
+ try {
582
+ response = await context.with(ctx, () => inner.fetch(request, requestOptions));
583
+ }
584
+ catch (error) {
585
+ for (const call of calls) {
586
+ failed(call.span, thrownType(error));
587
+ finish(call, undefined, null);
588
+ }
589
+ throw error;
590
+ }
591
+ return observe(request, response, calls);
592
+ };
593
+ return { ...inner, fetch };
594
+ }
595
+ function wrap(method, name, callback) {
11
596
  return (...args) => {
12
597
  // All supported registration callbacks receive ServerContext as their final argument.
13
598
  const ctx = args.at(-1);
599
+ const calls = context.active().getValue(callsKey);
600
+ const key = idKey(ctx.mcpReq.id);
601
+ const parent = key === undefined ? undefined : calls?.get(key);
602
+ const kind = kindOf(method);
603
+ if (parent !== undefined)
604
+ // The transport span is the call; this is the work inside it.
605
+ return context.with(parent.ctx, () => run(internal.start(spanName(method, name), { surface: 'mcp', kind, mcp: { method, name } }, { step: false, mcpFacts: { layer: 'handler', method } }), () => callback(...args), undefined, parent));
14
606
  const envelope = record(ctx.mcpReq.envelope);
15
- const clientInfo = record(envelope?.['io.modelcontextprotocol/clientInfo']);
16
- const protocol = boundedText(envelope?.['io.modelcontextprotocol/protocolVersion'] ??
17
- ctx.http?.req?.headers.get('mcp-protocol-version'), 64);
18
- const client = boundedText(clientInfo?.name, 128);
19
- const version = boundedText(clientInfo?.version, 128);
20
- return options.client.milestone(`mcp.${method}:${name}`.slice(0, 256), {
21
- surface: 'mcp',
22
- kind: method === 'tools/call' ? 'tool.call' : `mcp.${method}`,
23
- mcp: {
24
- method,
25
- ...(client === undefined ? {} : { client }),
26
- ...(version === undefined ? {} : { clientVersion: version }),
27
- ...(protocol === undefined ? {} : { protocol }),
28
- },
29
- }, async () => {
30
- const result = await handler(...args);
607
+ const client = clientOf(method,
608
+ // The envelope is what a request's `_meta` carries.
609
+ { _meta: envelope }, ctx.http?.req?.headers.get('mcp-protocol-version'), {});
610
+ const facts = { layer: 'handler', method };
611
+ // Alone, the handler is the step, and carries what a transport span would.
612
+ const request = ctx.http?.req;
613
+ carried(facts, ctx.mcpReq.id, request === undefined ? undefined : requestFactsOf(request));
614
+ if (typeof ctx.sessionId === 'string' && ctx.sessionId !== '')
615
+ facts.sessionHash = runtime.hash(ctx.sessionId);
616
+ return run(internal.start(spanName(method, name), { surface: 'mcp', kind, mcp: { method, name, ...client } }, { mcpFacts: facts }), () => callback(...args), facts);
617
+ };
618
+ }
619
+ function run(started, callback,
620
+ /** A step's facts: alone, the handler carries what a transport span would. */
621
+ step,
622
+ /** The transport call this handler runs inside, told when it throws. */
623
+ parent) {
624
+ const { span } = started;
625
+ return context.with(started.ctx, async () => {
626
+ try {
627
+ const result = await callback();
31
628
  if (record(result)?.isError === true) {
32
- const span = trace.getSpan(context.active());
33
- span?.setStatus({ code: SpanStatusCode.ERROR });
34
- span?.setAttribute('error.type', 'McpOperationError');
629
+ failed(span, 'tool_error');
630
+ if (step?.method === 'tools/call')
631
+ step.isError = true;
35
632
  }
36
633
  return result;
37
- });
38
- };
634
+ }
635
+ catch (error) {
636
+ const type = thrownType(error);
637
+ failed(span, type);
638
+ // The server answers the throw itself (an isError result for a
639
+ // tool); the call it answers is still a failed call, not a failed result.
640
+ if (parent !== undefined)
641
+ parent.threw = { type };
642
+ throw error;
643
+ }
644
+ finally {
645
+ span.end();
646
+ }
647
+ });
39
648
  }
40
649
  return {
41
- tool: (name, handler) => wrap('tools/call', name, handler),
42
- resource: (name, handler) => wrap('resources/read', name, handler),
43
- prompt: (name, handler) => wrap('prompts/get', name, handler),
650
+ transport,
651
+ handler,
652
+ tool: (name, callback) => wrap('tools/call', name, callback),
653
+ resource: (name, callback) => wrap('resources/read', name, callback),
654
+ prompt: (name, callback) => wrap('prompts/get', name, callback),
44
655
  };
45
656
  }
657
+ /**
658
+ * The client's copy of a stream, as it came; cancelling it lets go of the
659
+ * other copy too (`abandon`).
660
+ */
661
+ function following(source, abandon) {
662
+ const reader = source.getReader();
663
+ return new ReadableStream({
664
+ async pull(controller) {
665
+ const chunk = await reader.read();
666
+ if (chunk.done)
667
+ controller.close();
668
+ else
669
+ controller.enqueue(chunk.value);
670
+ },
671
+ cancel(reason) {
672
+ abandon();
673
+ return reader.cancel(reason);
674
+ },
675
+ }, { highWaterMark: 0 });
676
+ }
677
+ /**
678
+ * Feeds each JSON message of an SSE copy to `answered`, until `done`, the
679
+ * request is gone or the copy is let go of.
680
+ */
681
+ async function events(reader, signal, answered, abandon, done) {
682
+ const parser = createParser({
683
+ onEvent: (event) => {
684
+ answered(parseJson(event.data));
685
+ },
686
+ });
687
+ signal.addEventListener('abort', abandon, { once: true });
688
+ try {
689
+ while (!done()) {
690
+ let chunk;
691
+ try {
692
+ chunk = await reader.read();
693
+ }
694
+ catch (error) {
695
+ ended(error);
696
+ return;
697
+ }
698
+ if (chunk.done)
699
+ return;
700
+ parser.feed(chunk.value);
701
+ }
702
+ abandon();
703
+ }
704
+ finally {
705
+ signal.removeEventListener('abort', abandon);
706
+ }
707
+ }
708
+ /** The stream failed (the client went away): the calls left end without a response. */
709
+ function ended(error) {
710
+ if (!(error instanceof Error))
711
+ throw error;
712
+ }