@goodtiming/baton-sdk 0.4.0 → 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
@@ -37,12 +37,35 @@ __export(index_exports, {
37
37
  DEPTH_LIMIT: () => DEPTH_LIMIT,
38
38
  EventSchema: () => EventSchema,
39
39
  EventTypeSchema: () => EventTypeSchema,
40
- HASH_SCHEME: () => HASH_SCHEME,
41
40
  HttpSink: () => HttpSink,
42
41
  PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
43
42
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
44
43
  PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
45
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,
46
69
  SDK_VERSION: () => SDK_VERSION,
47
70
  Scrubber: () => Scrubber,
48
71
  StdoutSink: () => StdoutSink,
@@ -62,7 +85,7 @@ __export(index_exports, {
62
85
  module.exports = __toCommonJS(index_exports);
63
86
 
64
87
  // src/version.ts
65
- var SDK_VERSION = "ts-0.4.0";
88
+ var SDK_VERSION = "ts-0.5.0";
66
89
 
67
90
  // src/events.ts
68
91
  var import_zod = require("zod");
@@ -78,7 +101,24 @@ var ToolCallStartPayloadSchema = import_zod.z.object({
78
101
  var ToolCallEndPayloadSchema = import_zod.z.object({
79
102
  tool_name: import_zod.z.string(),
80
103
  result: import_zod.z.unknown().nullable().default(null),
81
- 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()
82
122
  }).strict();
83
123
  var ToolCallErrorPayloadSchema = import_zod.z.object({
84
124
  tool_name: import_zod.z.string(),
@@ -100,7 +140,28 @@ var ToolCallErrorPayloadSchema = import_zod.z.object({
100
140
  // silent when it does not. What makes the EMITTED shape complete is the
101
141
  // emitter declaring `result` on both failure legs (`withBaton.ts`),
102
142
  // explicitly `null` on a throw — not the schema filling it in.
103
- 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()
104
165
  }).strict();
105
166
  var AnnotationPayloadSchema = import_zod.z.object({
106
167
  intent: import_zod.z.string().nullable().default(null),
@@ -146,8 +207,75 @@ var EventTypeSchema = import_zod.z.enum([
146
207
  "tool_call_end",
147
208
  "tool_call_error",
148
209
  "annotation",
149
- "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"
150
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();
151
279
  var ToolCallStartEventSchema = import_zod.z.object({
152
280
  ...envelopeShape,
153
281
  event_type: import_zod.z.literal("tool_call_start").default("tool_call_start"),
@@ -173,12 +301,84 @@ var SurfaceSnapshotEventSchema = import_zod.z.object({
173
301
  event_type: import_zod.z.literal("surface_snapshot").default("surface_snapshot"),
174
302
  payload: SurfaceSnapshotPayloadSchema
175
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();
176
364
  var EventSchema = import_zod.z.discriminatedUnion("event_type", [
177
365
  ToolCallStartEventSchema,
178
366
  ToolCallEndEventSchema,
179
367
  ToolCallErrorEventSchema,
180
368
  AnnotationEventSchema,
181
- 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
182
382
  ]);
183
383
 
184
384
  // src/scrub.ts
@@ -473,6 +673,7 @@ var HttpSink = class _HttpSink {
473
673
  };
474
674
 
475
675
  // src/integrations/mcp/withBaton.ts
676
+ var import_node_async_hooks = require("async_hooks");
476
677
  var import_uuid2 = require("uuid");
477
678
 
478
679
  // src/integrations/mcp/annotation.ts
@@ -533,7 +734,6 @@ function capCodePoints(value, max) {
533
734
  }
534
735
 
535
736
  // src/identity.ts
536
- var HASH_SCHEME = "h1";
537
737
  var PRINCIPAL_SOURCE_ASSERTED = "asserted";
538
738
  var PRINCIPAL_FORM_HASHED = "hashed";
539
739
  var PRINCIPAL_FORM_RAW = "raw";
@@ -557,14 +757,13 @@ function pythonStrip(value) {
557
757
  return value.replace(PYTHON_STRIP, "");
558
758
  }
559
759
  function hashPrincipalId(rawPrincipal, options) {
560
- const { tenantId, key, issuer = null, scheme = HASH_SCHEME } = options;
760
+ const { tenantId, key, issuer = null } = options;
561
761
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
562
762
  if (issuer !== null) {
563
763
  message += `\0${canonicalize(issuer)}`;
564
764
  }
565
765
  const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
566
- const digest = (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
567
- return `${scheme}:${digest}`;
766
+ return (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
568
767
  }
569
768
  function normalizePrincipal(result) {
570
769
  if (result === null || typeof result !== "object") return null;
@@ -840,6 +1039,24 @@ async function resolveCallPrincipal(hook, call, options) {
840
1039
  }
841
1040
  }
842
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
+
843
1060
  // src/integrations/mcp/runtimeAdapter.ts
844
1061
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
845
1062
  var CLIENT_NAME_MAX_LEN = 128;
@@ -848,7 +1065,7 @@ function clean(name, scrubber) {
848
1065
  if (typeof name !== "string" || !name) return null;
849
1066
  let cleaned = name;
850
1067
  if (scrubber) {
851
- const scrubbed = scrubber(cleaned);
1068
+ const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
852
1069
  if (typeof scrubbed !== "string") return null;
853
1070
  cleaned = scrubbed;
854
1071
  }
@@ -924,7 +1141,11 @@ function registerAnnotationTool(server, options) {
924
1141
  server,
925
1142
  scrubber: options.scrubber
926
1143
  }) ?? UNKNOWN_AGENT_RUNTIME;
927
- const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
1144
+ const scrubbedMeta = scrubOrNull(
1145
+ options.scrubber,
1146
+ meta ? roundMetaCoordinates(meta) : null,
1147
+ "_meta"
1148
+ );
928
1149
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
929
1150
  if (args.signal_type === void 0) {
930
1151
  options.tracker?.mark(sessionId);
@@ -955,6 +1176,7 @@ function registerAnnotationTool(server, options) {
955
1176
  // Agent-facing names -> wire keys, as with `overall_task`
956
1177
  // below: `user_goal` is stored as `intent`, `expected_result` as
957
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
958
1180
  intent: options.scrubber(args.user_goal),
959
1181
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
960
1182
  // `signal_type` is a closed enum — nothing to scrub. The task label
@@ -969,8 +1191,10 @@ function registerAnnotationTool(server, options) {
969
1191
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
970
1192
  // split the injected params use (`overall_task` -> `call_workflow`):
971
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
972
1195
  workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
973
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
974
1198
  context: args.context ? options.scrubber(args.context) : null
975
1199
  }
976
1200
  })
@@ -1185,8 +1409,68 @@ function sealKey(dsn) {
1185
1409
  return dsn;
1186
1410
  }
1187
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
+
1188
1471
  // src/integrations/mcp/config.ts
1189
1472
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1473
+ var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1190
1474
  var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1191
1475
  function resolveTenantId(explicit, vendorId) {
1192
1476
  if (explicit) return explicit;
@@ -1297,6 +1581,14 @@ function validateBatonConfig(config) {
1297
1581
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1298
1582
  );
1299
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
+ }
1300
1592
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1301
1593
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1302
1594
  }
@@ -1342,34 +1634,6 @@ var DisabledSink = class {
1342
1634
  }
1343
1635
  };
1344
1636
 
1345
- // src/integrations/mcp/errorResult.ts
1346
- var TOOL_ERROR_TYPE = "tool_error";
1347
- var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1348
- function isErrorResult(value) {
1349
- try {
1350
- if (typeof value !== "object" || value === null) return false;
1351
- return Boolean(value.isError);
1352
- } catch {
1353
- return false;
1354
- }
1355
- }
1356
- function errorText(value) {
1357
- const parts = [];
1358
- try {
1359
- const content = value?.content;
1360
- if (!Array.isArray(content)) return "";
1361
- for (const part of content) {
1362
- const text = part?.text;
1363
- if (typeof text !== "string") continue;
1364
- const trimmed = text.trim();
1365
- if (trimmed) parts.push(trimmed);
1366
- }
1367
- } catch {
1368
- return "";
1369
- }
1370
- return parts.join("\n");
1371
- }
1372
-
1373
1637
  // src/integrations/mcp/handle.ts
1374
1638
  var BatonHandle = class {
1375
1639
  sink;
@@ -1623,6 +1887,8 @@ function buildSeamAugmentations(options) {
1623
1887
  // src/integrations/mcp/withBaton.ts
1624
1888
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
1625
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();
1626
1892
  var SurfaceState = class {
1627
1893
  constructor(serverMeta) {
1628
1894
  this.serverMeta = serverMeta;
@@ -1677,105 +1943,137 @@ var SurfaceState = class {
1677
1943
  function errorBody(ctx, text) {
1678
1944
  return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1679
1945
  }
1680
- function batonWrap(nameRef, original, ctx) {
1681
- return async (...callArgs) => {
1682
- const toolName = nameRef.current;
1683
- await maybeEmitSurfaceSnapshot(ctx);
1684
- const extra = callArgs[callArgs.length - 1];
1685
- const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1686
- const meta = extraMeta(extra);
1687
- const runtime = detectAgentRuntime(meta, {
1688
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1689
- // `_meta`; 1.x leaves them in. Both are handed over — see
1690
- // `mcpTypes.extraEnvelope`.
1691
- envelope: extraEnvelope(extra),
1692
- // Tier 2's carrier: neither peer puts client identity on the
1693
- // handler context, both expose the cached handshake on the server.
1694
- server: ctx.server,
1695
- scrubber: ctx.scrubber
1696
- }) ?? UNKNOWN_AGENT_RUNTIME;
1697
- const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
1698
- const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1699
- const dispositions = ctx.paramRegistry.get(toolName);
1700
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1701
- const rawExpected = extractGoalParam(
1702
- params,
1703
- EXPECTED_RESULT_PARAM_NAME,
1704
- toolName,
1705
- dispositions
1706
- );
1707
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);
1708
- const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1709
- const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1710
- const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1711
- const callId = (0, import_uuid2.v7)();
1712
- const principal = await resolveCallPrincipal(
1713
- ctx.resolvePrincipal,
1714
- { extra, toolName, arguments: params },
1715
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1716
- );
1717
- const common = {
1718
- tenant_id: ctx.tenantId,
1719
- vendor_id: ctx.vendorId,
1720
- session_id: sessionId,
1721
- consent_token: ctx.consentToken,
1722
- agent_runtime: runtime,
1723
- // The five `...common` sites below are the tool-call legs — start, end,
1724
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1725
- // annotation, the same five Python stamps (`middleware.py`
1726
- // 503/547/586/644/674; it was four until the returned shape landed
1727
- // there too). `surface_snapshot` is deliberately NOT among them: it
1728
- // describes the SERVER and is captured outside any call, so there is no
1729
- // caller to name (register D5).
1730
- principal,
1731
- // Same five stamps, same exclusion: a surface_snapshot describes the
1732
- // SERVER and is captured outside any call, so it has no caller's
1733
- // transport to name any more than it has a caller to name.
1734
- transport_observed: observeTransport(extra),
1735
- runtime_meta: scrubbedMeta
1736
- };
1737
- if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1738
- await emit(
1739
- ctx.sink,
1740
- () => AnnotationEventSchema.parse({
1741
- ...common,
1742
- sequence_number: ctx.counter.next(sessionId),
1743
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1744
- payload: {
1745
- intent: scrubbedIntent,
1746
- expected_outcome: scrubbedExpected,
1747
- intent_source: INTENT_SOURCE_PARAM,
1748
- tool_name: toolName
1749
- }
1750
- })
1751
- );
1752
- }
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)) {
1753
2011
  await emit(
1754
2012
  ctx.sink,
1755
- () => ToolCallStartEventSchema.parse({
2013
+ () => AnnotationEventSchema.parse({
1756
2014
  ...common,
1757
- call_id: callId,
1758
2015
  sequence_number: ctx.counter.next(sessionId),
1759
2016
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1760
2017
  payload: {
1761
- tool_name: toolName,
1762
- params: ctx.scrubber(params),
1763
- call_intent: scrubbedIntent,
1764
- call_expected: scrubbedExpected,
1765
- call_workflow: scrubbedWorkflow,
1766
- 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
1767
2022
  }
1768
2023
  })
1769
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);
1770
2070
  const startedAt = performance.now();
1771
2071
  let result;
1772
2072
  try {
1773
2073
  result = await original(...callArgs);
1774
2074
  } catch (err) {
1775
2075
  const durationMs2 = Math.round(performance.now() - startedAt);
1776
- const message = err instanceof Error ? err.message : String(err);
1777
- await emit(
1778
- ctx.sink,
2076
+ await parkFailure(
1779
2077
  () => ToolCallErrorEventSchema.parse({
1780
2078
  ...common,
1781
2079
  call_id: callId,
@@ -1783,17 +2081,26 @@ function batonWrap(nameRef, original, ctx) {
1783
2081
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1784
2082
  payload: {
1785
2083
  tool_name: toolName,
1786
- error_type: err instanceof Error ? err.constructor.name : "Error",
1787
- 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)),
1788
2092
  duration_ms: durationMs2,
1789
2093
  // Explicit, though the field is `.optional()` and this is its
1790
2094
  // absent value. The schema is deliberately not an emitter (see
1791
2095
  // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1792
- // key would be missing — and Python's `tool_call_error` vector
1793
- // carries `result: null`, so the cross-SDK key-set check in
1794
- // `emitterConformance.test.ts` is what would say so. Each of the
1795
- // two failure shapes declares which it is, the same reason
1796
- // 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.
1797
2104
  result: null
1798
2105
  }
1799
2106
  })
@@ -1802,8 +2109,7 @@ function batonWrap(nameRef, original, ctx) {
1802
2109
  }
1803
2110
  const durationMs = Math.round(performance.now() - startedAt);
1804
2111
  if (isErrorResult(result)) {
1805
- await emit(
1806
- ctx.sink,
2112
+ await parkFailure(
1807
2113
  () => ToolCallErrorEventSchema.parse({
1808
2114
  ...common,
1809
2115
  call_id: callId,
@@ -1812,36 +2118,105 @@ function batonWrap(nameRef, original, ctx) {
1812
2118
  payload: {
1813
2119
  tool_name: toolName,
1814
2120
  error_type: TOOL_ERROR_TYPE,
1815
- error_body: errorBody(ctx, errorText(result)),
1816
2121
  duration_ms: durationMs,
1817
- // The whole envelope. ⚠ On this producer that is the same shape
1818
- // `tool_call_end.result` records, which is NOT what Python's
1819
- // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1820
- // holds that claim and names the test that enforces it.
1821
- 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
+ )
1822
2138
  }
1823
2139
  })
1824
2140
  );
1825
2141
  return result;
1826
2142
  }
1827
- await emit(
1828
- ctx.sink,
2143
+ await parkSuccess(
1829
2144
  () => ToolCallEndEventSchema.parse({
1830
2145
  ...common,
1831
2146
  call_id: callId,
1832
2147
  sequence_number: ctx.counter.next(sessionId),
1833
2148
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1834
- 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
+ }
1835
2210
  })
1836
2211
  );
1837
2212
  return result;
1838
2213
  };
1839
2214
  }
1840
- function extractGoalParam(args, paramName, toolName, dispositions) {
2215
+ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
1841
2216
  if (!(paramName in args)) return null;
1842
2217
  const disposition = dispositions ? dispositions[paramName] : void 0;
1843
2218
  if (disposition === "native") return null;
1844
- if (disposition === void 0) {
2219
+ if (disposition === void 0 && registered) {
1845
2220
  process.stderr.write(
1846
2221
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
1847
2222
  `
@@ -1900,12 +2275,29 @@ function captureAndInject(name, entry, ctx) {
1900
2275
  }
1901
2276
  var TOOLS_LIST_METHOD = "tools/list";
1902
2277
  var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
1903
- 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) {
1904
2281
  const table = lowLevel._requestHandlers;
1905
2282
  const originalSet = lowLevel.setRequestHandler;
1906
2283
  if (!(table instanceof Map) || typeof originalSet !== "function") return;
1907
2284
  const handlers = table;
1908
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) {
1909
2301
  const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
1910
2302
  const advertise = (result) => {
1911
2303
  try {
@@ -1918,22 +2310,273 @@ function installToolsListSeam(lowLevel, ctx) {
1918
2310
  return result;
1919
2311
  }
1920
2312
  };
1921
- const wrapCurrent = () => {
1922
- const handler = handlers.get(TOOLS_LIST_METHOD);
1923
- if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
1924
- const seamed = (...args) => {
1925
- const out = handler(...args);
1926
- 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
+ );
1927
2341
  };
1928
- seamed[TOOLS_LIST_SEAM] = true;
1929
- handlers.set(TOOLS_LIST_METHOD, seamed);
1930
- };
1931
- wrapCurrent();
1932
- lowLevel.setRequestHandler = (...args) => {
1933
- const registered = setRequestHandler.apply(lowLevel, args);
1934
- wrapCurrent();
1935
- return registered;
1936
- };
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
+ );
1937
2580
  }
1938
2581
  function isThenable(value) {
1939
2582
  return typeof value?.then === "function";
@@ -1941,20 +2584,13 @@ function isThenable(value) {
1941
2584
  function wrapIfNeeded(nameRef, entry, ctx) {
1942
2585
  if (!entry || typeof entry !== "object") return;
1943
2586
  const mutable = entry;
1944
- if (typeof mutable.executor === "function") {
1945
- if (mutable.executor[BATON_WRAPPED]) return;
1946
- const originalExecutor = mutable.executor;
1947
- const wrapper2 = batonWrap(nameRef, originalExecutor, ctx);
1948
- wrapper2[BATON_WRAPPED] = true;
1949
- mutable.executor = wrapper2;
1950
- return;
1951
- }
1952
- if (typeof mutable.handler !== "function") return;
1953
- if (mutable.handler[BATON_WRAPPED]) return;
1954
- const original = mutable.handler;
1955
- 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);
1956
2592
  wrapper[BATON_WRAPPED] = true;
1957
- mutable.handler = wrapper;
2593
+ mutable[slot] = wrapper;
1958
2594
  }
1959
2595
  function wireEntry(name, entry, ctx) {
1960
2596
  if (name === ctx.annotationToolName) return;
@@ -2109,6 +2745,7 @@ function withBaton(server, supplied = {}) {
2109
2745
  scrubber,
2110
2746
  annotationToolName,
2111
2747
  intentParamMode,
2748
+ resultCaptureMode: config.resultCaptureMode ?? "full",
2112
2749
  paramRegistry: /* @__PURE__ */ new Map(),
2113
2750
  resolvePrincipal: config.resolvePrincipal,
2114
2751
  principalIdMode: config.principalIdMode ?? "hashed",
@@ -2126,6 +2763,22 @@ function withBaton(server, supplied = {}) {
2126
2763
  });
2127
2764
  internals.server._instructions = instructions;
2128
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);
2129
2782
  const resolvedAnnotationToolName = registerAnnotationTool(server, {
2130
2783
  sink,
2131
2784
  counter: ctx.counter,
@@ -2178,12 +2831,35 @@ function withBaton(server, supplied = {}) {
2178
2831
  DEPTH_LIMIT,
2179
2832
  EventSchema,
2180
2833
  EventTypeSchema,
2181
- HASH_SCHEME,
2182
2834
  HttpSink,
2183
2835
  PRINCIPAL_FORM_HASHED,
2184
2836
  PRINCIPAL_FORM_RAW,
2185
2837
  PRINCIPAL_SOURCE_ASSERTED,
2186
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,
2187
2863
  SDK_VERSION,
2188
2864
  Scrubber,
2189
2865
  StdoutSink,