@goodtiming/baton-sdk 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -42,6 +42,30 @@ __export(index_exports, {
42
42
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
43
43
  PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
44
44
  PrincipalWireSchema: () => PrincipalWireSchema,
45
+ PromptGetEndEventSchema: () => PromptGetEndEventSchema,
46
+ PromptGetEndPayloadSchema: () => PromptGetEndPayloadSchema,
47
+ PromptGetErrorEventSchema: () => PromptGetErrorEventSchema,
48
+ PromptGetErrorPayloadSchema: () => PromptGetErrorPayloadSchema,
49
+ PromptGetStartEventSchema: () => PromptGetStartEventSchema,
50
+ PromptGetStartPayloadSchema: () => PromptGetStartPayloadSchema,
51
+ PromptListEndEventSchema: () => PromptListEndEventSchema,
52
+ PromptListEndPayloadSchema: () => PromptListEndPayloadSchema,
53
+ PromptListErrorEventSchema: () => PromptListErrorEventSchema,
54
+ PromptListErrorPayloadSchema: () => PromptListErrorPayloadSchema,
55
+ PromptListStartEventSchema: () => PromptListStartEventSchema,
56
+ PromptListStartPayloadSchema: () => PromptListStartPayloadSchema,
57
+ ResourceListEndEventSchema: () => ResourceListEndEventSchema,
58
+ ResourceListEndPayloadSchema: () => ResourceListEndPayloadSchema,
59
+ ResourceListErrorEventSchema: () => ResourceListErrorEventSchema,
60
+ ResourceListErrorPayloadSchema: () => ResourceListErrorPayloadSchema,
61
+ ResourceListStartEventSchema: () => ResourceListStartEventSchema,
62
+ ResourceListStartPayloadSchema: () => ResourceListStartPayloadSchema,
63
+ ResourceReadEndEventSchema: () => ResourceReadEndEventSchema,
64
+ ResourceReadEndPayloadSchema: () => ResourceReadEndPayloadSchema,
65
+ ResourceReadErrorEventSchema: () => ResourceReadErrorEventSchema,
66
+ ResourceReadErrorPayloadSchema: () => ResourceReadErrorPayloadSchema,
67
+ ResourceReadStartEventSchema: () => ResourceReadStartEventSchema,
68
+ ResourceReadStartPayloadSchema: () => ResourceReadStartPayloadSchema,
45
69
  SDK_VERSION: () => SDK_VERSION,
46
70
  Scrubber: () => Scrubber,
47
71
  StdoutSink: () => StdoutSink,
@@ -55,13 +79,15 @@ __export(index_exports, {
55
79
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
56
80
  hashPrincipalId: () => hashPrincipalId,
57
81
  identityScrub: () => identityScrub,
82
+ principalFromOAuthEmail: () => principalFromOAuthEmail,
83
+ principalFromOAuthSub: () => principalFromOAuthSub,
58
84
  safeWrite: () => safeWrite,
59
85
  withBaton: () => withBaton
60
86
  });
61
87
  module.exports = __toCommonJS(index_exports);
62
88
 
63
89
  // src/version.ts
64
- var SDK_VERSION = "ts-0.4.1";
90
+ var SDK_VERSION = "ts-0.5.1";
65
91
 
66
92
  // src/events.ts
67
93
  var import_zod = require("zod");
@@ -77,7 +103,24 @@ var ToolCallStartPayloadSchema = import_zod.z.object({
77
103
  var ToolCallEndPayloadSchema = import_zod.z.object({
78
104
  tool_name: import_zod.z.string(),
79
105
  result: import_zod.z.unknown().nullable().default(null),
80
- duration_ms: import_zod.z.number().int().nullable().default(null)
106
+ duration_ms: import_zod.z.number().int().nullable().default(null),
107
+ // SPEC §11.4: the producer declares it WITHHELD result-derived data.
108
+ // Absent means CAPTURED, so no consumer needs a version table.
109
+ //
110
+ // `.optional()`, NOT `.default(null)`, for the reason recorded on
111
+ // `ToolCallErrorPayloadSchema.result` below: a default makes this reader
112
+ // an EMITTER, and parsing a stored event from before the member existed
113
+ // would hand back an invented key.
114
+ //
115
+ // ⚠ **This package OMITS the member when capturing, where the Python SDK
116
+ // sends `result_capture: null`.** Both are conformant and SPEC §11.4 says
117
+ // so outright — absent and null are equivalent, and a consumer MUST read
118
+ // the VALUE, never test for the key. It is the same axis `result` already
119
+ // differs on between `baton-sdk` (null) and `baton-proxy` (omitted), per
120
+ // §11.4.3. Omitting is chosen here because the alternative — matching
121
+ // Python — would require regenerating `baton-spec`'s vectors from an
122
+ // UNMERGED branch, pinning a key set no released producer emits.
123
+ result_capture: import_zod.z.string().nullable().optional()
81
124
  }).strict();
82
125
  var ToolCallErrorPayloadSchema = import_zod.z.object({
83
126
  tool_name: import_zod.z.string(),
@@ -99,7 +142,28 @@ var ToolCallErrorPayloadSchema = import_zod.z.object({
99
142
  // silent when it does not. What makes the EMITTED shape complete is the
100
143
  // emitter declaring `result` on both failure legs (`withBaton.ts`),
101
144
  // explicitly `null` on a throw — not the schema filling it in.
102
- result: import_zod.z.unknown().nullable().optional()
145
+ result: import_zod.z.unknown().nullable().optional(),
146
+ // SPEC §11.4, on BOTH payloads because the RETURN failure shape withholds
147
+ // `result` too. Same `.optional()` reasoning as the field above it, and
148
+ // same omit-when-capturing posture as `ToolCallEndPayloadSchema`.
149
+ result_capture: import_zod.z.string().nullable().optional(),
150
+ // SPEC §11.4.3: the producer NAMES a failure it made above the vendor's
151
+ // handler. `tool_call_error` ONLY — unlike `result_capture`, which rides
152
+ // both payloads — because the one case that files `tool_call_end` today
153
+ // IS the false success this member exists to correct, so after the fix
154
+ // nothing carries it on a success payload.
155
+ //
156
+ // A plain `z.string()` and NOT `z.enum(FAILURE_KINDS)`, which SPEC
157
+ // requires rather than permits: a closed enum turns a later registered
158
+ // value into a `ValidationError` on the vendor's tool-call path, which
159
+ // §11.2 says must fail open. The registry in
160
+ // `integrations/mcp/errorResult.ts` constrains what this producer EMITS;
161
+ // it must not constrain what this schema READS.
162
+ //
163
+ // Same `.optional()`-not-`.default(null)` reasoning as the two fields
164
+ // above: a default makes the schema an emitter, and parsing a stored
165
+ // event from before the member existed would hand back an invented key.
166
+ failure_kind: import_zod.z.string().nullable().optional()
103
167
  }).strict();
104
168
  var AnnotationPayloadSchema = import_zod.z.object({
105
169
  intent: import_zod.z.string().nullable().default(null),
@@ -123,7 +187,8 @@ var DEFAULT_CONSENT_TOKEN = "customer-consented";
123
187
  var PrincipalWireSchema = import_zod.z.object({
124
188
  id: import_zod.z.string(),
125
189
  source: import_zod.z.string(),
126
- form: import_zod.z.string()
190
+ form: import_zod.z.string(),
191
+ display_name: import_zod.z.string().nullable().optional()
127
192
  }).strict();
128
193
  var envelopeShape = {
129
194
  event_id: import_zod.z.uuid().default(() => (0, import_uuid.v7)()),
@@ -145,8 +210,75 @@ var EventTypeSchema = import_zod.z.enum([
145
210
  "tool_call_end",
146
211
  "tool_call_error",
147
212
  "annotation",
148
- "surface_snapshot"
213
+ "surface_snapshot",
214
+ // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
215
+ // shapes were set by `baton-proxy`, which has been emitting all of them in
216
+ // production — see the payload schemas below.
217
+ "resource_list_start",
218
+ "resource_list_end",
219
+ "resource_list_error",
220
+ "resource_read_start",
221
+ "resource_read_end",
222
+ "resource_read_error",
223
+ "prompt_list_start",
224
+ "prompt_list_end",
225
+ "prompt_list_error",
226
+ "prompt_get_start",
227
+ "prompt_get_end",
228
+ "prompt_get_error"
149
229
  ]);
230
+ var timingShape = { duration_ms: import_zod.z.number().int().nullable().default(null) };
231
+ var failureShape = { error_type: import_zod.z.string(), error_body: import_zod.z.string(), ...timingShape };
232
+ var ResourceListStartPayloadSchema = import_zod.z.object({}).strict();
233
+ var ResourceListEndPayloadSchema = import_zod.z.object({
234
+ count: import_zod.z.number().int(),
235
+ ...timingShape
236
+ }).strict();
237
+ var ResourceListErrorPayloadSchema = import_zod.z.object({
238
+ ...failureShape
239
+ }).strict();
240
+ var ResourceReadStartPayloadSchema = import_zod.z.object({
241
+ uri: import_zod.z.string(),
242
+ /** The caller's own request params, PII-scrubbed (SPEC §7).
243
+ *
244
+ * ⚠ Nullable because the SCHEMA permits it, not because this producer
245
+ * emits it: `withBaton`'s `paramsBag` answers `{}` for an absent bag,
246
+ * matching `baton-proxy` (`dict(params) if params else {}` — it never
247
+ * emits null). A consumer must still read both, since the schema admits
248
+ * both and a third producer may choose either. */
249
+ params: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
250
+ }).strict();
251
+ var ResourceReadEndPayloadSchema = import_zod.z.object({
252
+ uri: import_zod.z.string(),
253
+ ...timingShape
254
+ }).strict();
255
+ var ResourceReadErrorPayloadSchema = import_zod.z.object({
256
+ uri: import_zod.z.string(),
257
+ ...failureShape
258
+ }).strict();
259
+ var PromptListStartPayloadSchema = import_zod.z.object({}).strict();
260
+ var PromptListEndPayloadSchema = import_zod.z.object({
261
+ count: import_zod.z.number().int(),
262
+ ...timingShape
263
+ }).strict();
264
+ var PromptListErrorPayloadSchema = import_zod.z.object({
265
+ ...failureShape
266
+ }).strict();
267
+ var PromptGetStartPayloadSchema = import_zod.z.object({
268
+ name: import_zod.z.string(),
269
+ /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
270
+ * where the request supplied none — see `ResourceReadStartPayloadSchema`'s
271
+ * `params` for why the schema is nullable anyway. */
272
+ params: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
273
+ }).strict();
274
+ var PromptGetEndPayloadSchema = import_zod.z.object({
275
+ name: import_zod.z.string(),
276
+ ...timingShape
277
+ }).strict();
278
+ var PromptGetErrorPayloadSchema = import_zod.z.object({
279
+ name: import_zod.z.string(),
280
+ ...failureShape
281
+ }).strict();
150
282
  var ToolCallStartEventSchema = import_zod.z.object({
151
283
  ...envelopeShape,
152
284
  event_type: import_zod.z.literal("tool_call_start").default("tool_call_start"),
@@ -172,12 +304,84 @@ var SurfaceSnapshotEventSchema = import_zod.z.object({
172
304
  event_type: import_zod.z.literal("surface_snapshot").default("surface_snapshot"),
173
305
  payload: SurfaceSnapshotPayloadSchema
174
306
  }).strict();
307
+ var ResourceListStartEventSchema = import_zod.z.object({
308
+ ...envelopeShape,
309
+ event_type: import_zod.z.literal("resource_list_start").default("resource_list_start"),
310
+ payload: ResourceListStartPayloadSchema
311
+ }).strict();
312
+ var ResourceListEndEventSchema = import_zod.z.object({
313
+ ...envelopeShape,
314
+ event_type: import_zod.z.literal("resource_list_end").default("resource_list_end"),
315
+ payload: ResourceListEndPayloadSchema
316
+ }).strict();
317
+ var ResourceListErrorEventSchema = import_zod.z.object({
318
+ ...envelopeShape,
319
+ event_type: import_zod.z.literal("resource_list_error").default("resource_list_error"),
320
+ payload: ResourceListErrorPayloadSchema
321
+ }).strict();
322
+ var ResourceReadStartEventSchema = import_zod.z.object({
323
+ ...envelopeShape,
324
+ event_type: import_zod.z.literal("resource_read_start").default("resource_read_start"),
325
+ payload: ResourceReadStartPayloadSchema
326
+ }).strict();
327
+ var ResourceReadEndEventSchema = import_zod.z.object({
328
+ ...envelopeShape,
329
+ event_type: import_zod.z.literal("resource_read_end").default("resource_read_end"),
330
+ payload: ResourceReadEndPayloadSchema
331
+ }).strict();
332
+ var ResourceReadErrorEventSchema = import_zod.z.object({
333
+ ...envelopeShape,
334
+ event_type: import_zod.z.literal("resource_read_error").default("resource_read_error"),
335
+ payload: ResourceReadErrorPayloadSchema
336
+ }).strict();
337
+ var PromptListStartEventSchema = import_zod.z.object({
338
+ ...envelopeShape,
339
+ event_type: import_zod.z.literal("prompt_list_start").default("prompt_list_start"),
340
+ payload: PromptListStartPayloadSchema
341
+ }).strict();
342
+ var PromptListEndEventSchema = import_zod.z.object({
343
+ ...envelopeShape,
344
+ event_type: import_zod.z.literal("prompt_list_end").default("prompt_list_end"),
345
+ payload: PromptListEndPayloadSchema
346
+ }).strict();
347
+ var PromptListErrorEventSchema = import_zod.z.object({
348
+ ...envelopeShape,
349
+ event_type: import_zod.z.literal("prompt_list_error").default("prompt_list_error"),
350
+ payload: PromptListErrorPayloadSchema
351
+ }).strict();
352
+ var PromptGetStartEventSchema = import_zod.z.object({
353
+ ...envelopeShape,
354
+ event_type: import_zod.z.literal("prompt_get_start").default("prompt_get_start"),
355
+ payload: PromptGetStartPayloadSchema
356
+ }).strict();
357
+ var PromptGetEndEventSchema = import_zod.z.object({
358
+ ...envelopeShape,
359
+ event_type: import_zod.z.literal("prompt_get_end").default("prompt_get_end"),
360
+ payload: PromptGetEndPayloadSchema
361
+ }).strict();
362
+ var PromptGetErrorEventSchema = import_zod.z.object({
363
+ ...envelopeShape,
364
+ event_type: import_zod.z.literal("prompt_get_error").default("prompt_get_error"),
365
+ payload: PromptGetErrorPayloadSchema
366
+ }).strict();
175
367
  var EventSchema = import_zod.z.discriminatedUnion("event_type", [
176
368
  ToolCallStartEventSchema,
177
369
  ToolCallEndEventSchema,
178
370
  ToolCallErrorEventSchema,
179
371
  AnnotationEventSchema,
180
- SurfaceSnapshotEventSchema
372
+ SurfaceSnapshotEventSchema,
373
+ ResourceListStartEventSchema,
374
+ ResourceListEndEventSchema,
375
+ ResourceListErrorEventSchema,
376
+ ResourceReadStartEventSchema,
377
+ ResourceReadEndEventSchema,
378
+ ResourceReadErrorEventSchema,
379
+ PromptListStartEventSchema,
380
+ PromptListEndEventSchema,
381
+ PromptListErrorEventSchema,
382
+ PromptGetStartEventSchema,
383
+ PromptGetEndEventSchema,
384
+ PromptGetErrorEventSchema
181
385
  ]);
182
386
 
183
387
  // src/scrub.ts
@@ -472,6 +676,7 @@ var HttpSink = class _HttpSink {
472
676
  };
473
677
 
474
678
  // src/integrations/mcp/withBaton.ts
679
+ var import_node_async_hooks = require("async_hooks");
475
680
  var import_uuid2 = require("uuid");
476
681
 
477
682
  // src/integrations/mcp/annotation.ts
@@ -526,6 +731,11 @@ function roundMetaCoordinates(meta) {
526
731
  var import_node_crypto = require("crypto");
527
732
 
528
733
  // src/_text.ts
734
+ function exceedsCodePoints(value, max) {
735
+ if (value.length <= max) return false;
736
+ if (value.length > 2 * max) return true;
737
+ return [...value].length > max;
738
+ }
529
739
  function capCodePoints(value, max) {
530
740
  if (value.length <= max) return value;
531
741
  return [...value].slice(0, max).join("");
@@ -536,6 +746,13 @@ var PRINCIPAL_SOURCE_ASSERTED = "asserted";
536
746
  var PRINCIPAL_FORM_HASHED = "hashed";
537
747
  var PRINCIPAL_FORM_RAW = "raw";
538
748
  var RAW_PRINCIPAL_ID_MAX_LEN = 128;
749
+ var DISPLAY_NAME_MAX_LEN = 128;
750
+ var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
751
+ function wireDisplayName(value) {
752
+ if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
753
+ if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
754
+ return value;
755
+ }
539
756
  var PRINCIPAL_ID_MODE_HASHED = "hashed";
540
757
  var PRINCIPAL_ID_MODE_RAW = "raw";
541
758
  var FORM_BY_MODE = {
@@ -571,7 +788,7 @@ function normalizePrincipal(result) {
571
788
  if (canonicalize(candidate.principalId) === "") return null;
572
789
  const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
573
790
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
574
- return { principalId: candidate.principalId, issuer };
791
+ return typeof candidate.displayName === "string" ? { principalId: candidate.principalId, issuer, displayName: candidate.displayName } : { principalId: candidate.principalId, issuer };
575
792
  }
576
793
  function principalFor(principal, options) {
577
794
  let id;
@@ -585,7 +802,14 @@ function principalFor(principal, options) {
585
802
  issuer: principal.issuer ?? null
586
803
  });
587
804
  }
588
- return { id, source: PRINCIPAL_SOURCE_ASSERTED, form: FORM_BY_MODE[options.mode] };
805
+ const wire = {
806
+ id,
807
+ source: PRINCIPAL_SOURCE_ASSERTED,
808
+ form: FORM_BY_MODE[options.mode]
809
+ };
810
+ const displayName = wireDisplayName(principal.displayName);
811
+ if (displayName !== null) wire.display_name = displayName;
812
+ return wire;
589
813
  }
590
814
 
591
815
  // src/integrations/mcp/llmText.ts
@@ -746,6 +970,10 @@ async function emit(sink, build) {
746
970
  }
747
971
 
748
972
  // src/integrations/mcp/mcpTypes.ts
973
+ function extraAuthInfo(extra) {
974
+ const found = extra.authInfo ?? extra.http?.authInfo;
975
+ return found !== null && typeof found === "object" ? found : null;
976
+ }
749
977
  function extraMeta(extra) {
750
978
  const direct = extra._meta;
751
979
  if (direct) return direct;
@@ -790,7 +1018,8 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
790
1018
  headers: extraHeaders(extra),
791
1019
  meta: extraMeta(extra),
792
1020
  toolName,
793
- arguments: args
1021
+ arguments: args,
1022
+ authInfo: extraAuthInfo(extra)
794
1023
  };
795
1024
  }
796
1025
  function warnIfIdentityCannotResolve(config) {
@@ -837,6 +1066,24 @@ async function resolveCallPrincipal(hook, call, options) {
837
1066
  }
838
1067
  }
839
1068
 
1069
+ // src/integrations/mcp/safeScrub.ts
1070
+ var warned = /* @__PURE__ */ new Set();
1071
+ function scrubOrNull(scrubber, value, field) {
1072
+ if (value === null) return null;
1073
+ try {
1074
+ return scrubber(value);
1075
+ } catch (err) {
1076
+ if (!warned.has(field)) {
1077
+ warned.add(field);
1078
+ process.stderr.write(
1079
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${String(err)}
1080
+ `
1081
+ );
1082
+ }
1083
+ return null;
1084
+ }
1085
+ }
1086
+
840
1087
  // src/integrations/mcp/runtimeAdapter.ts
841
1088
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
842
1089
  var CLIENT_NAME_MAX_LEN = 128;
@@ -845,7 +1092,7 @@ function clean(name, scrubber) {
845
1092
  if (typeof name !== "string" || !name) return null;
846
1093
  let cleaned = name;
847
1094
  if (scrubber) {
848
- const scrubbed = scrubber(cleaned);
1095
+ const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
849
1096
  if (typeof scrubbed !== "string") return null;
850
1097
  cleaned = scrubbed;
851
1098
  }
@@ -921,7 +1168,11 @@ function registerAnnotationTool(server, options) {
921
1168
  server,
922
1169
  scrubber: options.scrubber
923
1170
  }) ?? UNKNOWN_AGENT_RUNTIME;
924
- const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
1171
+ const scrubbedMeta = scrubOrNull(
1172
+ options.scrubber,
1173
+ meta ? roundMetaCoordinates(meta) : null,
1174
+ "_meta"
1175
+ );
925
1176
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
926
1177
  if (args.signal_type === void 0) {
927
1178
  options.tracker?.mark(sessionId);
@@ -952,6 +1203,7 @@ function registerAnnotationTool(server, options) {
952
1203
  // Agent-facing names -> wire keys, as with `overall_task`
953
1204
  // below: `user_goal` is stored as `intent`, `expected_result` as
954
1205
  // `expected_outcome`.
1206
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
955
1207
  intent: options.scrubber(args.user_goal),
956
1208
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
957
1209
  // `signal_type` is a closed enum — nothing to scrub. The task label
@@ -966,8 +1218,10 @@ function registerAnnotationTool(server, options) {
966
1218
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
967
1219
  // split the injected params use (`overall_task` -> `call_workflow`):
968
1220
  // renaming the param must not move the key the console groups on.
1221
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
969
1222
  workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
970
1223
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1224
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
971
1225
  context: args.context ? options.scrubber(args.context) : null
972
1226
  }
973
1227
  })
@@ -1182,8 +1436,68 @@ function sealKey(dsn) {
1182
1436
  return dsn;
1183
1437
  }
1184
1438
 
1439
+ // src/integrations/mcp/errorResult.ts
1440
+ var TOOL_ERROR_TYPE = "tool_error";
1441
+ var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
1442
+ var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
1443
+ function requestSideFailureKind(entry) {
1444
+ if (entry == null) return "unknown_tool";
1445
+ if (entry.enabled === false) return "tool_disabled";
1446
+ return TASK_MODES.has(entry.execution?.taskSupport) ? void 0 : "invalid_argument";
1447
+ }
1448
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1449
+ function isErrorResult(value) {
1450
+ try {
1451
+ if (typeof value !== "object" || value === null) return false;
1452
+ return Boolean(value.isError);
1453
+ } catch {
1454
+ return false;
1455
+ }
1456
+ }
1457
+ function errorText(value) {
1458
+ const parts = [];
1459
+ try {
1460
+ const content = value?.content;
1461
+ if (!Array.isArray(content)) return "";
1462
+ for (const part of content) {
1463
+ const text = part?.text;
1464
+ if (typeof text !== "string") continue;
1465
+ const trimmed = text.trim();
1466
+ if (trimmed) parts.push(trimmed);
1467
+ }
1468
+ } catch {
1469
+ return "";
1470
+ }
1471
+ return parts.join("\n");
1472
+ }
1473
+ var RESULT_CAPTURE_MODES = ["full", "off"];
1474
+ var WITHHELD = "off";
1475
+ function endResultFields(mode, result, scrubber) {
1476
+ switch (mode) {
1477
+ case WITHHELD:
1478
+ return { result: null, result_capture: WITHHELD };
1479
+ case "full":
1480
+ return { result: scrubber(result) };
1481
+ }
1482
+ }
1483
+ function returnedErrorFields(mode, result, errorBody2, scrubber) {
1484
+ return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
1485
+ }
1486
+ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1487
+ switch (mode) {
1488
+ case WITHHELD:
1489
+ return { error_body: "", result: null, result_capture: WITHHELD };
1490
+ case "full":
1491
+ return { error_body: errorBody2(text()), result: scrubber(result) };
1492
+ }
1493
+ }
1494
+ function requestSideErrorFields(text, errorBody2) {
1495
+ return { error_body: errorBody2(text), result: null };
1496
+ }
1497
+
1185
1498
  // src/integrations/mcp/config.ts
1186
1499
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1500
+ var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1187
1501
  var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1188
1502
  function resolveTenantId(explicit, vendorId) {
1189
1503
  if (explicit) return explicit;
@@ -1294,6 +1608,14 @@ function validateBatonConfig(config) {
1294
1608
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1295
1609
  );
1296
1610
  }
1611
+ if (config.resultCaptureMode !== void 0 && !RESULT_CAPTURE_MODE_SET.has(config.resultCaptureMode)) {
1612
+ throw new Error(
1613
+ `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
1614
+ );
1615
+ }
1616
+ if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
1617
+ throw new Error("BatonConfig.scrubber must be a function.");
1618
+ }
1297
1619
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1298
1620
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1299
1621
  }
@@ -1339,34 +1661,6 @@ var DisabledSink = class {
1339
1661
  }
1340
1662
  };
1341
1663
 
1342
- // src/integrations/mcp/errorResult.ts
1343
- var TOOL_ERROR_TYPE = "tool_error";
1344
- var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1345
- function isErrorResult(value) {
1346
- try {
1347
- if (typeof value !== "object" || value === null) return false;
1348
- return Boolean(value.isError);
1349
- } catch {
1350
- return false;
1351
- }
1352
- }
1353
- function errorText(value) {
1354
- const parts = [];
1355
- try {
1356
- const content = value?.content;
1357
- if (!Array.isArray(content)) return "";
1358
- for (const part of content) {
1359
- const text = part?.text;
1360
- if (typeof text !== "string") continue;
1361
- const trimmed = text.trim();
1362
- if (trimmed) parts.push(trimmed);
1363
- }
1364
- } catch {
1365
- return "";
1366
- }
1367
- return parts.join("\n");
1368
- }
1369
-
1370
1664
  // src/integrations/mcp/handle.ts
1371
1665
  var BatonHandle = class {
1372
1666
  sink;
@@ -1620,6 +1914,8 @@ function buildSeamAugmentations(options) {
1620
1914
  // src/integrations/mcp/withBaton.ts
1621
1915
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
1622
1916
  var wired = /* @__PURE__ */ new WeakSet();
1917
+ var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1918
+ var callSlots = new import_node_async_hooks.AsyncLocalStorage();
1623
1919
  var SurfaceState = class {
1624
1920
  constructor(serverMeta) {
1625
1921
  this.serverMeta = serverMeta;
@@ -1674,105 +1970,137 @@ var SurfaceState = class {
1674
1970
  function errorBody(ctx, text) {
1675
1971
  return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1676
1972
  }
1677
- function batonWrap(nameRef, original, ctx) {
1678
- return async (...callArgs) => {
1679
- const toolName = nameRef.current;
1680
- await maybeEmitSurfaceSnapshot(ctx);
1681
- const extra = callArgs[callArgs.length - 1];
1682
- const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1683
- const meta = extraMeta(extra);
1684
- const runtime = detectAgentRuntime(meta, {
1685
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1686
- // `_meta`; 1.x leaves them in. Both are handed over — see
1687
- // `mcpTypes.extraEnvelope`.
1688
- envelope: extraEnvelope(extra),
1689
- // Tier 2's carrier: neither peer puts client identity on the
1690
- // handler context, both expose the cached handshake on the server.
1691
- server: ctx.server,
1692
- scrubber: ctx.scrubber
1693
- }) ?? UNKNOWN_AGENT_RUNTIME;
1694
- const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
1695
- const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1696
- const dispositions = ctx.paramRegistry.get(toolName);
1697
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1698
- const rawExpected = extractGoalParam(
1699
- params,
1700
- EXPECTED_RESULT_PARAM_NAME,
1701
- toolName,
1702
- dispositions
1703
- );
1704
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);
1705
- const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1706
- const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1707
- const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1708
- const callId = (0, import_uuid2.v7)();
1709
- const principal = await resolveCallPrincipal(
1710
- ctx.resolvePrincipal,
1711
- { extra, toolName, arguments: params },
1712
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1713
- );
1714
- const common = {
1715
- tenant_id: ctx.tenantId,
1716
- vendor_id: ctx.vendorId,
1717
- session_id: sessionId,
1718
- consent_token: ctx.consentToken,
1719
- agent_runtime: runtime,
1720
- // The five `...common` sites below are the tool-call legs — start, end,
1721
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1722
- // annotation, the same five Python stamps (`middleware.py`
1723
- // 503/547/586/644/674; it was four until the returned shape landed
1724
- // there too). `surface_snapshot` is deliberately NOT among them: it
1725
- // describes the SERVER and is captured outside any call, so there is no
1726
- // caller to name (register D5).
1727
- principal,
1728
- // Same five stamps, same exclusion: a surface_snapshot describes the
1729
- // SERVER and is captured outside any call, so it has no caller's
1730
- // transport to name any more than it has a caller to name.
1731
- transport_observed: observeTransport(extra),
1732
- runtime_meta: scrubbedMeta
1733
- };
1734
- if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1735
- await emit(
1736
- ctx.sink,
1737
- () => AnnotationEventSchema.parse({
1738
- ...common,
1739
- sequence_number: ctx.counter.next(sessionId),
1740
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1741
- payload: {
1742
- intent: scrubbedIntent,
1743
- expected_outcome: scrubbedExpected,
1744
- intent_source: INTENT_SOURCE_PARAM,
1745
- tool_name: toolName
1746
- }
1747
- })
1748
- );
1749
- }
1973
+ function errorTypeOf(err) {
1974
+ return err instanceof Error ? err.constructor.name : "Error";
1975
+ }
1976
+ function messageOf(err) {
1977
+ return err instanceof Error ? err.message : String(err);
1978
+ }
1979
+ async function resolveEnvelopeParts(ctx, extra) {
1980
+ const meta = extraMeta(extra);
1981
+ const runtime = detectAgentRuntime(meta, {
1982
+ // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1983
+ // `_meta`; 1.x leaves them in. Both are handed over — see
1984
+ // `mcpTypes.extraEnvelope`.
1985
+ envelope: extraEnvelope(extra),
1986
+ // Tier 2's carrier: neither peer puts client identity on the
1987
+ // handler context, both expose the cached handshake on the server.
1988
+ server: ctx.server,
1989
+ scrubber: ctx.scrubber
1990
+ }) ?? UNKNOWN_AGENT_RUNTIME;
1991
+ const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1992
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1993
+ return { sessionId, runtime, scrubbedMeta };
1994
+ }
1995
+ async function openCall(ctx, toolName, extra, params, registered = true) {
1996
+ await maybeEmitSurfaceSnapshot(ctx);
1997
+ const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1998
+ const dispositions = ctx.paramRegistry.get(toolName);
1999
+ const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2000
+ const rawExpected = extractGoalParam(
2001
+ params,
2002
+ EXPECTED_RESULT_PARAM_NAME,
2003
+ toolName,
2004
+ dispositions,
2005
+ registered
2006
+ );
2007
+ const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
2008
+ const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2009
+ const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
2010
+ const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
2011
+ const callId = (0, import_uuid2.v7)();
2012
+ const principal = await resolveCallPrincipal(
2013
+ ctx.resolvePrincipal,
2014
+ { extra, toolName, arguments: params },
2015
+ { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
2016
+ );
2017
+ const common = {
2018
+ tenant_id: ctx.tenantId,
2019
+ vendor_id: ctx.vendorId,
2020
+ session_id: sessionId,
2021
+ consent_token: ctx.consentToken,
2022
+ agent_runtime: runtime,
2023
+ // The five `...common` sites below are the tool-call legs — start, end,
2024
+ // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
2025
+ // annotation, the same five Python stamps (`middleware.py`
2026
+ // 503/547/586/644/674; it was four until the returned shape landed
2027
+ // there too). `surface_snapshot` is deliberately NOT among them: it
2028
+ // describes the SERVER and is captured outside any call, so there is no
2029
+ // caller to name (register D5).
2030
+ principal,
2031
+ // Same five stamps, same exclusion: a surface_snapshot describes the
2032
+ // SERVER and is captured outside any call, so it has no caller's
2033
+ // transport to name any more than it has a caller to name.
2034
+ transport_observed: observeTransport(extra),
2035
+ runtime_meta: scrubbedMeta
2036
+ };
2037
+ if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1750
2038
  await emit(
1751
2039
  ctx.sink,
1752
- () => ToolCallStartEventSchema.parse({
2040
+ () => AnnotationEventSchema.parse({
1753
2041
  ...common,
1754
- call_id: callId,
1755
2042
  sequence_number: ctx.counter.next(sessionId),
1756
2043
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1757
2044
  payload: {
1758
- tool_name: toolName,
1759
- params: ctx.scrubber(params),
1760
- call_intent: scrubbedIntent,
1761
- call_expected: scrubbedExpected,
1762
- call_workflow: scrubbedWorkflow,
1763
- intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
2045
+ intent: scrubbedIntent,
2046
+ expected_outcome: scrubbedExpected,
2047
+ intent_source: INTENT_SOURCE_PARAM,
2048
+ tool_name: toolName
1764
2049
  }
1765
2050
  })
1766
2051
  );
2052
+ }
2053
+ await emit(
2054
+ ctx.sink,
2055
+ () => ToolCallStartEventSchema.parse({
2056
+ ...common,
2057
+ call_id: callId,
2058
+ sequence_number: ctx.counter.next(sessionId),
2059
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2060
+ payload: {
2061
+ tool_name: toolName,
2062
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for params
2063
+ params: ctx.scrubber(params),
2064
+ call_intent: scrubbedIntent,
2065
+ call_expected: scrubbedExpected,
2066
+ call_workflow: scrubbedWorkflow,
2067
+ intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
2068
+ }
2069
+ })
2070
+ );
2071
+ return { common, callId, sessionId };
2072
+ }
2073
+ function batonWrap(nameRef, original, ctx) {
2074
+ return async (...callArgs) => {
2075
+ const toolName = nameRef.current;
2076
+ const slot = callSlots.getStore();
2077
+ if (slot) slot.innerFired = true;
2078
+ const extra = callArgs[callArgs.length - 1];
2079
+ const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2080
+ const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);
2081
+ const terminate = async (build, replacement) => {
2082
+ if (!slot) {
2083
+ await emit(ctx.sink, build);
2084
+ return;
2085
+ }
2086
+ const earlier = slot.flushTerminal;
2087
+ if (earlier !== null) await earlier(CLEAN_OUTCOME);
2088
+ slot.flushTerminal = async (outcome) => {
2089
+ await emit(
2090
+ ctx.sink,
2091
+ () => replacement !== null && outcome.failed ? replacement(outcome) : build()
2092
+ );
2093
+ };
2094
+ };
2095
+ const parkFailure = (build) => terminate(build, null);
2096
+ const parkSuccess = (build, replacement) => terminate(build, replacement);
1767
2097
  const startedAt = performance.now();
1768
2098
  let result;
1769
2099
  try {
1770
2100
  result = await original(...callArgs);
1771
2101
  } catch (err) {
1772
2102
  const durationMs2 = Math.round(performance.now() - startedAt);
1773
- const message = err instanceof Error ? err.message : String(err);
1774
- await emit(
1775
- ctx.sink,
2103
+ await parkFailure(
1776
2104
  () => ToolCallErrorEventSchema.parse({
1777
2105
  ...common,
1778
2106
  call_id: callId,
@@ -1780,17 +2108,26 @@ function batonWrap(nameRef, original, ctx) {
1780
2108
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1781
2109
  payload: {
1782
2110
  tool_name: toolName,
1783
- error_type: err instanceof Error ? err.constructor.name : "Error",
1784
- error_body: errorBody(ctx, message),
2111
+ error_type: errorTypeOf(err),
2112
+ // ⚠ KEPT under `resultCaptureMode: "off"`, and that is the rule's
2113
+ // shape rather than an exception to it: the rule is keyed on
2114
+ // PROVENANCE, and a thrown error's message is the vendor's own
2115
+ // code speaking about a call that returned nothing (SPEC
2116
+ // §11.4.3(1)). A switch written as "drop `error_body`" would
2117
+ // delete the highest-value diagnostic the product has.
2118
+ error_body: errorBody(ctx, messageOf(err)),
1785
2119
  duration_ms: durationMs2,
1786
2120
  // Explicit, though the field is `.optional()` and this is its
1787
2121
  // absent value. The schema is deliberately not an emitter (see
1788
2122
  // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1789
- // key would be missing — and Python's `tool_call_error` vector
1790
- // carries `result: null`, so the cross-SDK key-set check in
1791
- // `emitterConformance.test.ts` is what would say so. Each of the
1792
- // two failure shapes declares which it is, the same reason
1793
- // Python's emitter made the parameter positional-without-default.
2123
+ // key would be missing. Each of the two failure shapes declares
2124
+ // which it is, the same reason Python's emitter made the parameter
2125
+ // positional-without-default.
2126
+ //
2127
+ // ⚠ Guarded by `errorResult.test.ts`'s `toContain("result")`, NOT by
2128
+ // the cross-SDK key-set check — measured by removing this line. Why,
2129
+ // at one site: `endResultFields` in `errorResult.ts`. SPEC §11.4.3
2130
+ // states the same void rationale and wants the same amendment.
1794
2131
  result: null
1795
2132
  }
1796
2133
  })
@@ -1799,8 +2136,7 @@ function batonWrap(nameRef, original, ctx) {
1799
2136
  }
1800
2137
  const durationMs = Math.round(performance.now() - startedAt);
1801
2138
  if (isErrorResult(result)) {
1802
- await emit(
1803
- ctx.sink,
2139
+ await parkFailure(
1804
2140
  () => ToolCallErrorEventSchema.parse({
1805
2141
  ...common,
1806
2142
  call_id: callId,
@@ -1809,36 +2145,105 @@ function batonWrap(nameRef, original, ctx) {
1809
2145
  payload: {
1810
2146
  tool_name: toolName,
1811
2147
  error_type: TOOL_ERROR_TYPE,
1812
- error_body: errorBody(ctx, errorText(result)),
1813
2148
  duration_ms: durationMs,
1814
- // The whole envelope. ⚠ On this producer that is the same shape
1815
- // `tool_call_end.result` records, which is NOT what Python's
1816
- // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1817
- // holds that claim and names the test that enforces it.
1818
- result: ctx.scrubber(result)
2149
+ // Both remaining members are unwrapped FROM the result on this
2150
+ // shape, so one projection decides them together and owns the
2151
+ // scrubber call. `error_type` is NOT result-derived and is passed
2152
+ // regardless: the call still failed (SPEC §11.2.6).
2153
+ //
2154
+ // ⚠ Under `"full"` `result` is the whole envelope, and on this
2155
+ // producer that is the same shape `tool_call_end.result` records —
2156
+ // which is NOT what Python's contrast says.
2157
+ // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
2158
+ // names the test that enforces it.
2159
+ ...returnedErrorFields(
2160
+ ctx.resultCaptureMode,
2161
+ result,
2162
+ (text) => errorBody(ctx, text),
2163
+ ctx.scrubber
2164
+ )
1819
2165
  }
1820
2166
  })
1821
2167
  );
1822
2168
  return result;
1823
2169
  }
1824
- await emit(
1825
- ctx.sink,
2170
+ await parkSuccess(
1826
2171
  () => ToolCallEndEventSchema.parse({
1827
2172
  ...common,
1828
2173
  call_id: callId,
1829
2174
  sequence_number: ctx.counter.next(sessionId),
1830
2175
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1831
- payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
2176
+ payload: {
2177
+ tool_name: toolName,
2178
+ duration_ms: durationMs,
2179
+ ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
2180
+ }
2181
+ }),
2182
+ // The handler returned something this sensor reads as a success, and
2183
+ // then the outer seam saw the call fail anyway — so what failed is the
2184
+ // producer's own conversion of the output (SPEC §11.4.3's
2185
+ // `output_schema_mismatch`). Correcting this is the whole point of the
2186
+ // second seam: without it this is a `tool_call_end` for a call the
2187
+ // CALLER saw fail, which is a success the product invented.
2188
+ (outcome) => ToolCallErrorEventSchema.parse({
2189
+ ...common,
2190
+ call_id: callId,
2191
+ sequence_number: ctx.counter.next(sessionId),
2192
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2193
+ payload: {
2194
+ tool_name: toolName,
2195
+ // The lane the OUTER came back on, not this one's: on 2.x the
2196
+ // conversion failure is converted to a returned `isError` inside
2197
+ // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2198
+ // right there. A throw out of the handler is unreachable on
2199
+ // either major today for this lane; spelled anyway, because the
2200
+ // alternative is a crash on the day it stops being.
2201
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2202
+ // ⚠ The INNER's measurement — the vendor's handler duration —
2203
+ // not the outer's. Every other leg means the same thing by this
2204
+ // member, and widening it here for one failure kind would make
2205
+ // `duration_ms` mean two things in one column.
2206
+ duration_ms: durationMs,
2207
+ failure_kind: OUTPUT_SCHEMA_MISMATCH,
2208
+ // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2209
+ // kinds.** The message quotes the value the tool returned
2210
+ // ("`'not-an-int'` is not of type `integer`"), so it is
2211
+ // result-derived by provenance and goes — which leaves
2212
+ // `failure_kind` as the ONLY surviving signal for this failure
2213
+ // under `"off"`, and is the measurement that justified putting
2214
+ // the member on the wire at all.
2215
+ //
2216
+ // ⚠ `result` is what the CLIENT received — the SDK's own error
2217
+ // envelope — not the vendor's rejected return value. §11.4.3
2218
+ // asks for the envelope that holds the flag and the reason, and
2219
+ // this package's own invariant is that it agrees with the
2220
+ // caller. Recording the rejected output TOO would need a member
2221
+ // nothing on the wire has; the loss is deliberate and worth
2222
+ // knowing when debugging one of these.
2223
+ ...resultDerivedFields(
2224
+ ctx.resultCaptureMode,
2225
+ () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2226
+ // ⚠ `null` on the `raised` lane, never `undefined`, and the
2227
+ // union is what forces the branch rather than a comment: the
2228
+ // scrubber would answer `undefined` and DROP the key, where the
2229
+ // sibling raise lane a few lines up declares `result: null`
2230
+ // explicitly, for the reason `ToolCallErrorPayloadSchema`
2231
+ // records. One shape for "no result object existed", not two.
2232
+ outcome.raised ? null : outcome.result ?? null,
2233
+ (text) => errorBody(ctx, text),
2234
+ ctx.scrubber
2235
+ )
2236
+ }
1832
2237
  })
1833
2238
  );
1834
2239
  return result;
1835
2240
  };
1836
2241
  }
1837
- function extractGoalParam(args, paramName, toolName, dispositions) {
2242
+ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
1838
2243
  if (!(paramName in args)) return null;
1839
2244
  const disposition = dispositions ? dispositions[paramName] : void 0;
1840
2245
  if (disposition === "native") return null;
1841
- if (disposition === void 0) {
2246
+ if (disposition === void 0 && registered) {
1842
2247
  process.stderr.write(
1843
2248
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
1844
2249
  `
@@ -1897,12 +2302,29 @@ function captureAndInject(name, entry, ctx) {
1897
2302
  }
1898
2303
  var TOOLS_LIST_METHOD = "tools/list";
1899
2304
  var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
1900
- function installToolsListSeam(lowLevel, ctx) {
2305
+ var TOOLS_CALL_METHOD = "tools/call";
2306
+ var TOOLS_CALL_SEAM = /* @__PURE__ */ Symbol("batonToolsCallSeam");
2307
+ function installRequestSeam(lowLevel, method, seamTag, wrap) {
1901
2308
  const table = lowLevel._requestHandlers;
1902
2309
  const originalSet = lowLevel.setRequestHandler;
1903
2310
  if (!(table instanceof Map) || typeof originalSet !== "function") return;
1904
2311
  const handlers = table;
1905
2312
  const setRequestHandler = originalSet;
2313
+ const wrapCurrent = () => {
2314
+ const handler = handlers.get(method);
2315
+ if (typeof handler !== "function" || handler[seamTag]) return;
2316
+ const seamed = wrap(handler);
2317
+ seamed[seamTag] = true;
2318
+ handlers.set(method, seamed);
2319
+ };
2320
+ wrapCurrent();
2321
+ lowLevel.setRequestHandler = (...args) => {
2322
+ const registered = setRequestHandler.apply(lowLevel, args);
2323
+ wrapCurrent();
2324
+ return registered;
2325
+ };
2326
+ }
2327
+ function installToolsListSeam(lowLevel, ctx) {
1906
2328
  const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
1907
2329
  const advertise = (result) => {
1908
2330
  try {
@@ -1915,22 +2337,273 @@ function installToolsListSeam(lowLevel, ctx) {
1915
2337
  return result;
1916
2338
  }
1917
2339
  };
1918
- const wrapCurrent = () => {
1919
- const handler = handlers.get(TOOLS_LIST_METHOD);
1920
- if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
1921
- const seamed = (...args) => {
1922
- const out = handler(...args);
1923
- return isThenable(out) ? out.then(advertise) : advertise(out);
2340
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {
2341
+ const out = handler(...args);
2342
+ return isThenable(out) ? out.then(advertise) : advertise(out);
2343
+ });
2344
+ }
2345
+ var LIFECYCLE_SEAMS = {
2346
+ resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2347
+ resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2348
+ promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2349
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2350
+ };
2351
+ function installLifecycleSeam(lowLevel, ctx, spec) {
2352
+ installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
2353
+ const request = args[0];
2354
+ const requestParams = request?.params ?? {};
2355
+ const extra = args[1];
2356
+ const opened = await openLifecycleCall(ctx, spec, requestParams, extra);
2357
+ const fire = async (schema, payload) => {
2358
+ if (opened === null) return;
2359
+ await emit(
2360
+ ctx.sink,
2361
+ () => schema.parse({
2362
+ ...opened.common,
2363
+ sequence_number: ctx.counter.next(opened.sessionId),
2364
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2365
+ payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
2366
+ })
2367
+ );
1924
2368
  };
1925
- seamed[TOOLS_LIST_SEAM] = true;
1926
- handlers.set(TOOLS_LIST_METHOD, seamed);
1927
- };
1928
- wrapCurrent();
1929
- lowLevel.setRequestHandler = (...args) => {
1930
- const registered = setRequestHandler.apply(lowLevel, args);
1931
- wrapCurrent();
1932
- return registered;
1933
- };
2369
+ await fire(spec.schemas.start, spec.startParams(requestParams));
2370
+ const startedAt = performance.now();
2371
+ const elapsed = () => Math.round(performance.now() - startedAt);
2372
+ try {
2373
+ const result = await handler(...args);
2374
+ await fire(spec.schemas.end, {
2375
+ ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
2376
+ duration_ms: elapsed()
2377
+ });
2378
+ return result;
2379
+ } catch (err) {
2380
+ await fire(spec.schemas.error, {
2381
+ error_type: errorTypeOf(err),
2382
+ // KEPT under every capture mode: a failed FETCH's message is the
2383
+ // producer's own diagnostic, not anything a resource returned, so
2384
+ // nothing here is result-derived (SPEC §11.4.4). The scrub and the cap
2385
+ // are `scrubLifecyclePayload`'s, in that order.
2386
+ error_body: messageOf(err),
2387
+ duration_ms: elapsed()
2388
+ });
2389
+ throw err;
2390
+ }
2391
+ });
2392
+ }
2393
+ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2394
+ try {
2395
+ const parts = await resolveEnvelopeParts(ctx, extra);
2396
+ return {
2397
+ sessionId: parts.sessionId,
2398
+ subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
2399
+ common: {
2400
+ tenant_id: ctx.tenantId,
2401
+ vendor_id: ctx.vendorId,
2402
+ session_id: parts.sessionId,
2403
+ consent_token: ctx.consentToken,
2404
+ agent_runtime: parts.runtime,
2405
+ transport_observed: observeTransport(extra),
2406
+ runtime_meta: parts.scrubbedMeta
2407
+ }
2408
+ };
2409
+ } catch (err) {
2410
+ process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
2411
+ `);
2412
+ return null;
2413
+ }
2414
+ }
2415
+ var NO_PARAMS = () => EMPTY_PARAMS;
2416
+ var EMPTY_PARAMS = Object.freeze({});
2417
+ var LIFECYCLE_SPECS = [
2418
+ {
2419
+ method: "resources/list",
2420
+ seamTag: LIFECYCLE_SEAMS.resourceList,
2421
+ schemas: {
2422
+ start: ResourceListStartEventSchema,
2423
+ end: ResourceListEndEventSchema,
2424
+ error: ResourceListErrorEventSchema
2425
+ },
2426
+ // ⚠ `resources` ALONE. Resource TEMPLATES are a separate MCP method with
2427
+ // their own result array and are deliberately not added in, matching the
2428
+ // proxy — so a template-only server reports 0, which §11.4.4 says a
2429
+ // consumer MUST NOT read as "this server has no resources".
2430
+ countKey: "resources",
2431
+ startParams: NO_PARAMS
2432
+ },
2433
+ {
2434
+ method: "resources/read",
2435
+ seamTag: LIFECYCLE_SEAMS.resourceRead,
2436
+ schemas: {
2437
+ start: ResourceReadStartEventSchema,
2438
+ end: ResourceReadEndEventSchema,
2439
+ error: ResourceReadErrorEventSchema
2440
+ },
2441
+ subjectKey: "uri",
2442
+ // ⚠ The whole params bag MINUS `_meta`, so `uri` lands here as well as in
2443
+ // its own member. That duplication is the proxy's and is reproduced on
2444
+ // purpose: the dedicated member is what a consumer reads, the bag is what
2445
+ // the caller actually sent, and a producer that stripped `uri` out could no
2446
+ // longer say the second thing. `_meta` is excluded because it rides the
2447
+ // envelope as `runtime_meta` already.
2448
+ startParams: (params) => ({ params: paramsBag(params) })
2449
+ },
2450
+ {
2451
+ method: "prompts/list",
2452
+ seamTag: LIFECYCLE_SEAMS.promptList,
2453
+ schemas: {
2454
+ start: PromptListStartEventSchema,
2455
+ end: PromptListEndEventSchema,
2456
+ error: PromptListErrorEventSchema
2457
+ },
2458
+ countKey: "prompts",
2459
+ startParams: NO_PARAMS
2460
+ },
2461
+ {
2462
+ method: "prompts/get",
2463
+ seamTag: LIFECYCLE_SEAMS.promptGet,
2464
+ schemas: {
2465
+ start: PromptGetStartEventSchema,
2466
+ end: PromptGetEndEventSchema,
2467
+ error: PromptGetErrorEventSchema
2468
+ },
2469
+ subjectKey: "name",
2470
+ // ⚠ `arguments` ALONE, NOT the whole bag — the opposite of the resource
2471
+ // read above, so `name` does NOT appear inside `params`. The two are
2472
+ // inconsistent in the producer the shapes came from; the inconsistency is
2473
+ // reproduced rather than tidied, because a consumer reading one producer
2474
+ // and a second producer reading the other must agree.
2475
+ startParams: (params) => ({
2476
+ params: paramsBag(params["arguments"])
2477
+ })
2478
+ }
2479
+ ];
2480
+ function installLifecycleSeams(lowLevel, ctx) {
2481
+ for (const spec of LIFECYCLE_SPECS) installLifecycleSeam(lowLevel, ctx, spec);
2482
+ }
2483
+ function stringSubject(value) {
2484
+ return typeof value === "string" ? value : "";
2485
+ }
2486
+ function countOf(result, key) {
2487
+ const list = result?.[key];
2488
+ return Array.isArray(list) ? list.length : 0;
2489
+ }
2490
+ function paramsBag(bag) {
2491
+ if (!bag || typeof bag !== "object") return {};
2492
+ const out = {};
2493
+ for (const key of Object.keys(bag)) {
2494
+ if (key !== "_meta") out[key] = bag[key];
2495
+ }
2496
+ return out;
2497
+ }
2498
+ function scrubLifecyclePayload(ctx, raw) {
2499
+ const scrubbed = ctx.scrubber(raw);
2500
+ const body = scrubbed?.["error_body"];
2501
+ if (typeof body !== "string") return scrubbed;
2502
+ return { ...scrubbed, error_body: capCodePoints(body, ERROR_BODY_MAX_CODE_POINTS) };
2503
+ }
2504
+ function dispatchSlot(entry) {
2505
+ if (typeof entry.executor === "function") return "executor";
2506
+ if (typeof entry.handler === "function") return "handler";
2507
+ return void 0;
2508
+ }
2509
+ function dispatchTarget(entry) {
2510
+ const slot = dispatchSlot(entry);
2511
+ return slot === void 0 ? void 0 : entry[slot];
2512
+ }
2513
+ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2514
+ installRequestSeam(
2515
+ lowLevel,
2516
+ TOOLS_CALL_METHOD,
2517
+ TOOLS_CALL_SEAM,
2518
+ (handler) => async (...args) => {
2519
+ const slot = { innerFired: false, flushTerminal: null };
2520
+ let outcome = CLEAN_OUTCOME;
2521
+ try {
2522
+ const result = await callSlots.run(slot, () => handler(...args));
2523
+ outcome = { failed: isErrorResult(result), raised: false, result };
2524
+ return result;
2525
+ } catch (err) {
2526
+ outcome = { failed: true, raised: true, err };
2527
+ throw err;
2528
+ } finally {
2529
+ await settleCall(slot, outcome, args, toolEntry, ctx);
2530
+ }
2531
+ }
2532
+ );
2533
+ }
2534
+ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2535
+ try {
2536
+ if (slot.flushTerminal !== null) {
2537
+ const flush = slot.flushTerminal;
2538
+ slot.flushTerminal = null;
2539
+ await flush(outcome);
2540
+ return;
2541
+ }
2542
+ if (slot.innerFired) return;
2543
+ if (!outcome.failed) return;
2544
+ await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2545
+ } catch (err) {
2546
+ process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2547
+ `);
2548
+ }
2549
+ }
2550
+ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2551
+ const request = args[0];
2552
+ const toolName = request?.params?.name;
2553
+ if (typeof toolName !== "string") return;
2554
+ if (toolName === ctx.annotationToolName) return;
2555
+ const entry = toolEntry(toolName);
2556
+ if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2557
+ const params = { ...request?.params?.arguments ?? {} };
2558
+ const { common, callId, sessionId } = await openCall(
2559
+ ctx,
2560
+ toolName,
2561
+ args[1],
2562
+ params,
2563
+ entry != null
2564
+ );
2565
+ const failureKind = requestSideFailureKind(entry);
2566
+ await emit(
2567
+ ctx.sink,
2568
+ () => ToolCallErrorEventSchema.parse({
2569
+ ...common,
2570
+ call_id: callId,
2571
+ sequence_number: ctx.counter.next(sessionId),
2572
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2573
+ payload: {
2574
+ tool_name: toolName,
2575
+ // The lane the SDK rejected on, which is NOT the same across majors
2576
+ // for one failure: 1.x converts all three to a returned `isError`
2577
+ // inside its own `try` (`mcp.js:101-108`), v2 THROWS the first two
2578
+ // and returns the third. So the same customer-visible failure is
2579
+ // `"tool_error"` on one major and `"ProtocolError"` on the other —
2580
+ // measured 2026-10-01, and deliberately not special-cased: this
2581
+ // member is §11.4.3's RAISE/RETURN discriminator and it is reporting
2582
+ // the shape faithfully. `failure_kind` is what makes the two
2583
+ // comparable, which is the member's whole justification.
2584
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2585
+ // ⚠ `null`, not 0. The vendor's handler never ran, so there is no
2586
+ // handler duration to report; the time this call did spend was spent
2587
+ // in the SDK's validator, which is not what any other event means by
2588
+ // this member. §11.4 types it nullable for cases like this one.
2589
+ duration_ms: null,
2590
+ // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
2591
+ // `.optional()` accepts `undefined` and keeps the KEY in its output,
2592
+ // so the plain form writes a present-but-undefined member — invisible
2593
+ // to a JSON-serialising sink and plainly visible to a vendor-supplied
2594
+ // one that iterates keys. SPEC §11.4.3 says a producer that cannot
2595
+ // determine the kind MUST OMIT the member, and omitting is what this
2596
+ // spells.
2597
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
2598
+ // KEPT under `"off"` — see `requestSideErrorFields`, which takes no
2599
+ // capture mode because nothing here is derived from a result.
2600
+ ...requestSideErrorFields(
2601
+ outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2602
+ (text) => errorBody(ctx, text)
2603
+ )
2604
+ }
2605
+ })
2606
+ );
1934
2607
  }
1935
2608
  function isThenable(value) {
1936
2609
  return typeof value?.then === "function";
@@ -1938,20 +2611,13 @@ function isThenable(value) {
1938
2611
  function wrapIfNeeded(nameRef, entry, ctx) {
1939
2612
  if (!entry || typeof entry !== "object") return;
1940
2613
  const mutable = entry;
1941
- if (typeof mutable.executor === "function") {
1942
- if (mutable.executor[BATON_WRAPPED]) return;
1943
- const originalExecutor = mutable.executor;
1944
- const wrapper2 = batonWrap(nameRef, originalExecutor, ctx);
1945
- wrapper2[BATON_WRAPPED] = true;
1946
- mutable.executor = wrapper2;
1947
- return;
1948
- }
1949
- if (typeof mutable.handler !== "function") return;
1950
- if (mutable.handler[BATON_WRAPPED]) return;
1951
- const original = mutable.handler;
1952
- const wrapper = batonWrap(nameRef, original, ctx);
2614
+ const slot = dispatchSlot(mutable);
2615
+ if (slot === void 0) return;
2616
+ const target = mutable[slot];
2617
+ if (target[BATON_WRAPPED]) return;
2618
+ const wrapper = batonWrap(nameRef, target, ctx);
1953
2619
  wrapper[BATON_WRAPPED] = true;
1954
- mutable.handler = wrapper;
2620
+ mutable[slot] = wrapper;
1955
2621
  }
1956
2622
  function wireEntry(name, entry, ctx) {
1957
2623
  if (name === ctx.annotationToolName) return;
@@ -2106,6 +2772,7 @@ function withBaton(server, supplied = {}) {
2106
2772
  scrubber,
2107
2773
  annotationToolName,
2108
2774
  intentParamMode,
2775
+ resultCaptureMode: config.resultCaptureMode ?? "full",
2109
2776
  paramRegistry: /* @__PURE__ */ new Map(),
2110
2777
  resolvePrincipal: config.resolvePrincipal,
2111
2778
  principalIdMode: config.principalIdMode ?? "hashed",
@@ -2123,6 +2790,22 @@ function withBaton(server, supplied = {}) {
2123
2790
  });
2124
2791
  internals.server._instructions = instructions;
2125
2792
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
2793
+ installToolsCallSeam(
2794
+ internals.server,
2795
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
2796
+ // object, so `registry["constructor"]` answers `Object` and
2797
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
2798
+ // so the "a tool we did not wrap" guard would decline to report, and a
2799
+ // caller-visible `Tool constructor disabled` would reach the client with
2800
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
2801
+ // exactly the kind of failure the seam exists to make visible.
2802
+ (name) => {
2803
+ const registry = internals._registeredTools;
2804
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
2805
+ },
2806
+ ctx
2807
+ );
2808
+ installLifecycleSeams(internals.server, ctx);
2126
2809
  const resolvedAnnotationToolName = registerAnnotationTool(server, {
2127
2810
  sink,
2128
2811
  counter: ctx.counter,
@@ -2166,6 +2849,38 @@ function withBaton(server, supplied = {}) {
2166
2849
  annotationToolName: resolvedAnnotationToolName
2167
2850
  });
2168
2851
  }
2852
+
2853
+ // src/integrations/mcp/oauthHooks.ts
2854
+ function claimsOf(context) {
2855
+ try {
2856
+ const extra = context.authInfo?.extra;
2857
+ return extra !== null && typeof extra === "object" ? extra : null;
2858
+ } catch {
2859
+ return null;
2860
+ }
2861
+ }
2862
+ function stringClaim(claims, name) {
2863
+ const value = claims[name];
2864
+ return typeof value === "string" && pythonStrip(value) !== "" ? value : null;
2865
+ }
2866
+ function principalFromOAuthSub(context) {
2867
+ const claims = claimsOf(context);
2868
+ if (claims === null) return null;
2869
+ const sub = stringClaim(claims, "sub");
2870
+ const iss = claims.iss;
2871
+ return sub === null ? null : { principalId: sub, issuer: typeof iss === "string" && iss !== "" ? iss : null };
2872
+ }
2873
+ function principalFromOAuthEmail(context) {
2874
+ const claims = claimsOf(context);
2875
+ if (claims === null) return null;
2876
+ const email = stringClaim(claims, "email");
2877
+ if (email === null) return null;
2878
+ const at = email.lastIndexOf("@");
2879
+ return {
2880
+ principalId: email,
2881
+ displayName: at > 0 ? email.slice(0, at) : null
2882
+ };
2883
+ }
2169
2884
  // Annotate the CommonJS export names for ESM import in node:
2170
2885
  0 && (module.exports = {
2171
2886
  AnnotationEventSchema,
@@ -2180,6 +2895,30 @@ function withBaton(server, supplied = {}) {
2180
2895
  PRINCIPAL_FORM_RAW,
2181
2896
  PRINCIPAL_SOURCE_ASSERTED,
2182
2897
  PrincipalWireSchema,
2898
+ PromptGetEndEventSchema,
2899
+ PromptGetEndPayloadSchema,
2900
+ PromptGetErrorEventSchema,
2901
+ PromptGetErrorPayloadSchema,
2902
+ PromptGetStartEventSchema,
2903
+ PromptGetStartPayloadSchema,
2904
+ PromptListEndEventSchema,
2905
+ PromptListEndPayloadSchema,
2906
+ PromptListErrorEventSchema,
2907
+ PromptListErrorPayloadSchema,
2908
+ PromptListStartEventSchema,
2909
+ PromptListStartPayloadSchema,
2910
+ ResourceListEndEventSchema,
2911
+ ResourceListEndPayloadSchema,
2912
+ ResourceListErrorEventSchema,
2913
+ ResourceListErrorPayloadSchema,
2914
+ ResourceListStartEventSchema,
2915
+ ResourceListStartPayloadSchema,
2916
+ ResourceReadEndEventSchema,
2917
+ ResourceReadEndPayloadSchema,
2918
+ ResourceReadErrorEventSchema,
2919
+ ResourceReadErrorPayloadSchema,
2920
+ ResourceReadStartEventSchema,
2921
+ ResourceReadStartPayloadSchema,
2183
2922
  SDK_VERSION,
2184
2923
  Scrubber,
2185
2924
  StdoutSink,
@@ -2193,6 +2932,8 @@ function withBaton(server, supplied = {}) {
2193
2932
  ToolCallStartPayloadSchema,
2194
2933
  hashPrincipalId,
2195
2934
  identityScrub,
2935
+ principalFromOAuthEmail,
2936
+ principalFromOAuthSub,
2196
2937
  safeWrite,
2197
2938
  withBaton
2198
2939
  });