@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.4.0";
2
+ var SDK_VERSION = "ts-0.5.0";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -15,7 +15,24 @@ var ToolCallStartPayloadSchema = z.object({
15
15
  var ToolCallEndPayloadSchema = z.object({
16
16
  tool_name: z.string(),
17
17
  result: z.unknown().nullable().default(null),
18
- duration_ms: z.number().int().nullable().default(null)
18
+ duration_ms: z.number().int().nullable().default(null),
19
+ // SPEC §11.4: the producer declares it WITHHELD result-derived data.
20
+ // Absent means CAPTURED, so no consumer needs a version table.
21
+ //
22
+ // `.optional()`, NOT `.default(null)`, for the reason recorded on
23
+ // `ToolCallErrorPayloadSchema.result` below: a default makes this reader
24
+ // an EMITTER, and parsing a stored event from before the member existed
25
+ // would hand back an invented key.
26
+ //
27
+ // ⚠ **This package OMITS the member when capturing, where the Python SDK
28
+ // sends `result_capture: null`.** Both are conformant and SPEC §11.4 says
29
+ // so outright — absent and null are equivalent, and a consumer MUST read
30
+ // the VALUE, never test for the key. It is the same axis `result` already
31
+ // differs on between `baton-sdk` (null) and `baton-proxy` (omitted), per
32
+ // §11.4.3. Omitting is chosen here because the alternative — matching
33
+ // Python — would require regenerating `baton-spec`'s vectors from an
34
+ // UNMERGED branch, pinning a key set no released producer emits.
35
+ result_capture: z.string().nullable().optional()
19
36
  }).strict();
20
37
  var ToolCallErrorPayloadSchema = z.object({
21
38
  tool_name: z.string(),
@@ -37,7 +54,28 @@ var ToolCallErrorPayloadSchema = z.object({
37
54
  // silent when it does not. What makes the EMITTED shape complete is the
38
55
  // emitter declaring `result` on both failure legs (`withBaton.ts`),
39
56
  // explicitly `null` on a throw — not the schema filling it in.
40
- result: z.unknown().nullable().optional()
57
+ result: z.unknown().nullable().optional(),
58
+ // SPEC §11.4, on BOTH payloads because the RETURN failure shape withholds
59
+ // `result` too. Same `.optional()` reasoning as the field above it, and
60
+ // same omit-when-capturing posture as `ToolCallEndPayloadSchema`.
61
+ result_capture: z.string().nullable().optional(),
62
+ // SPEC §11.4.3: the producer NAMES a failure it made above the vendor's
63
+ // handler. `tool_call_error` ONLY — unlike `result_capture`, which rides
64
+ // both payloads — because the one case that files `tool_call_end` today
65
+ // IS the false success this member exists to correct, so after the fix
66
+ // nothing carries it on a success payload.
67
+ //
68
+ // A plain `z.string()` and NOT `z.enum(FAILURE_KINDS)`, which SPEC
69
+ // requires rather than permits: a closed enum turns a later registered
70
+ // value into a `ValidationError` on the vendor's tool-call path, which
71
+ // §11.2 says must fail open. The registry in
72
+ // `integrations/mcp/errorResult.ts` constrains what this producer EMITS;
73
+ // it must not constrain what this schema READS.
74
+ //
75
+ // Same `.optional()`-not-`.default(null)` reasoning as the two fields
76
+ // above: a default makes the schema an emitter, and parsing a stored
77
+ // event from before the member existed would hand back an invented key.
78
+ failure_kind: z.string().nullable().optional()
41
79
  }).strict();
42
80
  var AnnotationPayloadSchema = z.object({
43
81
  intent: z.string().nullable().default(null),
@@ -83,8 +121,75 @@ var EventTypeSchema = z.enum([
83
121
  "tool_call_end",
84
122
  "tool_call_error",
85
123
  "annotation",
86
- "surface_snapshot"
124
+ "surface_snapshot",
125
+ // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
126
+ // shapes were set by `baton-proxy`, which has been emitting all of them in
127
+ // production — see the payload schemas below.
128
+ "resource_list_start",
129
+ "resource_list_end",
130
+ "resource_list_error",
131
+ "resource_read_start",
132
+ "resource_read_end",
133
+ "resource_read_error",
134
+ "prompt_list_start",
135
+ "prompt_list_end",
136
+ "prompt_list_error",
137
+ "prompt_get_start",
138
+ "prompt_get_end",
139
+ "prompt_get_error"
87
140
  ]);
141
+ var timingShape = { duration_ms: z.number().int().nullable().default(null) };
142
+ var failureShape = { error_type: z.string(), error_body: z.string(), ...timingShape };
143
+ var ResourceListStartPayloadSchema = z.object({}).strict();
144
+ var ResourceListEndPayloadSchema = z.object({
145
+ count: z.number().int(),
146
+ ...timingShape
147
+ }).strict();
148
+ var ResourceListErrorPayloadSchema = z.object({
149
+ ...failureShape
150
+ }).strict();
151
+ var ResourceReadStartPayloadSchema = z.object({
152
+ uri: z.string(),
153
+ /** The caller's own request params, PII-scrubbed (SPEC §7).
154
+ *
155
+ * ⚠ Nullable because the SCHEMA permits it, not because this producer
156
+ * emits it: `withBaton`'s `paramsBag` answers `{}` for an absent bag,
157
+ * matching `baton-proxy` (`dict(params) if params else {}` — it never
158
+ * emits null). A consumer must still read both, since the schema admits
159
+ * both and a third producer may choose either. */
160
+ params: z.record(z.string(), z.unknown()).nullable().default(null)
161
+ }).strict();
162
+ var ResourceReadEndPayloadSchema = z.object({
163
+ uri: z.string(),
164
+ ...timingShape
165
+ }).strict();
166
+ var ResourceReadErrorPayloadSchema = z.object({
167
+ uri: z.string(),
168
+ ...failureShape
169
+ }).strict();
170
+ var PromptListStartPayloadSchema = z.object({}).strict();
171
+ var PromptListEndPayloadSchema = z.object({
172
+ count: z.number().int(),
173
+ ...timingShape
174
+ }).strict();
175
+ var PromptListErrorPayloadSchema = z.object({
176
+ ...failureShape
177
+ }).strict();
178
+ var PromptGetStartPayloadSchema = z.object({
179
+ name: z.string(),
180
+ /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
181
+ * where the request supplied none — see `ResourceReadStartPayloadSchema`'s
182
+ * `params` for why the schema is nullable anyway. */
183
+ params: z.record(z.string(), z.unknown()).nullable().default(null)
184
+ }).strict();
185
+ var PromptGetEndPayloadSchema = z.object({
186
+ name: z.string(),
187
+ ...timingShape
188
+ }).strict();
189
+ var PromptGetErrorPayloadSchema = z.object({
190
+ name: z.string(),
191
+ ...failureShape
192
+ }).strict();
88
193
  var ToolCallStartEventSchema = z.object({
89
194
  ...envelopeShape,
90
195
  event_type: z.literal("tool_call_start").default("tool_call_start"),
@@ -110,12 +215,84 @@ var SurfaceSnapshotEventSchema = z.object({
110
215
  event_type: z.literal("surface_snapshot").default("surface_snapshot"),
111
216
  payload: SurfaceSnapshotPayloadSchema
112
217
  }).strict();
218
+ var ResourceListStartEventSchema = z.object({
219
+ ...envelopeShape,
220
+ event_type: z.literal("resource_list_start").default("resource_list_start"),
221
+ payload: ResourceListStartPayloadSchema
222
+ }).strict();
223
+ var ResourceListEndEventSchema = z.object({
224
+ ...envelopeShape,
225
+ event_type: z.literal("resource_list_end").default("resource_list_end"),
226
+ payload: ResourceListEndPayloadSchema
227
+ }).strict();
228
+ var ResourceListErrorEventSchema = z.object({
229
+ ...envelopeShape,
230
+ event_type: z.literal("resource_list_error").default("resource_list_error"),
231
+ payload: ResourceListErrorPayloadSchema
232
+ }).strict();
233
+ var ResourceReadStartEventSchema = z.object({
234
+ ...envelopeShape,
235
+ event_type: z.literal("resource_read_start").default("resource_read_start"),
236
+ payload: ResourceReadStartPayloadSchema
237
+ }).strict();
238
+ var ResourceReadEndEventSchema = z.object({
239
+ ...envelopeShape,
240
+ event_type: z.literal("resource_read_end").default("resource_read_end"),
241
+ payload: ResourceReadEndPayloadSchema
242
+ }).strict();
243
+ var ResourceReadErrorEventSchema = z.object({
244
+ ...envelopeShape,
245
+ event_type: z.literal("resource_read_error").default("resource_read_error"),
246
+ payload: ResourceReadErrorPayloadSchema
247
+ }).strict();
248
+ var PromptListStartEventSchema = z.object({
249
+ ...envelopeShape,
250
+ event_type: z.literal("prompt_list_start").default("prompt_list_start"),
251
+ payload: PromptListStartPayloadSchema
252
+ }).strict();
253
+ var PromptListEndEventSchema = z.object({
254
+ ...envelopeShape,
255
+ event_type: z.literal("prompt_list_end").default("prompt_list_end"),
256
+ payload: PromptListEndPayloadSchema
257
+ }).strict();
258
+ var PromptListErrorEventSchema = z.object({
259
+ ...envelopeShape,
260
+ event_type: z.literal("prompt_list_error").default("prompt_list_error"),
261
+ payload: PromptListErrorPayloadSchema
262
+ }).strict();
263
+ var PromptGetStartEventSchema = z.object({
264
+ ...envelopeShape,
265
+ event_type: z.literal("prompt_get_start").default("prompt_get_start"),
266
+ payload: PromptGetStartPayloadSchema
267
+ }).strict();
268
+ var PromptGetEndEventSchema = z.object({
269
+ ...envelopeShape,
270
+ event_type: z.literal("prompt_get_end").default("prompt_get_end"),
271
+ payload: PromptGetEndPayloadSchema
272
+ }).strict();
273
+ var PromptGetErrorEventSchema = z.object({
274
+ ...envelopeShape,
275
+ event_type: z.literal("prompt_get_error").default("prompt_get_error"),
276
+ payload: PromptGetErrorPayloadSchema
277
+ }).strict();
113
278
  var EventSchema = z.discriminatedUnion("event_type", [
114
279
  ToolCallStartEventSchema,
115
280
  ToolCallEndEventSchema,
116
281
  ToolCallErrorEventSchema,
117
282
  AnnotationEventSchema,
118
- SurfaceSnapshotEventSchema
283
+ SurfaceSnapshotEventSchema,
284
+ ResourceListStartEventSchema,
285
+ ResourceListEndEventSchema,
286
+ ResourceListErrorEventSchema,
287
+ ResourceReadStartEventSchema,
288
+ ResourceReadEndEventSchema,
289
+ ResourceReadErrorEventSchema,
290
+ PromptListStartEventSchema,
291
+ PromptListEndEventSchema,
292
+ PromptListErrorEventSchema,
293
+ PromptGetStartEventSchema,
294
+ PromptGetEndEventSchema,
295
+ PromptGetErrorEventSchema
119
296
  ]);
120
297
 
121
298
  // src/scrub.ts
@@ -410,6 +587,7 @@ var HttpSink = class _HttpSink {
410
587
  };
411
588
 
412
589
  // src/integrations/mcp/withBaton.ts
590
+ import { AsyncLocalStorage } from "async_hooks";
413
591
  import { v7 as uuidv72 } from "uuid";
414
592
 
415
593
  // src/integrations/mcp/annotation.ts
@@ -470,7 +648,6 @@ function capCodePoints(value, max) {
470
648
  }
471
649
 
472
650
  // src/identity.ts
473
- var HASH_SCHEME = "h1";
474
651
  var PRINCIPAL_SOURCE_ASSERTED = "asserted";
475
652
  var PRINCIPAL_FORM_HASHED = "hashed";
476
653
  var PRINCIPAL_FORM_RAW = "raw";
@@ -494,14 +671,13 @@ function pythonStrip(value) {
494
671
  return value.replace(PYTHON_STRIP, "");
495
672
  }
496
673
  function hashPrincipalId(rawPrincipal, options) {
497
- const { tenantId, key, issuer = null, scheme = HASH_SCHEME } = options;
674
+ const { tenantId, key, issuer = null } = options;
498
675
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
499
676
  if (issuer !== null) {
500
677
  message += `\0${canonicalize(issuer)}`;
501
678
  }
502
679
  const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
503
- const digest = createHmac("sha256", keyBytes).update(message, "utf8").digest("hex");
504
- return `${scheme}:${digest}`;
680
+ return createHmac("sha256", keyBytes).update(message, "utf8").digest("hex");
505
681
  }
506
682
  function normalizePrincipal(result) {
507
683
  if (result === null || typeof result !== "object") return null;
@@ -777,6 +953,24 @@ async function resolveCallPrincipal(hook, call, options) {
777
953
  }
778
954
  }
779
955
 
956
+ // src/integrations/mcp/safeScrub.ts
957
+ var warned = /* @__PURE__ */ new Set();
958
+ function scrubOrNull(scrubber, value, field) {
959
+ if (value === null) return null;
960
+ try {
961
+ return scrubber(value);
962
+ } catch (err) {
963
+ if (!warned.has(field)) {
964
+ warned.add(field);
965
+ process.stderr.write(
966
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${String(err)}
967
+ `
968
+ );
969
+ }
970
+ return null;
971
+ }
972
+ }
973
+
780
974
  // src/integrations/mcp/runtimeAdapter.ts
781
975
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
782
976
  var CLIENT_NAME_MAX_LEN = 128;
@@ -785,7 +979,7 @@ function clean(name, scrubber) {
785
979
  if (typeof name !== "string" || !name) return null;
786
980
  let cleaned = name;
787
981
  if (scrubber) {
788
- const scrubbed = scrubber(cleaned);
982
+ const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
789
983
  if (typeof scrubbed !== "string") return null;
790
984
  cleaned = scrubbed;
791
985
  }
@@ -861,7 +1055,11 @@ function registerAnnotationTool(server, options) {
861
1055
  server,
862
1056
  scrubber: options.scrubber
863
1057
  }) ?? UNKNOWN_AGENT_RUNTIME;
864
- const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
1058
+ const scrubbedMeta = scrubOrNull(
1059
+ options.scrubber,
1060
+ meta ? roundMetaCoordinates(meta) : null,
1061
+ "_meta"
1062
+ );
865
1063
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
866
1064
  if (args.signal_type === void 0) {
867
1065
  options.tracker?.mark(sessionId);
@@ -892,6 +1090,7 @@ function registerAnnotationTool(server, options) {
892
1090
  // Agent-facing names -> wire keys, as with `overall_task`
893
1091
  // below: `user_goal` is stored as `intent`, `expected_result` as
894
1092
  // `expected_outcome`.
1093
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
895
1094
  intent: options.scrubber(args.user_goal),
896
1095
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
897
1096
  // `signal_type` is a closed enum — nothing to scrub. The task label
@@ -906,8 +1105,10 @@ function registerAnnotationTool(server, options) {
906
1105
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
907
1106
  // split the injected params use (`overall_task` -> `call_workflow`):
908
1107
  // renaming the param must not move the key the console groups on.
1108
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
909
1109
  workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
910
1110
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1111
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
911
1112
  context: args.context ? options.scrubber(args.context) : null
912
1113
  }
913
1114
  })
@@ -1122,8 +1323,68 @@ function sealKey(dsn) {
1122
1323
  return dsn;
1123
1324
  }
1124
1325
 
1326
+ // src/integrations/mcp/errorResult.ts
1327
+ var TOOL_ERROR_TYPE = "tool_error";
1328
+ var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
1329
+ var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
1330
+ function requestSideFailureKind(entry) {
1331
+ if (entry == null) return "unknown_tool";
1332
+ if (entry.enabled === false) return "tool_disabled";
1333
+ return TASK_MODES.has(entry.execution?.taskSupport) ? void 0 : "invalid_argument";
1334
+ }
1335
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1336
+ function isErrorResult(value) {
1337
+ try {
1338
+ if (typeof value !== "object" || value === null) return false;
1339
+ return Boolean(value.isError);
1340
+ } catch {
1341
+ return false;
1342
+ }
1343
+ }
1344
+ function errorText(value) {
1345
+ const parts = [];
1346
+ try {
1347
+ const content = value?.content;
1348
+ if (!Array.isArray(content)) return "";
1349
+ for (const part of content) {
1350
+ const text = part?.text;
1351
+ if (typeof text !== "string") continue;
1352
+ const trimmed = text.trim();
1353
+ if (trimmed) parts.push(trimmed);
1354
+ }
1355
+ } catch {
1356
+ return "";
1357
+ }
1358
+ return parts.join("\n");
1359
+ }
1360
+ var RESULT_CAPTURE_MODES = ["full", "off"];
1361
+ var WITHHELD = "off";
1362
+ function endResultFields(mode, result, scrubber) {
1363
+ switch (mode) {
1364
+ case WITHHELD:
1365
+ return { result: null, result_capture: WITHHELD };
1366
+ case "full":
1367
+ return { result: scrubber(result) };
1368
+ }
1369
+ }
1370
+ function returnedErrorFields(mode, result, errorBody2, scrubber) {
1371
+ return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
1372
+ }
1373
+ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1374
+ switch (mode) {
1375
+ case WITHHELD:
1376
+ return { error_body: "", result: null, result_capture: WITHHELD };
1377
+ case "full":
1378
+ return { error_body: errorBody2(text()), result: scrubber(result) };
1379
+ }
1380
+ }
1381
+ function requestSideErrorFields(text, errorBody2) {
1382
+ return { error_body: errorBody2(text), result: null };
1383
+ }
1384
+
1125
1385
  // src/integrations/mcp/config.ts
1126
1386
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1387
+ var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1127
1388
  var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1128
1389
  function resolveTenantId(explicit, vendorId) {
1129
1390
  if (explicit) return explicit;
@@ -1234,6 +1495,14 @@ function validateBatonConfig(config) {
1234
1495
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1235
1496
  );
1236
1497
  }
1498
+ if (config.resultCaptureMode !== void 0 && !RESULT_CAPTURE_MODE_SET.has(config.resultCaptureMode)) {
1499
+ throw new Error(
1500
+ `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
1501
+ );
1502
+ }
1503
+ if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
1504
+ throw new Error("BatonConfig.scrubber must be a function.");
1505
+ }
1237
1506
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1238
1507
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1239
1508
  }
@@ -1279,34 +1548,6 @@ var DisabledSink = class {
1279
1548
  }
1280
1549
  };
1281
1550
 
1282
- // src/integrations/mcp/errorResult.ts
1283
- var TOOL_ERROR_TYPE = "tool_error";
1284
- var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1285
- function isErrorResult(value) {
1286
- try {
1287
- if (typeof value !== "object" || value === null) return false;
1288
- return Boolean(value.isError);
1289
- } catch {
1290
- return false;
1291
- }
1292
- }
1293
- function errorText(value) {
1294
- const parts = [];
1295
- try {
1296
- const content = value?.content;
1297
- if (!Array.isArray(content)) return "";
1298
- for (const part of content) {
1299
- const text = part?.text;
1300
- if (typeof text !== "string") continue;
1301
- const trimmed = text.trim();
1302
- if (trimmed) parts.push(trimmed);
1303
- }
1304
- } catch {
1305
- return "";
1306
- }
1307
- return parts.join("\n");
1308
- }
1309
-
1310
1551
  // src/integrations/mcp/handle.ts
1311
1552
  var BatonHandle = class {
1312
1553
  sink;
@@ -1560,6 +1801,8 @@ function buildSeamAugmentations(options) {
1560
1801
  // src/integrations/mcp/withBaton.ts
1561
1802
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
1562
1803
  var wired = /* @__PURE__ */ new WeakSet();
1804
+ var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1805
+ var callSlots = new AsyncLocalStorage();
1563
1806
  var SurfaceState = class {
1564
1807
  constructor(serverMeta) {
1565
1808
  this.serverMeta = serverMeta;
@@ -1614,105 +1857,137 @@ var SurfaceState = class {
1614
1857
  function errorBody(ctx, text) {
1615
1858
  return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1616
1859
  }
1617
- function batonWrap(nameRef, original, ctx) {
1618
- return async (...callArgs) => {
1619
- const toolName = nameRef.current;
1620
- await maybeEmitSurfaceSnapshot(ctx);
1621
- const extra = callArgs[callArgs.length - 1];
1622
- const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1623
- const meta = extraMeta(extra);
1624
- const runtime = detectAgentRuntime(meta, {
1625
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1626
- // `_meta`; 1.x leaves them in. Both are handed over — see
1627
- // `mcpTypes.extraEnvelope`.
1628
- envelope: extraEnvelope(extra),
1629
- // Tier 2's carrier: neither peer puts client identity on the
1630
- // handler context, both expose the cached handshake on the server.
1631
- server: ctx.server,
1632
- scrubber: ctx.scrubber
1633
- }) ?? UNKNOWN_AGENT_RUNTIME;
1634
- const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
1635
- const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1636
- const dispositions = ctx.paramRegistry.get(toolName);
1637
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1638
- const rawExpected = extractGoalParam(
1639
- params,
1640
- EXPECTED_RESULT_PARAM_NAME,
1641
- toolName,
1642
- dispositions
1643
- );
1644
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);
1645
- const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1646
- const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1647
- const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1648
- const callId = uuidv72();
1649
- const principal = await resolveCallPrincipal(
1650
- ctx.resolvePrincipal,
1651
- { extra, toolName, arguments: params },
1652
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1653
- );
1654
- const common = {
1655
- tenant_id: ctx.tenantId,
1656
- vendor_id: ctx.vendorId,
1657
- session_id: sessionId,
1658
- consent_token: ctx.consentToken,
1659
- agent_runtime: runtime,
1660
- // The five `...common` sites below are the tool-call legs — start, end,
1661
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1662
- // annotation, the same five Python stamps (`middleware.py`
1663
- // 503/547/586/644/674; it was four until the returned shape landed
1664
- // there too). `surface_snapshot` is deliberately NOT among them: it
1665
- // describes the SERVER and is captured outside any call, so there is no
1666
- // caller to name (register D5).
1667
- principal,
1668
- // Same five stamps, same exclusion: a surface_snapshot describes the
1669
- // SERVER and is captured outside any call, so it has no caller's
1670
- // transport to name any more than it has a caller to name.
1671
- transport_observed: observeTransport(extra),
1672
- runtime_meta: scrubbedMeta
1673
- };
1674
- if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1675
- await emit(
1676
- ctx.sink,
1677
- () => AnnotationEventSchema.parse({
1678
- ...common,
1679
- sequence_number: ctx.counter.next(sessionId),
1680
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1681
- payload: {
1682
- intent: scrubbedIntent,
1683
- expected_outcome: scrubbedExpected,
1684
- intent_source: INTENT_SOURCE_PARAM,
1685
- tool_name: toolName
1686
- }
1687
- })
1688
- );
1689
- }
1860
+ function errorTypeOf(err) {
1861
+ return err instanceof Error ? err.constructor.name : "Error";
1862
+ }
1863
+ function messageOf(err) {
1864
+ return err instanceof Error ? err.message : String(err);
1865
+ }
1866
+ async function resolveEnvelopeParts(ctx, extra) {
1867
+ const meta = extraMeta(extra);
1868
+ const runtime = detectAgentRuntime(meta, {
1869
+ // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1870
+ // `_meta`; 1.x leaves them in. Both are handed over — see
1871
+ // `mcpTypes.extraEnvelope`.
1872
+ envelope: extraEnvelope(extra),
1873
+ // Tier 2's carrier: neither peer puts client identity on the
1874
+ // handler context, both expose the cached handshake on the server.
1875
+ server: ctx.server,
1876
+ scrubber: ctx.scrubber
1877
+ }) ?? UNKNOWN_AGENT_RUNTIME;
1878
+ const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1879
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1880
+ return { sessionId, runtime, scrubbedMeta };
1881
+ }
1882
+ async function openCall(ctx, toolName, extra, params, registered = true) {
1883
+ await maybeEmitSurfaceSnapshot(ctx);
1884
+ const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1885
+ const dispositions = ctx.paramRegistry.get(toolName);
1886
+ const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
1887
+ const rawExpected = extractGoalParam(
1888
+ params,
1889
+ EXPECTED_RESULT_PARAM_NAME,
1890
+ toolName,
1891
+ dispositions,
1892
+ registered
1893
+ );
1894
+ const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
1895
+ const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
1896
+ const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
1897
+ const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
1898
+ const callId = uuidv72();
1899
+ const principal = await resolveCallPrincipal(
1900
+ ctx.resolvePrincipal,
1901
+ { extra, toolName, arguments: params },
1902
+ { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1903
+ );
1904
+ const common = {
1905
+ tenant_id: ctx.tenantId,
1906
+ vendor_id: ctx.vendorId,
1907
+ session_id: sessionId,
1908
+ consent_token: ctx.consentToken,
1909
+ agent_runtime: runtime,
1910
+ // The five `...common` sites below are the tool-call legs — start, end,
1911
+ // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1912
+ // annotation, the same five Python stamps (`middleware.py`
1913
+ // 503/547/586/644/674; it was four until the returned shape landed
1914
+ // there too). `surface_snapshot` is deliberately NOT among them: it
1915
+ // describes the SERVER and is captured outside any call, so there is no
1916
+ // caller to name (register D5).
1917
+ principal,
1918
+ // Same five stamps, same exclusion: a surface_snapshot describes the
1919
+ // SERVER and is captured outside any call, so it has no caller's
1920
+ // transport to name any more than it has a caller to name.
1921
+ transport_observed: observeTransport(extra),
1922
+ runtime_meta: scrubbedMeta
1923
+ };
1924
+ if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1690
1925
  await emit(
1691
1926
  ctx.sink,
1692
- () => ToolCallStartEventSchema.parse({
1927
+ () => AnnotationEventSchema.parse({
1693
1928
  ...common,
1694
- call_id: callId,
1695
1929
  sequence_number: ctx.counter.next(sessionId),
1696
1930
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1697
1931
  payload: {
1698
- tool_name: toolName,
1699
- params: ctx.scrubber(params),
1700
- call_intent: scrubbedIntent,
1701
- call_expected: scrubbedExpected,
1702
- call_workflow: scrubbedWorkflow,
1703
- intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
1932
+ intent: scrubbedIntent,
1933
+ expected_outcome: scrubbedExpected,
1934
+ intent_source: INTENT_SOURCE_PARAM,
1935
+ tool_name: toolName
1704
1936
  }
1705
1937
  })
1706
1938
  );
1939
+ }
1940
+ await emit(
1941
+ ctx.sink,
1942
+ () => ToolCallStartEventSchema.parse({
1943
+ ...common,
1944
+ call_id: callId,
1945
+ sequence_number: ctx.counter.next(sessionId),
1946
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1947
+ payload: {
1948
+ tool_name: toolName,
1949
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for params
1950
+ params: ctx.scrubber(params),
1951
+ call_intent: scrubbedIntent,
1952
+ call_expected: scrubbedExpected,
1953
+ call_workflow: scrubbedWorkflow,
1954
+ intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
1955
+ }
1956
+ })
1957
+ );
1958
+ return { common, callId, sessionId };
1959
+ }
1960
+ function batonWrap(nameRef, original, ctx) {
1961
+ return async (...callArgs) => {
1962
+ const toolName = nameRef.current;
1963
+ const slot = callSlots.getStore();
1964
+ if (slot) slot.innerFired = true;
1965
+ const extra = callArgs[callArgs.length - 1];
1966
+ const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1967
+ const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);
1968
+ const terminate = async (build, replacement) => {
1969
+ if (!slot) {
1970
+ await emit(ctx.sink, build);
1971
+ return;
1972
+ }
1973
+ const earlier = slot.flushTerminal;
1974
+ if (earlier !== null) await earlier(CLEAN_OUTCOME);
1975
+ slot.flushTerminal = async (outcome) => {
1976
+ await emit(
1977
+ ctx.sink,
1978
+ () => replacement !== null && outcome.failed ? replacement(outcome) : build()
1979
+ );
1980
+ };
1981
+ };
1982
+ const parkFailure = (build) => terminate(build, null);
1983
+ const parkSuccess = (build, replacement) => terminate(build, replacement);
1707
1984
  const startedAt = performance.now();
1708
1985
  let result;
1709
1986
  try {
1710
1987
  result = await original(...callArgs);
1711
1988
  } catch (err) {
1712
1989
  const durationMs2 = Math.round(performance.now() - startedAt);
1713
- const message = err instanceof Error ? err.message : String(err);
1714
- await emit(
1715
- ctx.sink,
1990
+ await parkFailure(
1716
1991
  () => ToolCallErrorEventSchema.parse({
1717
1992
  ...common,
1718
1993
  call_id: callId,
@@ -1720,17 +1995,26 @@ function batonWrap(nameRef, original, ctx) {
1720
1995
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1721
1996
  payload: {
1722
1997
  tool_name: toolName,
1723
- error_type: err instanceof Error ? err.constructor.name : "Error",
1724
- error_body: errorBody(ctx, message),
1998
+ error_type: errorTypeOf(err),
1999
+ // ⚠ KEPT under `resultCaptureMode: "off"`, and that is the rule's
2000
+ // shape rather than an exception to it: the rule is keyed on
2001
+ // PROVENANCE, and a thrown error's message is the vendor's own
2002
+ // code speaking about a call that returned nothing (SPEC
2003
+ // §11.4.3(1)). A switch written as "drop `error_body`" would
2004
+ // delete the highest-value diagnostic the product has.
2005
+ error_body: errorBody(ctx, messageOf(err)),
1725
2006
  duration_ms: durationMs2,
1726
2007
  // Explicit, though the field is `.optional()` and this is its
1727
2008
  // absent value. The schema is deliberately not an emitter (see
1728
2009
  // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1729
- // key would be missing — and Python's `tool_call_error` vector
1730
- // carries `result: null`, so the cross-SDK key-set check in
1731
- // `emitterConformance.test.ts` is what would say so. Each of the
1732
- // two failure shapes declares which it is, the same reason
1733
- // Python's emitter made the parameter positional-without-default.
2010
+ // key would be missing. Each of the two failure shapes declares
2011
+ // which it is, the same reason Python's emitter made the parameter
2012
+ // positional-without-default.
2013
+ //
2014
+ // ⚠ Guarded by `errorResult.test.ts`'s `toContain("result")`, NOT by
2015
+ // the cross-SDK key-set check — measured by removing this line. Why,
2016
+ // at one site: `endResultFields` in `errorResult.ts`. SPEC §11.4.3
2017
+ // states the same void rationale and wants the same amendment.
1734
2018
  result: null
1735
2019
  }
1736
2020
  })
@@ -1739,8 +2023,7 @@ function batonWrap(nameRef, original, ctx) {
1739
2023
  }
1740
2024
  const durationMs = Math.round(performance.now() - startedAt);
1741
2025
  if (isErrorResult(result)) {
1742
- await emit(
1743
- ctx.sink,
2026
+ await parkFailure(
1744
2027
  () => ToolCallErrorEventSchema.parse({
1745
2028
  ...common,
1746
2029
  call_id: callId,
@@ -1749,36 +2032,105 @@ function batonWrap(nameRef, original, ctx) {
1749
2032
  payload: {
1750
2033
  tool_name: toolName,
1751
2034
  error_type: TOOL_ERROR_TYPE,
1752
- error_body: errorBody(ctx, errorText(result)),
1753
2035
  duration_ms: durationMs,
1754
- // The whole envelope. ⚠ On this producer that is the same shape
1755
- // `tool_call_end.result` records, which is NOT what Python's
1756
- // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1757
- // holds that claim and names the test that enforces it.
1758
- result: ctx.scrubber(result)
2036
+ // Both remaining members are unwrapped FROM the result on this
2037
+ // shape, so one projection decides them together and owns the
2038
+ // scrubber call. `error_type` is NOT result-derived and is passed
2039
+ // regardless: the call still failed (SPEC §11.2.6).
2040
+ //
2041
+ // ⚠ Under `"full"` `result` is the whole envelope, and on this
2042
+ // producer that is the same shape `tool_call_end.result` records —
2043
+ // which is NOT what Python's contrast says.
2044
+ // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
2045
+ // names the test that enforces it.
2046
+ ...returnedErrorFields(
2047
+ ctx.resultCaptureMode,
2048
+ result,
2049
+ (text) => errorBody(ctx, text),
2050
+ ctx.scrubber
2051
+ )
1759
2052
  }
1760
2053
  })
1761
2054
  );
1762
2055
  return result;
1763
2056
  }
1764
- await emit(
1765
- ctx.sink,
2057
+ await parkSuccess(
1766
2058
  () => ToolCallEndEventSchema.parse({
1767
2059
  ...common,
1768
2060
  call_id: callId,
1769
2061
  sequence_number: ctx.counter.next(sessionId),
1770
2062
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1771
- payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
2063
+ payload: {
2064
+ tool_name: toolName,
2065
+ duration_ms: durationMs,
2066
+ ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
2067
+ }
2068
+ }),
2069
+ // The handler returned something this sensor reads as a success, and
2070
+ // then the outer seam saw the call fail anyway — so what failed is the
2071
+ // producer's own conversion of the output (SPEC §11.4.3's
2072
+ // `output_schema_mismatch`). Correcting this is the whole point of the
2073
+ // second seam: without it this is a `tool_call_end` for a call the
2074
+ // CALLER saw fail, which is a success the product invented.
2075
+ (outcome) => ToolCallErrorEventSchema.parse({
2076
+ ...common,
2077
+ call_id: callId,
2078
+ sequence_number: ctx.counter.next(sessionId),
2079
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2080
+ payload: {
2081
+ tool_name: toolName,
2082
+ // The lane the OUTER came back on, not this one's: on 2.x the
2083
+ // conversion failure is converted to a returned `isError` inside
2084
+ // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2085
+ // right there. A throw out of the handler is unreachable on
2086
+ // either major today for this lane; spelled anyway, because the
2087
+ // alternative is a crash on the day it stops being.
2088
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2089
+ // ⚠ The INNER's measurement — the vendor's handler duration —
2090
+ // not the outer's. Every other leg means the same thing by this
2091
+ // member, and widening it here for one failure kind would make
2092
+ // `duration_ms` mean two things in one column.
2093
+ duration_ms: durationMs,
2094
+ failure_kind: OUTPUT_SCHEMA_MISMATCH,
2095
+ // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2096
+ // kinds.** The message quotes the value the tool returned
2097
+ // ("`'not-an-int'` is not of type `integer`"), so it is
2098
+ // result-derived by provenance and goes — which leaves
2099
+ // `failure_kind` as the ONLY surviving signal for this failure
2100
+ // under `"off"`, and is the measurement that justified putting
2101
+ // the member on the wire at all.
2102
+ //
2103
+ // ⚠ `result` is what the CLIENT received — the SDK's own error
2104
+ // envelope — not the vendor's rejected return value. §11.4.3
2105
+ // asks for the envelope that holds the flag and the reason, and
2106
+ // this package's own invariant is that it agrees with the
2107
+ // caller. Recording the rejected output TOO would need a member
2108
+ // nothing on the wire has; the loss is deliberate and worth
2109
+ // knowing when debugging one of these.
2110
+ ...resultDerivedFields(
2111
+ ctx.resultCaptureMode,
2112
+ () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2113
+ // ⚠ `null` on the `raised` lane, never `undefined`, and the
2114
+ // union is what forces the branch rather than a comment: the
2115
+ // scrubber would answer `undefined` and DROP the key, where the
2116
+ // sibling raise lane a few lines up declares `result: null`
2117
+ // explicitly, for the reason `ToolCallErrorPayloadSchema`
2118
+ // records. One shape for "no result object existed", not two.
2119
+ outcome.raised ? null : outcome.result ?? null,
2120
+ (text) => errorBody(ctx, text),
2121
+ ctx.scrubber
2122
+ )
2123
+ }
1772
2124
  })
1773
2125
  );
1774
2126
  return result;
1775
2127
  };
1776
2128
  }
1777
- function extractGoalParam(args, paramName, toolName, dispositions) {
2129
+ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
1778
2130
  if (!(paramName in args)) return null;
1779
2131
  const disposition = dispositions ? dispositions[paramName] : void 0;
1780
2132
  if (disposition === "native") return null;
1781
- if (disposition === void 0) {
2133
+ if (disposition === void 0 && registered) {
1782
2134
  process.stderr.write(
1783
2135
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
1784
2136
  `
@@ -1837,12 +2189,29 @@ function captureAndInject(name, entry, ctx) {
1837
2189
  }
1838
2190
  var TOOLS_LIST_METHOD = "tools/list";
1839
2191
  var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
1840
- function installToolsListSeam(lowLevel, ctx) {
2192
+ var TOOLS_CALL_METHOD = "tools/call";
2193
+ var TOOLS_CALL_SEAM = /* @__PURE__ */ Symbol("batonToolsCallSeam");
2194
+ function installRequestSeam(lowLevel, method, seamTag, wrap) {
1841
2195
  const table = lowLevel._requestHandlers;
1842
2196
  const originalSet = lowLevel.setRequestHandler;
1843
2197
  if (!(table instanceof Map) || typeof originalSet !== "function") return;
1844
2198
  const handlers = table;
1845
2199
  const setRequestHandler = originalSet;
2200
+ const wrapCurrent = () => {
2201
+ const handler = handlers.get(method);
2202
+ if (typeof handler !== "function" || handler[seamTag]) return;
2203
+ const seamed = wrap(handler);
2204
+ seamed[seamTag] = true;
2205
+ handlers.set(method, seamed);
2206
+ };
2207
+ wrapCurrent();
2208
+ lowLevel.setRequestHandler = (...args) => {
2209
+ const registered = setRequestHandler.apply(lowLevel, args);
2210
+ wrapCurrent();
2211
+ return registered;
2212
+ };
2213
+ }
2214
+ function installToolsListSeam(lowLevel, ctx) {
1846
2215
  const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
1847
2216
  const advertise = (result) => {
1848
2217
  try {
@@ -1855,22 +2224,273 @@ function installToolsListSeam(lowLevel, ctx) {
1855
2224
  return result;
1856
2225
  }
1857
2226
  };
1858
- const wrapCurrent = () => {
1859
- const handler = handlers.get(TOOLS_LIST_METHOD);
1860
- if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
1861
- const seamed = (...args) => {
1862
- const out = handler(...args);
1863
- return isThenable(out) ? out.then(advertise) : advertise(out);
2227
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {
2228
+ const out = handler(...args);
2229
+ return isThenable(out) ? out.then(advertise) : advertise(out);
2230
+ });
2231
+ }
2232
+ var LIFECYCLE_SEAMS = {
2233
+ resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2234
+ resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2235
+ promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2236
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2237
+ };
2238
+ function installLifecycleSeam(lowLevel, ctx, spec) {
2239
+ installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
2240
+ const request = args[0];
2241
+ const requestParams = request?.params ?? {};
2242
+ const extra = args[1];
2243
+ const opened = await openLifecycleCall(ctx, spec, requestParams, extra);
2244
+ const fire = async (schema, payload) => {
2245
+ if (opened === null) return;
2246
+ await emit(
2247
+ ctx.sink,
2248
+ () => schema.parse({
2249
+ ...opened.common,
2250
+ sequence_number: ctx.counter.next(opened.sessionId),
2251
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2252
+ payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
2253
+ })
2254
+ );
1864
2255
  };
1865
- seamed[TOOLS_LIST_SEAM] = true;
1866
- handlers.set(TOOLS_LIST_METHOD, seamed);
1867
- };
1868
- wrapCurrent();
1869
- lowLevel.setRequestHandler = (...args) => {
1870
- const registered = setRequestHandler.apply(lowLevel, args);
1871
- wrapCurrent();
1872
- return registered;
1873
- };
2256
+ await fire(spec.schemas.start, spec.startParams(requestParams));
2257
+ const startedAt = performance.now();
2258
+ const elapsed = () => Math.round(performance.now() - startedAt);
2259
+ try {
2260
+ const result = await handler(...args);
2261
+ await fire(spec.schemas.end, {
2262
+ ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
2263
+ duration_ms: elapsed()
2264
+ });
2265
+ return result;
2266
+ } catch (err) {
2267
+ await fire(spec.schemas.error, {
2268
+ error_type: errorTypeOf(err),
2269
+ // KEPT under every capture mode: a failed FETCH's message is the
2270
+ // producer's own diagnostic, not anything a resource returned, so
2271
+ // nothing here is result-derived (SPEC §11.4.4). The scrub and the cap
2272
+ // are `scrubLifecyclePayload`'s, in that order.
2273
+ error_body: messageOf(err),
2274
+ duration_ms: elapsed()
2275
+ });
2276
+ throw err;
2277
+ }
2278
+ });
2279
+ }
2280
+ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2281
+ try {
2282
+ const parts = await resolveEnvelopeParts(ctx, extra);
2283
+ return {
2284
+ sessionId: parts.sessionId,
2285
+ subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
2286
+ common: {
2287
+ tenant_id: ctx.tenantId,
2288
+ vendor_id: ctx.vendorId,
2289
+ session_id: parts.sessionId,
2290
+ consent_token: ctx.consentToken,
2291
+ agent_runtime: parts.runtime,
2292
+ transport_observed: observeTransport(extra),
2293
+ runtime_meta: parts.scrubbedMeta
2294
+ }
2295
+ };
2296
+ } catch (err) {
2297
+ process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
2298
+ `);
2299
+ return null;
2300
+ }
2301
+ }
2302
+ var NO_PARAMS = () => EMPTY_PARAMS;
2303
+ var EMPTY_PARAMS = Object.freeze({});
2304
+ var LIFECYCLE_SPECS = [
2305
+ {
2306
+ method: "resources/list",
2307
+ seamTag: LIFECYCLE_SEAMS.resourceList,
2308
+ schemas: {
2309
+ start: ResourceListStartEventSchema,
2310
+ end: ResourceListEndEventSchema,
2311
+ error: ResourceListErrorEventSchema
2312
+ },
2313
+ // ⚠ `resources` ALONE. Resource TEMPLATES are a separate MCP method with
2314
+ // their own result array and are deliberately not added in, matching the
2315
+ // proxy — so a template-only server reports 0, which §11.4.4 says a
2316
+ // consumer MUST NOT read as "this server has no resources".
2317
+ countKey: "resources",
2318
+ startParams: NO_PARAMS
2319
+ },
2320
+ {
2321
+ method: "resources/read",
2322
+ seamTag: LIFECYCLE_SEAMS.resourceRead,
2323
+ schemas: {
2324
+ start: ResourceReadStartEventSchema,
2325
+ end: ResourceReadEndEventSchema,
2326
+ error: ResourceReadErrorEventSchema
2327
+ },
2328
+ subjectKey: "uri",
2329
+ // ⚠ The whole params bag MINUS `_meta`, so `uri` lands here as well as in
2330
+ // its own member. That duplication is the proxy's and is reproduced on
2331
+ // purpose: the dedicated member is what a consumer reads, the bag is what
2332
+ // the caller actually sent, and a producer that stripped `uri` out could no
2333
+ // longer say the second thing. `_meta` is excluded because it rides the
2334
+ // envelope as `runtime_meta` already.
2335
+ startParams: (params) => ({ params: paramsBag(params) })
2336
+ },
2337
+ {
2338
+ method: "prompts/list",
2339
+ seamTag: LIFECYCLE_SEAMS.promptList,
2340
+ schemas: {
2341
+ start: PromptListStartEventSchema,
2342
+ end: PromptListEndEventSchema,
2343
+ error: PromptListErrorEventSchema
2344
+ },
2345
+ countKey: "prompts",
2346
+ startParams: NO_PARAMS
2347
+ },
2348
+ {
2349
+ method: "prompts/get",
2350
+ seamTag: LIFECYCLE_SEAMS.promptGet,
2351
+ schemas: {
2352
+ start: PromptGetStartEventSchema,
2353
+ end: PromptGetEndEventSchema,
2354
+ error: PromptGetErrorEventSchema
2355
+ },
2356
+ subjectKey: "name",
2357
+ // ⚠ `arguments` ALONE, NOT the whole bag — the opposite of the resource
2358
+ // read above, so `name` does NOT appear inside `params`. The two are
2359
+ // inconsistent in the producer the shapes came from; the inconsistency is
2360
+ // reproduced rather than tidied, because a consumer reading one producer
2361
+ // and a second producer reading the other must agree.
2362
+ startParams: (params) => ({
2363
+ params: paramsBag(params["arguments"])
2364
+ })
2365
+ }
2366
+ ];
2367
+ function installLifecycleSeams(lowLevel, ctx) {
2368
+ for (const spec of LIFECYCLE_SPECS) installLifecycleSeam(lowLevel, ctx, spec);
2369
+ }
2370
+ function stringSubject(value) {
2371
+ return typeof value === "string" ? value : "";
2372
+ }
2373
+ function countOf(result, key) {
2374
+ const list = result?.[key];
2375
+ return Array.isArray(list) ? list.length : 0;
2376
+ }
2377
+ function paramsBag(bag) {
2378
+ if (!bag || typeof bag !== "object") return {};
2379
+ const out = {};
2380
+ for (const key of Object.keys(bag)) {
2381
+ if (key !== "_meta") out[key] = bag[key];
2382
+ }
2383
+ return out;
2384
+ }
2385
+ function scrubLifecyclePayload(ctx, raw) {
2386
+ const scrubbed = ctx.scrubber(raw);
2387
+ const body = scrubbed?.["error_body"];
2388
+ if (typeof body !== "string") return scrubbed;
2389
+ return { ...scrubbed, error_body: capCodePoints(body, ERROR_BODY_MAX_CODE_POINTS) };
2390
+ }
2391
+ function dispatchSlot(entry) {
2392
+ if (typeof entry.executor === "function") return "executor";
2393
+ if (typeof entry.handler === "function") return "handler";
2394
+ return void 0;
2395
+ }
2396
+ function dispatchTarget(entry) {
2397
+ const slot = dispatchSlot(entry);
2398
+ return slot === void 0 ? void 0 : entry[slot];
2399
+ }
2400
+ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2401
+ installRequestSeam(
2402
+ lowLevel,
2403
+ TOOLS_CALL_METHOD,
2404
+ TOOLS_CALL_SEAM,
2405
+ (handler) => async (...args) => {
2406
+ const slot = { innerFired: false, flushTerminal: null };
2407
+ let outcome = CLEAN_OUTCOME;
2408
+ try {
2409
+ const result = await callSlots.run(slot, () => handler(...args));
2410
+ outcome = { failed: isErrorResult(result), raised: false, result };
2411
+ return result;
2412
+ } catch (err) {
2413
+ outcome = { failed: true, raised: true, err };
2414
+ throw err;
2415
+ } finally {
2416
+ await settleCall(slot, outcome, args, toolEntry, ctx);
2417
+ }
2418
+ }
2419
+ );
2420
+ }
2421
+ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2422
+ try {
2423
+ if (slot.flushTerminal !== null) {
2424
+ const flush = slot.flushTerminal;
2425
+ slot.flushTerminal = null;
2426
+ await flush(outcome);
2427
+ return;
2428
+ }
2429
+ if (slot.innerFired) return;
2430
+ if (!outcome.failed) return;
2431
+ await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2432
+ } catch (err) {
2433
+ process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2434
+ `);
2435
+ }
2436
+ }
2437
+ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2438
+ const request = args[0];
2439
+ const toolName = request?.params?.name;
2440
+ if (typeof toolName !== "string") return;
2441
+ if (toolName === ctx.annotationToolName) return;
2442
+ const entry = toolEntry(toolName);
2443
+ if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2444
+ const params = { ...request?.params?.arguments ?? {} };
2445
+ const { common, callId, sessionId } = await openCall(
2446
+ ctx,
2447
+ toolName,
2448
+ args[1],
2449
+ params,
2450
+ entry != null
2451
+ );
2452
+ const failureKind = requestSideFailureKind(entry);
2453
+ await emit(
2454
+ ctx.sink,
2455
+ () => ToolCallErrorEventSchema.parse({
2456
+ ...common,
2457
+ call_id: callId,
2458
+ sequence_number: ctx.counter.next(sessionId),
2459
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2460
+ payload: {
2461
+ tool_name: toolName,
2462
+ // The lane the SDK rejected on, which is NOT the same across majors
2463
+ // for one failure: 1.x converts all three to a returned `isError`
2464
+ // inside its own `try` (`mcp.js:101-108`), v2 THROWS the first two
2465
+ // and returns the third. So the same customer-visible failure is
2466
+ // `"tool_error"` on one major and `"ProtocolError"` on the other —
2467
+ // measured 2026-10-01, and deliberately not special-cased: this
2468
+ // member is §11.4.3's RAISE/RETURN discriminator and it is reporting
2469
+ // the shape faithfully. `failure_kind` is what makes the two
2470
+ // comparable, which is the member's whole justification.
2471
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2472
+ // ⚠ `null`, not 0. The vendor's handler never ran, so there is no
2473
+ // handler duration to report; the time this call did spend was spent
2474
+ // in the SDK's validator, which is not what any other event means by
2475
+ // this member. §11.4 types it nullable for cases like this one.
2476
+ duration_ms: null,
2477
+ // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
2478
+ // `.optional()` accepts `undefined` and keeps the KEY in its output,
2479
+ // so the plain form writes a present-but-undefined member — invisible
2480
+ // to a JSON-serialising sink and plainly visible to a vendor-supplied
2481
+ // one that iterates keys. SPEC §11.4.3 says a producer that cannot
2482
+ // determine the kind MUST OMIT the member, and omitting is what this
2483
+ // spells.
2484
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
2485
+ // KEPT under `"off"` — see `requestSideErrorFields`, which takes no
2486
+ // capture mode because nothing here is derived from a result.
2487
+ ...requestSideErrorFields(
2488
+ outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2489
+ (text) => errorBody(ctx, text)
2490
+ )
2491
+ }
2492
+ })
2493
+ );
1874
2494
  }
1875
2495
  function isThenable(value) {
1876
2496
  return typeof value?.then === "function";
@@ -1878,20 +2498,13 @@ function isThenable(value) {
1878
2498
  function wrapIfNeeded(nameRef, entry, ctx) {
1879
2499
  if (!entry || typeof entry !== "object") return;
1880
2500
  const mutable = entry;
1881
- if (typeof mutable.executor === "function") {
1882
- if (mutable.executor[BATON_WRAPPED]) return;
1883
- const originalExecutor = mutable.executor;
1884
- const wrapper2 = batonWrap(nameRef, originalExecutor, ctx);
1885
- wrapper2[BATON_WRAPPED] = true;
1886
- mutable.executor = wrapper2;
1887
- return;
1888
- }
1889
- if (typeof mutable.handler !== "function") return;
1890
- if (mutable.handler[BATON_WRAPPED]) return;
1891
- const original = mutable.handler;
1892
- const wrapper = batonWrap(nameRef, original, ctx);
2501
+ const slot = dispatchSlot(mutable);
2502
+ if (slot === void 0) return;
2503
+ const target = mutable[slot];
2504
+ if (target[BATON_WRAPPED]) return;
2505
+ const wrapper = batonWrap(nameRef, target, ctx);
1893
2506
  wrapper[BATON_WRAPPED] = true;
1894
- mutable.handler = wrapper;
2507
+ mutable[slot] = wrapper;
1895
2508
  }
1896
2509
  function wireEntry(name, entry, ctx) {
1897
2510
  if (name === ctx.annotationToolName) return;
@@ -2046,6 +2659,7 @@ function withBaton(server, supplied = {}) {
2046
2659
  scrubber,
2047
2660
  annotationToolName,
2048
2661
  intentParamMode,
2662
+ resultCaptureMode: config.resultCaptureMode ?? "full",
2049
2663
  paramRegistry: /* @__PURE__ */ new Map(),
2050
2664
  resolvePrincipal: config.resolvePrincipal,
2051
2665
  principalIdMode: config.principalIdMode ?? "hashed",
@@ -2063,6 +2677,22 @@ function withBaton(server, supplied = {}) {
2063
2677
  });
2064
2678
  internals.server._instructions = instructions;
2065
2679
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
2680
+ installToolsCallSeam(
2681
+ internals.server,
2682
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
2683
+ // object, so `registry["constructor"]` answers `Object` and
2684
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
2685
+ // so the "a tool we did not wrap" guard would decline to report, and a
2686
+ // caller-visible `Tool constructor disabled` would reach the client with
2687
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
2688
+ // exactly the kind of failure the seam exists to make visible.
2689
+ (name) => {
2690
+ const registry = internals._registeredTools;
2691
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
2692
+ },
2693
+ ctx
2694
+ );
2695
+ installLifecycleSeams(internals.server, ctx);
2066
2696
  const resolvedAnnotationToolName = registerAnnotationTool(server, {
2067
2697
  sink,
2068
2698
  counter: ctx.counter,
@@ -2114,12 +2744,35 @@ export {
2114
2744
  DEPTH_LIMIT,
2115
2745
  EventSchema,
2116
2746
  EventTypeSchema,
2117
- HASH_SCHEME,
2118
2747
  HttpSink,
2119
2748
  PRINCIPAL_FORM_HASHED,
2120
2749
  PRINCIPAL_FORM_RAW,
2121
2750
  PRINCIPAL_SOURCE_ASSERTED,
2122
2751
  PrincipalWireSchema,
2752
+ PromptGetEndEventSchema,
2753
+ PromptGetEndPayloadSchema,
2754
+ PromptGetErrorEventSchema,
2755
+ PromptGetErrorPayloadSchema,
2756
+ PromptGetStartEventSchema,
2757
+ PromptGetStartPayloadSchema,
2758
+ PromptListEndEventSchema,
2759
+ PromptListEndPayloadSchema,
2760
+ PromptListErrorEventSchema,
2761
+ PromptListErrorPayloadSchema,
2762
+ PromptListStartEventSchema,
2763
+ PromptListStartPayloadSchema,
2764
+ ResourceListEndEventSchema,
2765
+ ResourceListEndPayloadSchema,
2766
+ ResourceListErrorEventSchema,
2767
+ ResourceListErrorPayloadSchema,
2768
+ ResourceListStartEventSchema,
2769
+ ResourceListStartPayloadSchema,
2770
+ ResourceReadEndEventSchema,
2771
+ ResourceReadEndPayloadSchema,
2772
+ ResourceReadErrorEventSchema,
2773
+ ResourceReadErrorPayloadSchema,
2774
+ ResourceReadStartEventSchema,
2775
+ ResourceReadStartPayloadSchema,
2123
2776
  SDK_VERSION,
2124
2777
  Scrubber,
2125
2778
  StdoutSink,