@goodtiming/baton-sdk 0.4.1 → 0.5.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/index.cjs CHANGED
@@ -42,6 +42,30 @@ __export(index_exports, {
42
42
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
43
43
  PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
44
44
  PrincipalWireSchema: () => PrincipalWireSchema,
45
+ PromptGetEndEventSchema: () => PromptGetEndEventSchema,
46
+ PromptGetEndPayloadSchema: () => PromptGetEndPayloadSchema,
47
+ PromptGetErrorEventSchema: () => PromptGetErrorEventSchema,
48
+ PromptGetErrorPayloadSchema: () => PromptGetErrorPayloadSchema,
49
+ PromptGetStartEventSchema: () => PromptGetStartEventSchema,
50
+ PromptGetStartPayloadSchema: () => PromptGetStartPayloadSchema,
51
+ PromptListEndEventSchema: () => PromptListEndEventSchema,
52
+ PromptListEndPayloadSchema: () => PromptListEndPayloadSchema,
53
+ PromptListErrorEventSchema: () => PromptListErrorEventSchema,
54
+ PromptListErrorPayloadSchema: () => PromptListErrorPayloadSchema,
55
+ PromptListStartEventSchema: () => PromptListStartEventSchema,
56
+ PromptListStartPayloadSchema: () => PromptListStartPayloadSchema,
57
+ ResourceListEndEventSchema: () => ResourceListEndEventSchema,
58
+ ResourceListEndPayloadSchema: () => ResourceListEndPayloadSchema,
59
+ ResourceListErrorEventSchema: () => ResourceListErrorEventSchema,
60
+ ResourceListErrorPayloadSchema: () => ResourceListErrorPayloadSchema,
61
+ ResourceListStartEventSchema: () => ResourceListStartEventSchema,
62
+ ResourceListStartPayloadSchema: () => ResourceListStartPayloadSchema,
63
+ ResourceReadEndEventSchema: () => ResourceReadEndEventSchema,
64
+ ResourceReadEndPayloadSchema: () => ResourceReadEndPayloadSchema,
65
+ ResourceReadErrorEventSchema: () => ResourceReadErrorEventSchema,
66
+ ResourceReadErrorPayloadSchema: () => ResourceReadErrorPayloadSchema,
67
+ ResourceReadStartEventSchema: () => ResourceReadStartEventSchema,
68
+ ResourceReadStartPayloadSchema: () => ResourceReadStartPayloadSchema,
45
69
  SDK_VERSION: () => SDK_VERSION,
46
70
  Scrubber: () => Scrubber,
47
71
  StdoutSink: () => StdoutSink,
@@ -61,7 +85,7 @@ __export(index_exports, {
61
85
  module.exports = __toCommonJS(index_exports);
62
86
 
63
87
  // src/version.ts
64
- var SDK_VERSION = "ts-0.4.1";
88
+ var SDK_VERSION = "ts-0.5.0";
65
89
 
66
90
  // src/events.ts
67
91
  var import_zod = require("zod");
@@ -77,7 +101,24 @@ var ToolCallStartPayloadSchema = import_zod.z.object({
77
101
  var ToolCallEndPayloadSchema = import_zod.z.object({
78
102
  tool_name: import_zod.z.string(),
79
103
  result: import_zod.z.unknown().nullable().default(null),
80
- duration_ms: import_zod.z.number().int().nullable().default(null)
104
+ duration_ms: import_zod.z.number().int().nullable().default(null),
105
+ // SPEC §11.4: the producer declares it WITHHELD result-derived data.
106
+ // Absent means CAPTURED, so no consumer needs a version table.
107
+ //
108
+ // `.optional()`, NOT `.default(null)`, for the reason recorded on
109
+ // `ToolCallErrorPayloadSchema.result` below: a default makes this reader
110
+ // an EMITTER, and parsing a stored event from before the member existed
111
+ // would hand back an invented key.
112
+ //
113
+ // ⚠ **This package OMITS the member when capturing, where the Python SDK
114
+ // sends `result_capture: null`.** Both are conformant and SPEC §11.4 says
115
+ // so outright — absent and null are equivalent, and a consumer MUST read
116
+ // the VALUE, never test for the key. It is the same axis `result` already
117
+ // differs on between `baton-sdk` (null) and `baton-proxy` (omitted), per
118
+ // §11.4.3. Omitting is chosen here because the alternative — matching
119
+ // Python — would require regenerating `baton-spec`'s vectors from an
120
+ // UNMERGED branch, pinning a key set no released producer emits.
121
+ result_capture: import_zod.z.string().nullable().optional()
81
122
  }).strict();
82
123
  var ToolCallErrorPayloadSchema = import_zod.z.object({
83
124
  tool_name: import_zod.z.string(),
@@ -99,7 +140,28 @@ var ToolCallErrorPayloadSchema = import_zod.z.object({
99
140
  // silent when it does not. What makes the EMITTED shape complete is the
100
141
  // emitter declaring `result` on both failure legs (`withBaton.ts`),
101
142
  // explicitly `null` on a throw — not the schema filling it in.
102
- result: import_zod.z.unknown().nullable().optional()
143
+ result: import_zod.z.unknown().nullable().optional(),
144
+ // SPEC §11.4, on BOTH payloads because the RETURN failure shape withholds
145
+ // `result` too. Same `.optional()` reasoning as the field above it, and
146
+ // same omit-when-capturing posture as `ToolCallEndPayloadSchema`.
147
+ result_capture: import_zod.z.string().nullable().optional(),
148
+ // SPEC §11.4.3: the producer NAMES a failure it made above the vendor's
149
+ // handler. `tool_call_error` ONLY — unlike `result_capture`, which rides
150
+ // both payloads — because the one case that files `tool_call_end` today
151
+ // IS the false success this member exists to correct, so after the fix
152
+ // nothing carries it on a success payload.
153
+ //
154
+ // A plain `z.string()` and NOT `z.enum(FAILURE_KINDS)`, which SPEC
155
+ // requires rather than permits: a closed enum turns a later registered
156
+ // value into a `ValidationError` on the vendor's tool-call path, which
157
+ // §11.2 says must fail open. The registry in
158
+ // `integrations/mcp/errorResult.ts` constrains what this producer EMITS;
159
+ // it must not constrain what this schema READS.
160
+ //
161
+ // Same `.optional()`-not-`.default(null)` reasoning as the two fields
162
+ // above: a default makes the schema an emitter, and parsing a stored
163
+ // event from before the member existed would hand back an invented key.
164
+ failure_kind: import_zod.z.string().nullable().optional()
103
165
  }).strict();
104
166
  var AnnotationPayloadSchema = import_zod.z.object({
105
167
  intent: import_zod.z.string().nullable().default(null),
@@ -145,8 +207,75 @@ var EventTypeSchema = import_zod.z.enum([
145
207
  "tool_call_end",
146
208
  "tool_call_error",
147
209
  "annotation",
148
- "surface_snapshot"
210
+ "surface_snapshot",
211
+ // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
212
+ // shapes were set by `baton-proxy`, which has been emitting all of them in
213
+ // production — see the payload schemas below.
214
+ "resource_list_start",
215
+ "resource_list_end",
216
+ "resource_list_error",
217
+ "resource_read_start",
218
+ "resource_read_end",
219
+ "resource_read_error",
220
+ "prompt_list_start",
221
+ "prompt_list_end",
222
+ "prompt_list_error",
223
+ "prompt_get_start",
224
+ "prompt_get_end",
225
+ "prompt_get_error"
149
226
  ]);
227
+ var timingShape = { duration_ms: import_zod.z.number().int().nullable().default(null) };
228
+ var failureShape = { error_type: import_zod.z.string(), error_body: import_zod.z.string(), ...timingShape };
229
+ var ResourceListStartPayloadSchema = import_zod.z.object({}).strict();
230
+ var ResourceListEndPayloadSchema = import_zod.z.object({
231
+ count: import_zod.z.number().int(),
232
+ ...timingShape
233
+ }).strict();
234
+ var ResourceListErrorPayloadSchema = import_zod.z.object({
235
+ ...failureShape
236
+ }).strict();
237
+ var ResourceReadStartPayloadSchema = import_zod.z.object({
238
+ uri: import_zod.z.string(),
239
+ /** The caller's own request params, PII-scrubbed (SPEC §7).
240
+ *
241
+ * ⚠ Nullable because the SCHEMA permits it, not because this producer
242
+ * emits it: `withBaton`'s `paramsBag` answers `{}` for an absent bag,
243
+ * matching `baton-proxy` (`dict(params) if params else {}` — it never
244
+ * emits null). A consumer must still read both, since the schema admits
245
+ * both and a third producer may choose either. */
246
+ params: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
247
+ }).strict();
248
+ var ResourceReadEndPayloadSchema = import_zod.z.object({
249
+ uri: import_zod.z.string(),
250
+ ...timingShape
251
+ }).strict();
252
+ var ResourceReadErrorPayloadSchema = import_zod.z.object({
253
+ uri: import_zod.z.string(),
254
+ ...failureShape
255
+ }).strict();
256
+ var PromptListStartPayloadSchema = import_zod.z.object({}).strict();
257
+ var PromptListEndPayloadSchema = import_zod.z.object({
258
+ count: import_zod.z.number().int(),
259
+ ...timingShape
260
+ }).strict();
261
+ var PromptListErrorPayloadSchema = import_zod.z.object({
262
+ ...failureShape
263
+ }).strict();
264
+ var PromptGetStartPayloadSchema = import_zod.z.object({
265
+ name: import_zod.z.string(),
266
+ /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
267
+ * where the request supplied none — see `ResourceReadStartPayloadSchema`'s
268
+ * `params` for why the schema is nullable anyway. */
269
+ params: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
270
+ }).strict();
271
+ var PromptGetEndPayloadSchema = import_zod.z.object({
272
+ name: import_zod.z.string(),
273
+ ...timingShape
274
+ }).strict();
275
+ var PromptGetErrorPayloadSchema = import_zod.z.object({
276
+ name: import_zod.z.string(),
277
+ ...failureShape
278
+ }).strict();
150
279
  var ToolCallStartEventSchema = import_zod.z.object({
151
280
  ...envelopeShape,
152
281
  event_type: import_zod.z.literal("tool_call_start").default("tool_call_start"),
@@ -172,12 +301,84 @@ var SurfaceSnapshotEventSchema = import_zod.z.object({
172
301
  event_type: import_zod.z.literal("surface_snapshot").default("surface_snapshot"),
173
302
  payload: SurfaceSnapshotPayloadSchema
174
303
  }).strict();
304
+ var ResourceListStartEventSchema = import_zod.z.object({
305
+ ...envelopeShape,
306
+ event_type: import_zod.z.literal("resource_list_start").default("resource_list_start"),
307
+ payload: ResourceListStartPayloadSchema
308
+ }).strict();
309
+ var ResourceListEndEventSchema = import_zod.z.object({
310
+ ...envelopeShape,
311
+ event_type: import_zod.z.literal("resource_list_end").default("resource_list_end"),
312
+ payload: ResourceListEndPayloadSchema
313
+ }).strict();
314
+ var ResourceListErrorEventSchema = import_zod.z.object({
315
+ ...envelopeShape,
316
+ event_type: import_zod.z.literal("resource_list_error").default("resource_list_error"),
317
+ payload: ResourceListErrorPayloadSchema
318
+ }).strict();
319
+ var ResourceReadStartEventSchema = import_zod.z.object({
320
+ ...envelopeShape,
321
+ event_type: import_zod.z.literal("resource_read_start").default("resource_read_start"),
322
+ payload: ResourceReadStartPayloadSchema
323
+ }).strict();
324
+ var ResourceReadEndEventSchema = import_zod.z.object({
325
+ ...envelopeShape,
326
+ event_type: import_zod.z.literal("resource_read_end").default("resource_read_end"),
327
+ payload: ResourceReadEndPayloadSchema
328
+ }).strict();
329
+ var ResourceReadErrorEventSchema = import_zod.z.object({
330
+ ...envelopeShape,
331
+ event_type: import_zod.z.literal("resource_read_error").default("resource_read_error"),
332
+ payload: ResourceReadErrorPayloadSchema
333
+ }).strict();
334
+ var PromptListStartEventSchema = import_zod.z.object({
335
+ ...envelopeShape,
336
+ event_type: import_zod.z.literal("prompt_list_start").default("prompt_list_start"),
337
+ payload: PromptListStartPayloadSchema
338
+ }).strict();
339
+ var PromptListEndEventSchema = import_zod.z.object({
340
+ ...envelopeShape,
341
+ event_type: import_zod.z.literal("prompt_list_end").default("prompt_list_end"),
342
+ payload: PromptListEndPayloadSchema
343
+ }).strict();
344
+ var PromptListErrorEventSchema = import_zod.z.object({
345
+ ...envelopeShape,
346
+ event_type: import_zod.z.literal("prompt_list_error").default("prompt_list_error"),
347
+ payload: PromptListErrorPayloadSchema
348
+ }).strict();
349
+ var PromptGetStartEventSchema = import_zod.z.object({
350
+ ...envelopeShape,
351
+ event_type: import_zod.z.literal("prompt_get_start").default("prompt_get_start"),
352
+ payload: PromptGetStartPayloadSchema
353
+ }).strict();
354
+ var PromptGetEndEventSchema = import_zod.z.object({
355
+ ...envelopeShape,
356
+ event_type: import_zod.z.literal("prompt_get_end").default("prompt_get_end"),
357
+ payload: PromptGetEndPayloadSchema
358
+ }).strict();
359
+ var PromptGetErrorEventSchema = import_zod.z.object({
360
+ ...envelopeShape,
361
+ event_type: import_zod.z.literal("prompt_get_error").default("prompt_get_error"),
362
+ payload: PromptGetErrorPayloadSchema
363
+ }).strict();
175
364
  var EventSchema = import_zod.z.discriminatedUnion("event_type", [
176
365
  ToolCallStartEventSchema,
177
366
  ToolCallEndEventSchema,
178
367
  ToolCallErrorEventSchema,
179
368
  AnnotationEventSchema,
180
- SurfaceSnapshotEventSchema
369
+ SurfaceSnapshotEventSchema,
370
+ ResourceListStartEventSchema,
371
+ ResourceListEndEventSchema,
372
+ ResourceListErrorEventSchema,
373
+ ResourceReadStartEventSchema,
374
+ ResourceReadEndEventSchema,
375
+ ResourceReadErrorEventSchema,
376
+ PromptListStartEventSchema,
377
+ PromptListEndEventSchema,
378
+ PromptListErrorEventSchema,
379
+ PromptGetStartEventSchema,
380
+ PromptGetEndEventSchema,
381
+ PromptGetErrorEventSchema
181
382
  ]);
182
383
 
183
384
  // src/scrub.ts
@@ -472,6 +673,7 @@ var HttpSink = class _HttpSink {
472
673
  };
473
674
 
474
675
  // src/integrations/mcp/withBaton.ts
676
+ var import_node_async_hooks = require("async_hooks");
475
677
  var import_uuid2 = require("uuid");
476
678
 
477
679
  // src/integrations/mcp/annotation.ts
@@ -837,6 +1039,24 @@ async function resolveCallPrincipal(hook, call, options) {
837
1039
  }
838
1040
  }
839
1041
 
1042
+ // src/integrations/mcp/safeScrub.ts
1043
+ var warned = /* @__PURE__ */ new Set();
1044
+ function scrubOrNull(scrubber, value, field) {
1045
+ if (value === null) return null;
1046
+ try {
1047
+ return scrubber(value);
1048
+ } catch (err) {
1049
+ if (!warned.has(field)) {
1050
+ warned.add(field);
1051
+ process.stderr.write(
1052
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${String(err)}
1053
+ `
1054
+ );
1055
+ }
1056
+ return null;
1057
+ }
1058
+ }
1059
+
840
1060
  // src/integrations/mcp/runtimeAdapter.ts
841
1061
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
842
1062
  var CLIENT_NAME_MAX_LEN = 128;
@@ -845,7 +1065,7 @@ function clean(name, scrubber) {
845
1065
  if (typeof name !== "string" || !name) return null;
846
1066
  let cleaned = name;
847
1067
  if (scrubber) {
848
- const scrubbed = scrubber(cleaned);
1068
+ const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
849
1069
  if (typeof scrubbed !== "string") return null;
850
1070
  cleaned = scrubbed;
851
1071
  }
@@ -921,7 +1141,11 @@ function registerAnnotationTool(server, options) {
921
1141
  server,
922
1142
  scrubber: options.scrubber
923
1143
  }) ?? UNKNOWN_AGENT_RUNTIME;
924
- const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
1144
+ const scrubbedMeta = scrubOrNull(
1145
+ options.scrubber,
1146
+ meta ? roundMetaCoordinates(meta) : null,
1147
+ "_meta"
1148
+ );
925
1149
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
926
1150
  if (args.signal_type === void 0) {
927
1151
  options.tracker?.mark(sessionId);
@@ -952,6 +1176,7 @@ function registerAnnotationTool(server, options) {
952
1176
  // Agent-facing names -> wire keys, as with `overall_task`
953
1177
  // below: `user_goal` is stored as `intent`, `expected_result` as
954
1178
  // `expected_outcome`.
1179
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
955
1180
  intent: options.scrubber(args.user_goal),
956
1181
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
957
1182
  // `signal_type` is a closed enum — nothing to scrub. The task label
@@ -966,8 +1191,10 @@ function registerAnnotationTool(server, options) {
966
1191
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
967
1192
  // split the injected params use (`overall_task` -> `call_workflow`):
968
1193
  // renaming the param must not move the key the console groups on.
1194
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
969
1195
  workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
970
1196
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1197
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
971
1198
  context: args.context ? options.scrubber(args.context) : null
972
1199
  }
973
1200
  })
@@ -1182,8 +1409,68 @@ function sealKey(dsn) {
1182
1409
  return dsn;
1183
1410
  }
1184
1411
 
1412
+ // src/integrations/mcp/errorResult.ts
1413
+ var TOOL_ERROR_TYPE = "tool_error";
1414
+ var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
1415
+ var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
1416
+ function requestSideFailureKind(entry) {
1417
+ if (entry == null) return "unknown_tool";
1418
+ if (entry.enabled === false) return "tool_disabled";
1419
+ return TASK_MODES.has(entry.execution?.taskSupport) ? void 0 : "invalid_argument";
1420
+ }
1421
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1422
+ function isErrorResult(value) {
1423
+ try {
1424
+ if (typeof value !== "object" || value === null) return false;
1425
+ return Boolean(value.isError);
1426
+ } catch {
1427
+ return false;
1428
+ }
1429
+ }
1430
+ function errorText(value) {
1431
+ const parts = [];
1432
+ try {
1433
+ const content = value?.content;
1434
+ if (!Array.isArray(content)) return "";
1435
+ for (const part of content) {
1436
+ const text = part?.text;
1437
+ if (typeof text !== "string") continue;
1438
+ const trimmed = text.trim();
1439
+ if (trimmed) parts.push(trimmed);
1440
+ }
1441
+ } catch {
1442
+ return "";
1443
+ }
1444
+ return parts.join("\n");
1445
+ }
1446
+ var RESULT_CAPTURE_MODES = ["full", "off"];
1447
+ var WITHHELD = "off";
1448
+ function endResultFields(mode, result, scrubber) {
1449
+ switch (mode) {
1450
+ case WITHHELD:
1451
+ return { result: null, result_capture: WITHHELD };
1452
+ case "full":
1453
+ return { result: scrubber(result) };
1454
+ }
1455
+ }
1456
+ function returnedErrorFields(mode, result, errorBody2, scrubber) {
1457
+ return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
1458
+ }
1459
+ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1460
+ switch (mode) {
1461
+ case WITHHELD:
1462
+ return { error_body: "", result: null, result_capture: WITHHELD };
1463
+ case "full":
1464
+ return { error_body: errorBody2(text()), result: scrubber(result) };
1465
+ }
1466
+ }
1467
+ function requestSideErrorFields(text, errorBody2) {
1468
+ return { error_body: errorBody2(text), result: null };
1469
+ }
1470
+
1185
1471
  // src/integrations/mcp/config.ts
1186
1472
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1473
+ var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1187
1474
  var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1188
1475
  function resolveTenantId(explicit, vendorId) {
1189
1476
  if (explicit) return explicit;
@@ -1294,6 +1581,14 @@ function validateBatonConfig(config) {
1294
1581
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1295
1582
  );
1296
1583
  }
1584
+ if (config.resultCaptureMode !== void 0 && !RESULT_CAPTURE_MODE_SET.has(config.resultCaptureMode)) {
1585
+ throw new Error(
1586
+ `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
1587
+ );
1588
+ }
1589
+ if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
1590
+ throw new Error("BatonConfig.scrubber must be a function.");
1591
+ }
1297
1592
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1298
1593
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1299
1594
  }
@@ -1339,34 +1634,6 @@ var DisabledSink = class {
1339
1634
  }
1340
1635
  };
1341
1636
 
1342
- // src/integrations/mcp/errorResult.ts
1343
- var TOOL_ERROR_TYPE = "tool_error";
1344
- var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1345
- function isErrorResult(value) {
1346
- try {
1347
- if (typeof value !== "object" || value === null) return false;
1348
- return Boolean(value.isError);
1349
- } catch {
1350
- return false;
1351
- }
1352
- }
1353
- function errorText(value) {
1354
- const parts = [];
1355
- try {
1356
- const content = value?.content;
1357
- if (!Array.isArray(content)) return "";
1358
- for (const part of content) {
1359
- const text = part?.text;
1360
- if (typeof text !== "string") continue;
1361
- const trimmed = text.trim();
1362
- if (trimmed) parts.push(trimmed);
1363
- }
1364
- } catch {
1365
- return "";
1366
- }
1367
- return parts.join("\n");
1368
- }
1369
-
1370
1637
  // src/integrations/mcp/handle.ts
1371
1638
  var BatonHandle = class {
1372
1639
  sink;
@@ -1620,6 +1887,8 @@ function buildSeamAugmentations(options) {
1620
1887
  // src/integrations/mcp/withBaton.ts
1621
1888
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
1622
1889
  var wired = /* @__PURE__ */ new WeakSet();
1890
+ var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1891
+ var callSlots = new import_node_async_hooks.AsyncLocalStorage();
1623
1892
  var SurfaceState = class {
1624
1893
  constructor(serverMeta) {
1625
1894
  this.serverMeta = serverMeta;
@@ -1674,105 +1943,137 @@ var SurfaceState = class {
1674
1943
  function errorBody(ctx, text) {
1675
1944
  return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1676
1945
  }
1677
- function batonWrap(nameRef, original, ctx) {
1678
- return async (...callArgs) => {
1679
- const toolName = nameRef.current;
1680
- await maybeEmitSurfaceSnapshot(ctx);
1681
- const extra = callArgs[callArgs.length - 1];
1682
- const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1683
- const meta = extraMeta(extra);
1684
- const runtime = detectAgentRuntime(meta, {
1685
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1686
- // `_meta`; 1.x leaves them in. Both are handed over — see
1687
- // `mcpTypes.extraEnvelope`.
1688
- envelope: extraEnvelope(extra),
1689
- // Tier 2's carrier: neither peer puts client identity on the
1690
- // handler context, both expose the cached handshake on the server.
1691
- server: ctx.server,
1692
- scrubber: ctx.scrubber
1693
- }) ?? UNKNOWN_AGENT_RUNTIME;
1694
- const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
1695
- const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1696
- const dispositions = ctx.paramRegistry.get(toolName);
1697
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1698
- const rawExpected = extractGoalParam(
1699
- params,
1700
- EXPECTED_RESULT_PARAM_NAME,
1701
- toolName,
1702
- dispositions
1703
- );
1704
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);
1705
- const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1706
- const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1707
- const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1708
- const callId = (0, import_uuid2.v7)();
1709
- const principal = await resolveCallPrincipal(
1710
- ctx.resolvePrincipal,
1711
- { extra, toolName, arguments: params },
1712
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1713
- );
1714
- const common = {
1715
- tenant_id: ctx.tenantId,
1716
- vendor_id: ctx.vendorId,
1717
- session_id: sessionId,
1718
- consent_token: ctx.consentToken,
1719
- agent_runtime: runtime,
1720
- // The five `...common` sites below are the tool-call legs — start, end,
1721
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1722
- // annotation, the same five Python stamps (`middleware.py`
1723
- // 503/547/586/644/674; it was four until the returned shape landed
1724
- // there too). `surface_snapshot` is deliberately NOT among them: it
1725
- // describes the SERVER and is captured outside any call, so there is no
1726
- // caller to name (register D5).
1727
- principal,
1728
- // Same five stamps, same exclusion: a surface_snapshot describes the
1729
- // SERVER and is captured outside any call, so it has no caller's
1730
- // transport to name any more than it has a caller to name.
1731
- transport_observed: observeTransport(extra),
1732
- runtime_meta: scrubbedMeta
1733
- };
1734
- if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1735
- await emit(
1736
- ctx.sink,
1737
- () => AnnotationEventSchema.parse({
1738
- ...common,
1739
- sequence_number: ctx.counter.next(sessionId),
1740
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1741
- payload: {
1742
- intent: scrubbedIntent,
1743
- expected_outcome: scrubbedExpected,
1744
- intent_source: INTENT_SOURCE_PARAM,
1745
- tool_name: toolName
1746
- }
1747
- })
1748
- );
1749
- }
1946
+ function errorTypeOf(err) {
1947
+ return err instanceof Error ? err.constructor.name : "Error";
1948
+ }
1949
+ function messageOf(err) {
1950
+ return err instanceof Error ? err.message : String(err);
1951
+ }
1952
+ async function resolveEnvelopeParts(ctx, extra) {
1953
+ const meta = extraMeta(extra);
1954
+ const runtime = detectAgentRuntime(meta, {
1955
+ // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1956
+ // `_meta`; 1.x leaves them in. Both are handed over — see
1957
+ // `mcpTypes.extraEnvelope`.
1958
+ envelope: extraEnvelope(extra),
1959
+ // Tier 2's carrier: neither peer puts client identity on the
1960
+ // handler context, both expose the cached handshake on the server.
1961
+ server: ctx.server,
1962
+ scrubber: ctx.scrubber
1963
+ }) ?? UNKNOWN_AGENT_RUNTIME;
1964
+ const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1965
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1966
+ return { sessionId, runtime, scrubbedMeta };
1967
+ }
1968
+ async function openCall(ctx, toolName, extra, params, registered = true) {
1969
+ await maybeEmitSurfaceSnapshot(ctx);
1970
+ const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1971
+ const dispositions = ctx.paramRegistry.get(toolName);
1972
+ const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
1973
+ const rawExpected = extractGoalParam(
1974
+ params,
1975
+ EXPECTED_RESULT_PARAM_NAME,
1976
+ toolName,
1977
+ dispositions,
1978
+ registered
1979
+ );
1980
+ const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
1981
+ const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
1982
+ const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
1983
+ const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
1984
+ const callId = (0, import_uuid2.v7)();
1985
+ const principal = await resolveCallPrincipal(
1986
+ ctx.resolvePrincipal,
1987
+ { extra, toolName, arguments: params },
1988
+ { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1989
+ );
1990
+ const common = {
1991
+ tenant_id: ctx.tenantId,
1992
+ vendor_id: ctx.vendorId,
1993
+ session_id: sessionId,
1994
+ consent_token: ctx.consentToken,
1995
+ agent_runtime: runtime,
1996
+ // The five `...common` sites below are the tool-call legs — start, end,
1997
+ // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1998
+ // annotation, the same five Python stamps (`middleware.py`
1999
+ // 503/547/586/644/674; it was four until the returned shape landed
2000
+ // there too). `surface_snapshot` is deliberately NOT among them: it
2001
+ // describes the SERVER and is captured outside any call, so there is no
2002
+ // caller to name (register D5).
2003
+ principal,
2004
+ // Same five stamps, same exclusion: a surface_snapshot describes the
2005
+ // SERVER and is captured outside any call, so it has no caller's
2006
+ // transport to name any more than it has a caller to name.
2007
+ transport_observed: observeTransport(extra),
2008
+ runtime_meta: scrubbedMeta
2009
+ };
2010
+ if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1750
2011
  await emit(
1751
2012
  ctx.sink,
1752
- () => ToolCallStartEventSchema.parse({
2013
+ () => AnnotationEventSchema.parse({
1753
2014
  ...common,
1754
- call_id: callId,
1755
2015
  sequence_number: ctx.counter.next(sessionId),
1756
2016
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1757
2017
  payload: {
1758
- tool_name: toolName,
1759
- params: ctx.scrubber(params),
1760
- call_intent: scrubbedIntent,
1761
- call_expected: scrubbedExpected,
1762
- call_workflow: scrubbedWorkflow,
1763
- intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
2018
+ intent: scrubbedIntent,
2019
+ expected_outcome: scrubbedExpected,
2020
+ intent_source: INTENT_SOURCE_PARAM,
2021
+ tool_name: toolName
1764
2022
  }
1765
2023
  })
1766
2024
  );
2025
+ }
2026
+ await emit(
2027
+ ctx.sink,
2028
+ () => ToolCallStartEventSchema.parse({
2029
+ ...common,
2030
+ call_id: callId,
2031
+ sequence_number: ctx.counter.next(sessionId),
2032
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2033
+ payload: {
2034
+ tool_name: toolName,
2035
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for params
2036
+ params: ctx.scrubber(params),
2037
+ call_intent: scrubbedIntent,
2038
+ call_expected: scrubbedExpected,
2039
+ call_workflow: scrubbedWorkflow,
2040
+ intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
2041
+ }
2042
+ })
2043
+ );
2044
+ return { common, callId, sessionId };
2045
+ }
2046
+ function batonWrap(nameRef, original, ctx) {
2047
+ return async (...callArgs) => {
2048
+ const toolName = nameRef.current;
2049
+ const slot = callSlots.getStore();
2050
+ if (slot) slot.innerFired = true;
2051
+ const extra = callArgs[callArgs.length - 1];
2052
+ const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2053
+ const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);
2054
+ const terminate = async (build, replacement) => {
2055
+ if (!slot) {
2056
+ await emit(ctx.sink, build);
2057
+ return;
2058
+ }
2059
+ const earlier = slot.flushTerminal;
2060
+ if (earlier !== null) await earlier(CLEAN_OUTCOME);
2061
+ slot.flushTerminal = async (outcome) => {
2062
+ await emit(
2063
+ ctx.sink,
2064
+ () => replacement !== null && outcome.failed ? replacement(outcome) : build()
2065
+ );
2066
+ };
2067
+ };
2068
+ const parkFailure = (build) => terminate(build, null);
2069
+ const parkSuccess = (build, replacement) => terminate(build, replacement);
1767
2070
  const startedAt = performance.now();
1768
2071
  let result;
1769
2072
  try {
1770
2073
  result = await original(...callArgs);
1771
2074
  } catch (err) {
1772
2075
  const durationMs2 = Math.round(performance.now() - startedAt);
1773
- const message = err instanceof Error ? err.message : String(err);
1774
- await emit(
1775
- ctx.sink,
2076
+ await parkFailure(
1776
2077
  () => ToolCallErrorEventSchema.parse({
1777
2078
  ...common,
1778
2079
  call_id: callId,
@@ -1780,17 +2081,26 @@ function batonWrap(nameRef, original, ctx) {
1780
2081
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1781
2082
  payload: {
1782
2083
  tool_name: toolName,
1783
- error_type: err instanceof Error ? err.constructor.name : "Error",
1784
- error_body: errorBody(ctx, message),
2084
+ error_type: errorTypeOf(err),
2085
+ // ⚠ KEPT under `resultCaptureMode: "off"`, and that is the rule's
2086
+ // shape rather than an exception to it: the rule is keyed on
2087
+ // PROVENANCE, and a thrown error's message is the vendor's own
2088
+ // code speaking about a call that returned nothing (SPEC
2089
+ // §11.4.3(1)). A switch written as "drop `error_body`" would
2090
+ // delete the highest-value diagnostic the product has.
2091
+ error_body: errorBody(ctx, messageOf(err)),
1785
2092
  duration_ms: durationMs2,
1786
2093
  // Explicit, though the field is `.optional()` and this is its
1787
2094
  // absent value. The schema is deliberately not an emitter (see
1788
2095
  // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1789
- // key would be missing — and Python's `tool_call_error` vector
1790
- // carries `result: null`, so the cross-SDK key-set check in
1791
- // `emitterConformance.test.ts` is what would say so. Each of the
1792
- // two failure shapes declares which it is, the same reason
1793
- // Python's emitter made the parameter positional-without-default.
2096
+ // key would be missing. Each of the two failure shapes declares
2097
+ // which it is, the same reason Python's emitter made the parameter
2098
+ // positional-without-default.
2099
+ //
2100
+ // ⚠ Guarded by `errorResult.test.ts`'s `toContain("result")`, NOT by
2101
+ // the cross-SDK key-set check — measured by removing this line. Why,
2102
+ // at one site: `endResultFields` in `errorResult.ts`. SPEC §11.4.3
2103
+ // states the same void rationale and wants the same amendment.
1794
2104
  result: null
1795
2105
  }
1796
2106
  })
@@ -1799,8 +2109,7 @@ function batonWrap(nameRef, original, ctx) {
1799
2109
  }
1800
2110
  const durationMs = Math.round(performance.now() - startedAt);
1801
2111
  if (isErrorResult(result)) {
1802
- await emit(
1803
- ctx.sink,
2112
+ await parkFailure(
1804
2113
  () => ToolCallErrorEventSchema.parse({
1805
2114
  ...common,
1806
2115
  call_id: callId,
@@ -1809,36 +2118,105 @@ function batonWrap(nameRef, original, ctx) {
1809
2118
  payload: {
1810
2119
  tool_name: toolName,
1811
2120
  error_type: TOOL_ERROR_TYPE,
1812
- error_body: errorBody(ctx, errorText(result)),
1813
2121
  duration_ms: durationMs,
1814
- // The whole envelope. ⚠ On this producer that is the same shape
1815
- // `tool_call_end.result` records, which is NOT what Python's
1816
- // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1817
- // holds that claim and names the test that enforces it.
1818
- result: ctx.scrubber(result)
2122
+ // Both remaining members are unwrapped FROM the result on this
2123
+ // shape, so one projection decides them together and owns the
2124
+ // scrubber call. `error_type` is NOT result-derived and is passed
2125
+ // regardless: the call still failed (SPEC §11.2.6).
2126
+ //
2127
+ // ⚠ Under `"full"` `result` is the whole envelope, and on this
2128
+ // producer that is the same shape `tool_call_end.result` records —
2129
+ // which is NOT what Python's contrast says.
2130
+ // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
2131
+ // names the test that enforces it.
2132
+ ...returnedErrorFields(
2133
+ ctx.resultCaptureMode,
2134
+ result,
2135
+ (text) => errorBody(ctx, text),
2136
+ ctx.scrubber
2137
+ )
1819
2138
  }
1820
2139
  })
1821
2140
  );
1822
2141
  return result;
1823
2142
  }
1824
- await emit(
1825
- ctx.sink,
2143
+ await parkSuccess(
1826
2144
  () => ToolCallEndEventSchema.parse({
1827
2145
  ...common,
1828
2146
  call_id: callId,
1829
2147
  sequence_number: ctx.counter.next(sessionId),
1830
2148
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1831
- payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
2149
+ payload: {
2150
+ tool_name: toolName,
2151
+ duration_ms: durationMs,
2152
+ ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
2153
+ }
2154
+ }),
2155
+ // The handler returned something this sensor reads as a success, and
2156
+ // then the outer seam saw the call fail anyway — so what failed is the
2157
+ // producer's own conversion of the output (SPEC §11.4.3's
2158
+ // `output_schema_mismatch`). Correcting this is the whole point of the
2159
+ // second seam: without it this is a `tool_call_end` for a call the
2160
+ // CALLER saw fail, which is a success the product invented.
2161
+ (outcome) => ToolCallErrorEventSchema.parse({
2162
+ ...common,
2163
+ call_id: callId,
2164
+ sequence_number: ctx.counter.next(sessionId),
2165
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2166
+ payload: {
2167
+ tool_name: toolName,
2168
+ // The lane the OUTER came back on, not this one's: on 2.x the
2169
+ // conversion failure is converted to a returned `isError` inside
2170
+ // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2171
+ // right there. A throw out of the handler is unreachable on
2172
+ // either major today for this lane; spelled anyway, because the
2173
+ // alternative is a crash on the day it stops being.
2174
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2175
+ // ⚠ The INNER's measurement — the vendor's handler duration —
2176
+ // not the outer's. Every other leg means the same thing by this
2177
+ // member, and widening it here for one failure kind would make
2178
+ // `duration_ms` mean two things in one column.
2179
+ duration_ms: durationMs,
2180
+ failure_kind: OUTPUT_SCHEMA_MISMATCH,
2181
+ // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2182
+ // kinds.** The message quotes the value the tool returned
2183
+ // ("`'not-an-int'` is not of type `integer`"), so it is
2184
+ // result-derived by provenance and goes — which leaves
2185
+ // `failure_kind` as the ONLY surviving signal for this failure
2186
+ // under `"off"`, and is the measurement that justified putting
2187
+ // the member on the wire at all.
2188
+ //
2189
+ // ⚠ `result` is what the CLIENT received — the SDK's own error
2190
+ // envelope — not the vendor's rejected return value. §11.4.3
2191
+ // asks for the envelope that holds the flag and the reason, and
2192
+ // this package's own invariant is that it agrees with the
2193
+ // caller. Recording the rejected output TOO would need a member
2194
+ // nothing on the wire has; the loss is deliberate and worth
2195
+ // knowing when debugging one of these.
2196
+ ...resultDerivedFields(
2197
+ ctx.resultCaptureMode,
2198
+ () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2199
+ // ⚠ `null` on the `raised` lane, never `undefined`, and the
2200
+ // union is what forces the branch rather than a comment: the
2201
+ // scrubber would answer `undefined` and DROP the key, where the
2202
+ // sibling raise lane a few lines up declares `result: null`
2203
+ // explicitly, for the reason `ToolCallErrorPayloadSchema`
2204
+ // records. One shape for "no result object existed", not two.
2205
+ outcome.raised ? null : outcome.result ?? null,
2206
+ (text) => errorBody(ctx, text),
2207
+ ctx.scrubber
2208
+ )
2209
+ }
1832
2210
  })
1833
2211
  );
1834
2212
  return result;
1835
2213
  };
1836
2214
  }
1837
- function extractGoalParam(args, paramName, toolName, dispositions) {
2215
+ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
1838
2216
  if (!(paramName in args)) return null;
1839
2217
  const disposition = dispositions ? dispositions[paramName] : void 0;
1840
2218
  if (disposition === "native") return null;
1841
- if (disposition === void 0) {
2219
+ if (disposition === void 0 && registered) {
1842
2220
  process.stderr.write(
1843
2221
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
1844
2222
  `
@@ -1897,12 +2275,29 @@ function captureAndInject(name, entry, ctx) {
1897
2275
  }
1898
2276
  var TOOLS_LIST_METHOD = "tools/list";
1899
2277
  var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
1900
- function installToolsListSeam(lowLevel, ctx) {
2278
+ var TOOLS_CALL_METHOD = "tools/call";
2279
+ var TOOLS_CALL_SEAM = /* @__PURE__ */ Symbol("batonToolsCallSeam");
2280
+ function installRequestSeam(lowLevel, method, seamTag, wrap) {
1901
2281
  const table = lowLevel._requestHandlers;
1902
2282
  const originalSet = lowLevel.setRequestHandler;
1903
2283
  if (!(table instanceof Map) || typeof originalSet !== "function") return;
1904
2284
  const handlers = table;
1905
2285
  const setRequestHandler = originalSet;
2286
+ const wrapCurrent = () => {
2287
+ const handler = handlers.get(method);
2288
+ if (typeof handler !== "function" || handler[seamTag]) return;
2289
+ const seamed = wrap(handler);
2290
+ seamed[seamTag] = true;
2291
+ handlers.set(method, seamed);
2292
+ };
2293
+ wrapCurrent();
2294
+ lowLevel.setRequestHandler = (...args) => {
2295
+ const registered = setRequestHandler.apply(lowLevel, args);
2296
+ wrapCurrent();
2297
+ return registered;
2298
+ };
2299
+ }
2300
+ function installToolsListSeam(lowLevel, ctx) {
1906
2301
  const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
1907
2302
  const advertise = (result) => {
1908
2303
  try {
@@ -1915,22 +2310,273 @@ function installToolsListSeam(lowLevel, ctx) {
1915
2310
  return result;
1916
2311
  }
1917
2312
  };
1918
- const wrapCurrent = () => {
1919
- const handler = handlers.get(TOOLS_LIST_METHOD);
1920
- if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
1921
- const seamed = (...args) => {
1922
- const out = handler(...args);
1923
- return isThenable(out) ? out.then(advertise) : advertise(out);
2313
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {
2314
+ const out = handler(...args);
2315
+ return isThenable(out) ? out.then(advertise) : advertise(out);
2316
+ });
2317
+ }
2318
+ var LIFECYCLE_SEAMS = {
2319
+ resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2320
+ resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2321
+ promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2322
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2323
+ };
2324
+ function installLifecycleSeam(lowLevel, ctx, spec) {
2325
+ installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
2326
+ const request = args[0];
2327
+ const requestParams = request?.params ?? {};
2328
+ const extra = args[1];
2329
+ const opened = await openLifecycleCall(ctx, spec, requestParams, extra);
2330
+ const fire = async (schema, payload) => {
2331
+ if (opened === null) return;
2332
+ await emit(
2333
+ ctx.sink,
2334
+ () => schema.parse({
2335
+ ...opened.common,
2336
+ sequence_number: ctx.counter.next(opened.sessionId),
2337
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2338
+ payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
2339
+ })
2340
+ );
1924
2341
  };
1925
- seamed[TOOLS_LIST_SEAM] = true;
1926
- handlers.set(TOOLS_LIST_METHOD, seamed);
1927
- };
1928
- wrapCurrent();
1929
- lowLevel.setRequestHandler = (...args) => {
1930
- const registered = setRequestHandler.apply(lowLevel, args);
1931
- wrapCurrent();
1932
- return registered;
1933
- };
2342
+ await fire(spec.schemas.start, spec.startParams(requestParams));
2343
+ const startedAt = performance.now();
2344
+ const elapsed = () => Math.round(performance.now() - startedAt);
2345
+ try {
2346
+ const result = await handler(...args);
2347
+ await fire(spec.schemas.end, {
2348
+ ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
2349
+ duration_ms: elapsed()
2350
+ });
2351
+ return result;
2352
+ } catch (err) {
2353
+ await fire(spec.schemas.error, {
2354
+ error_type: errorTypeOf(err),
2355
+ // KEPT under every capture mode: a failed FETCH's message is the
2356
+ // producer's own diagnostic, not anything a resource returned, so
2357
+ // nothing here is result-derived (SPEC §11.4.4). The scrub and the cap
2358
+ // are `scrubLifecyclePayload`'s, in that order.
2359
+ error_body: messageOf(err),
2360
+ duration_ms: elapsed()
2361
+ });
2362
+ throw err;
2363
+ }
2364
+ });
2365
+ }
2366
+ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2367
+ try {
2368
+ const parts = await resolveEnvelopeParts(ctx, extra);
2369
+ return {
2370
+ sessionId: parts.sessionId,
2371
+ subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
2372
+ common: {
2373
+ tenant_id: ctx.tenantId,
2374
+ vendor_id: ctx.vendorId,
2375
+ session_id: parts.sessionId,
2376
+ consent_token: ctx.consentToken,
2377
+ agent_runtime: parts.runtime,
2378
+ transport_observed: observeTransport(extra),
2379
+ runtime_meta: parts.scrubbedMeta
2380
+ }
2381
+ };
2382
+ } catch (err) {
2383
+ process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
2384
+ `);
2385
+ return null;
2386
+ }
2387
+ }
2388
+ var NO_PARAMS = () => EMPTY_PARAMS;
2389
+ var EMPTY_PARAMS = Object.freeze({});
2390
+ var LIFECYCLE_SPECS = [
2391
+ {
2392
+ method: "resources/list",
2393
+ seamTag: LIFECYCLE_SEAMS.resourceList,
2394
+ schemas: {
2395
+ start: ResourceListStartEventSchema,
2396
+ end: ResourceListEndEventSchema,
2397
+ error: ResourceListErrorEventSchema
2398
+ },
2399
+ // ⚠ `resources` ALONE. Resource TEMPLATES are a separate MCP method with
2400
+ // their own result array and are deliberately not added in, matching the
2401
+ // proxy — so a template-only server reports 0, which §11.4.4 says a
2402
+ // consumer MUST NOT read as "this server has no resources".
2403
+ countKey: "resources",
2404
+ startParams: NO_PARAMS
2405
+ },
2406
+ {
2407
+ method: "resources/read",
2408
+ seamTag: LIFECYCLE_SEAMS.resourceRead,
2409
+ schemas: {
2410
+ start: ResourceReadStartEventSchema,
2411
+ end: ResourceReadEndEventSchema,
2412
+ error: ResourceReadErrorEventSchema
2413
+ },
2414
+ subjectKey: "uri",
2415
+ // ⚠ The whole params bag MINUS `_meta`, so `uri` lands here as well as in
2416
+ // its own member. That duplication is the proxy's and is reproduced on
2417
+ // purpose: the dedicated member is what a consumer reads, the bag is what
2418
+ // the caller actually sent, and a producer that stripped `uri` out could no
2419
+ // longer say the second thing. `_meta` is excluded because it rides the
2420
+ // envelope as `runtime_meta` already.
2421
+ startParams: (params) => ({ params: paramsBag(params) })
2422
+ },
2423
+ {
2424
+ method: "prompts/list",
2425
+ seamTag: LIFECYCLE_SEAMS.promptList,
2426
+ schemas: {
2427
+ start: PromptListStartEventSchema,
2428
+ end: PromptListEndEventSchema,
2429
+ error: PromptListErrorEventSchema
2430
+ },
2431
+ countKey: "prompts",
2432
+ startParams: NO_PARAMS
2433
+ },
2434
+ {
2435
+ method: "prompts/get",
2436
+ seamTag: LIFECYCLE_SEAMS.promptGet,
2437
+ schemas: {
2438
+ start: PromptGetStartEventSchema,
2439
+ end: PromptGetEndEventSchema,
2440
+ error: PromptGetErrorEventSchema
2441
+ },
2442
+ subjectKey: "name",
2443
+ // ⚠ `arguments` ALONE, NOT the whole bag — the opposite of the resource
2444
+ // read above, so `name` does NOT appear inside `params`. The two are
2445
+ // inconsistent in the producer the shapes came from; the inconsistency is
2446
+ // reproduced rather than tidied, because a consumer reading one producer
2447
+ // and a second producer reading the other must agree.
2448
+ startParams: (params) => ({
2449
+ params: paramsBag(params["arguments"])
2450
+ })
2451
+ }
2452
+ ];
2453
+ function installLifecycleSeams(lowLevel, ctx) {
2454
+ for (const spec of LIFECYCLE_SPECS) installLifecycleSeam(lowLevel, ctx, spec);
2455
+ }
2456
+ function stringSubject(value) {
2457
+ return typeof value === "string" ? value : "";
2458
+ }
2459
+ function countOf(result, key) {
2460
+ const list = result?.[key];
2461
+ return Array.isArray(list) ? list.length : 0;
2462
+ }
2463
+ function paramsBag(bag) {
2464
+ if (!bag || typeof bag !== "object") return {};
2465
+ const out = {};
2466
+ for (const key of Object.keys(bag)) {
2467
+ if (key !== "_meta") out[key] = bag[key];
2468
+ }
2469
+ return out;
2470
+ }
2471
+ function scrubLifecyclePayload(ctx, raw) {
2472
+ const scrubbed = ctx.scrubber(raw);
2473
+ const body = scrubbed?.["error_body"];
2474
+ if (typeof body !== "string") return scrubbed;
2475
+ return { ...scrubbed, error_body: capCodePoints(body, ERROR_BODY_MAX_CODE_POINTS) };
2476
+ }
2477
+ function dispatchSlot(entry) {
2478
+ if (typeof entry.executor === "function") return "executor";
2479
+ if (typeof entry.handler === "function") return "handler";
2480
+ return void 0;
2481
+ }
2482
+ function dispatchTarget(entry) {
2483
+ const slot = dispatchSlot(entry);
2484
+ return slot === void 0 ? void 0 : entry[slot];
2485
+ }
2486
+ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2487
+ installRequestSeam(
2488
+ lowLevel,
2489
+ TOOLS_CALL_METHOD,
2490
+ TOOLS_CALL_SEAM,
2491
+ (handler) => async (...args) => {
2492
+ const slot = { innerFired: false, flushTerminal: null };
2493
+ let outcome = CLEAN_OUTCOME;
2494
+ try {
2495
+ const result = await callSlots.run(slot, () => handler(...args));
2496
+ outcome = { failed: isErrorResult(result), raised: false, result };
2497
+ return result;
2498
+ } catch (err) {
2499
+ outcome = { failed: true, raised: true, err };
2500
+ throw err;
2501
+ } finally {
2502
+ await settleCall(slot, outcome, args, toolEntry, ctx);
2503
+ }
2504
+ }
2505
+ );
2506
+ }
2507
+ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2508
+ try {
2509
+ if (slot.flushTerminal !== null) {
2510
+ const flush = slot.flushTerminal;
2511
+ slot.flushTerminal = null;
2512
+ await flush(outcome);
2513
+ return;
2514
+ }
2515
+ if (slot.innerFired) return;
2516
+ if (!outcome.failed) return;
2517
+ await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2518
+ } catch (err) {
2519
+ process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2520
+ `);
2521
+ }
2522
+ }
2523
+ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2524
+ const request = args[0];
2525
+ const toolName = request?.params?.name;
2526
+ if (typeof toolName !== "string") return;
2527
+ if (toolName === ctx.annotationToolName) return;
2528
+ const entry = toolEntry(toolName);
2529
+ if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2530
+ const params = { ...request?.params?.arguments ?? {} };
2531
+ const { common, callId, sessionId } = await openCall(
2532
+ ctx,
2533
+ toolName,
2534
+ args[1],
2535
+ params,
2536
+ entry != null
2537
+ );
2538
+ const failureKind = requestSideFailureKind(entry);
2539
+ await emit(
2540
+ ctx.sink,
2541
+ () => ToolCallErrorEventSchema.parse({
2542
+ ...common,
2543
+ call_id: callId,
2544
+ sequence_number: ctx.counter.next(sessionId),
2545
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2546
+ payload: {
2547
+ tool_name: toolName,
2548
+ // The lane the SDK rejected on, which is NOT the same across majors
2549
+ // for one failure: 1.x converts all three to a returned `isError`
2550
+ // inside its own `try` (`mcp.js:101-108`), v2 THROWS the first two
2551
+ // and returns the third. So the same customer-visible failure is
2552
+ // `"tool_error"` on one major and `"ProtocolError"` on the other —
2553
+ // measured 2026-10-01, and deliberately not special-cased: this
2554
+ // member is §11.4.3's RAISE/RETURN discriminator and it is reporting
2555
+ // the shape faithfully. `failure_kind` is what makes the two
2556
+ // comparable, which is the member's whole justification.
2557
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2558
+ // ⚠ `null`, not 0. The vendor's handler never ran, so there is no
2559
+ // handler duration to report; the time this call did spend was spent
2560
+ // in the SDK's validator, which is not what any other event means by
2561
+ // this member. §11.4 types it nullable for cases like this one.
2562
+ duration_ms: null,
2563
+ // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
2564
+ // `.optional()` accepts `undefined` and keeps the KEY in its output,
2565
+ // so the plain form writes a present-but-undefined member — invisible
2566
+ // to a JSON-serialising sink and plainly visible to a vendor-supplied
2567
+ // one that iterates keys. SPEC §11.4.3 says a producer that cannot
2568
+ // determine the kind MUST OMIT the member, and omitting is what this
2569
+ // spells.
2570
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
2571
+ // KEPT under `"off"` — see `requestSideErrorFields`, which takes no
2572
+ // capture mode because nothing here is derived from a result.
2573
+ ...requestSideErrorFields(
2574
+ outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2575
+ (text) => errorBody(ctx, text)
2576
+ )
2577
+ }
2578
+ })
2579
+ );
1934
2580
  }
1935
2581
  function isThenable(value) {
1936
2582
  return typeof value?.then === "function";
@@ -1938,20 +2584,13 @@ function isThenable(value) {
1938
2584
  function wrapIfNeeded(nameRef, entry, ctx) {
1939
2585
  if (!entry || typeof entry !== "object") return;
1940
2586
  const mutable = entry;
1941
- if (typeof mutable.executor === "function") {
1942
- if (mutable.executor[BATON_WRAPPED]) return;
1943
- const originalExecutor = mutable.executor;
1944
- const wrapper2 = batonWrap(nameRef, originalExecutor, ctx);
1945
- wrapper2[BATON_WRAPPED] = true;
1946
- mutable.executor = wrapper2;
1947
- return;
1948
- }
1949
- if (typeof mutable.handler !== "function") return;
1950
- if (mutable.handler[BATON_WRAPPED]) return;
1951
- const original = mutable.handler;
1952
- const wrapper = batonWrap(nameRef, original, ctx);
2587
+ const slot = dispatchSlot(mutable);
2588
+ if (slot === void 0) return;
2589
+ const target = mutable[slot];
2590
+ if (target[BATON_WRAPPED]) return;
2591
+ const wrapper = batonWrap(nameRef, target, ctx);
1953
2592
  wrapper[BATON_WRAPPED] = true;
1954
- mutable.handler = wrapper;
2593
+ mutable[slot] = wrapper;
1955
2594
  }
1956
2595
  function wireEntry(name, entry, ctx) {
1957
2596
  if (name === ctx.annotationToolName) return;
@@ -2106,6 +2745,7 @@ function withBaton(server, supplied = {}) {
2106
2745
  scrubber,
2107
2746
  annotationToolName,
2108
2747
  intentParamMode,
2748
+ resultCaptureMode: config.resultCaptureMode ?? "full",
2109
2749
  paramRegistry: /* @__PURE__ */ new Map(),
2110
2750
  resolvePrincipal: config.resolvePrincipal,
2111
2751
  principalIdMode: config.principalIdMode ?? "hashed",
@@ -2123,6 +2763,22 @@ function withBaton(server, supplied = {}) {
2123
2763
  });
2124
2764
  internals.server._instructions = instructions;
2125
2765
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
2766
+ installToolsCallSeam(
2767
+ internals.server,
2768
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
2769
+ // object, so `registry["constructor"]` answers `Object` and
2770
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
2771
+ // so the "a tool we did not wrap" guard would decline to report, and a
2772
+ // caller-visible `Tool constructor disabled` would reach the client with
2773
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
2774
+ // exactly the kind of failure the seam exists to make visible.
2775
+ (name) => {
2776
+ const registry = internals._registeredTools;
2777
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
2778
+ },
2779
+ ctx
2780
+ );
2781
+ installLifecycleSeams(internals.server, ctx);
2126
2782
  const resolvedAnnotationToolName = registerAnnotationTool(server, {
2127
2783
  sink,
2128
2784
  counter: ctx.counter,
@@ -2180,6 +2836,30 @@ function withBaton(server, supplied = {}) {
2180
2836
  PRINCIPAL_FORM_RAW,
2181
2837
  PRINCIPAL_SOURCE_ASSERTED,
2182
2838
  PrincipalWireSchema,
2839
+ PromptGetEndEventSchema,
2840
+ PromptGetEndPayloadSchema,
2841
+ PromptGetErrorEventSchema,
2842
+ PromptGetErrorPayloadSchema,
2843
+ PromptGetStartEventSchema,
2844
+ PromptGetStartPayloadSchema,
2845
+ PromptListEndEventSchema,
2846
+ PromptListEndPayloadSchema,
2847
+ PromptListErrorEventSchema,
2848
+ PromptListErrorPayloadSchema,
2849
+ PromptListStartEventSchema,
2850
+ PromptListStartPayloadSchema,
2851
+ ResourceListEndEventSchema,
2852
+ ResourceListEndPayloadSchema,
2853
+ ResourceListErrorEventSchema,
2854
+ ResourceListErrorPayloadSchema,
2855
+ ResourceListStartEventSchema,
2856
+ ResourceListStartPayloadSchema,
2857
+ ResourceReadEndEventSchema,
2858
+ ResourceReadEndPayloadSchema,
2859
+ ResourceReadErrorEventSchema,
2860
+ ResourceReadErrorPayloadSchema,
2861
+ ResourceReadStartEventSchema,
2862
+ ResourceReadStartPayloadSchema,
2183
2863
  SDK_VERSION,
2184
2864
  Scrubber,
2185
2865
  StdoutSink,