@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.4.1";
2
+ var SDK_VERSION = "ts-0.5.1";
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),
@@ -61,7 +99,8 @@ var DEFAULT_CONSENT_TOKEN = "customer-consented";
61
99
  var PrincipalWireSchema = z.object({
62
100
  id: z.string(),
63
101
  source: z.string(),
64
- form: z.string()
102
+ form: z.string(),
103
+ display_name: z.string().nullable().optional()
65
104
  }).strict();
66
105
  var envelopeShape = {
67
106
  event_id: z.uuid().default(() => uuidv7()),
@@ -83,8 +122,75 @@ var EventTypeSchema = z.enum([
83
122
  "tool_call_end",
84
123
  "tool_call_error",
85
124
  "annotation",
86
- "surface_snapshot"
125
+ "surface_snapshot",
126
+ // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
127
+ // shapes were set by `baton-proxy`, which has been emitting all of them in
128
+ // production — see the payload schemas below.
129
+ "resource_list_start",
130
+ "resource_list_end",
131
+ "resource_list_error",
132
+ "resource_read_start",
133
+ "resource_read_end",
134
+ "resource_read_error",
135
+ "prompt_list_start",
136
+ "prompt_list_end",
137
+ "prompt_list_error",
138
+ "prompt_get_start",
139
+ "prompt_get_end",
140
+ "prompt_get_error"
87
141
  ]);
142
+ var timingShape = { duration_ms: z.number().int().nullable().default(null) };
143
+ var failureShape = { error_type: z.string(), error_body: z.string(), ...timingShape };
144
+ var ResourceListStartPayloadSchema = z.object({}).strict();
145
+ var ResourceListEndPayloadSchema = z.object({
146
+ count: z.number().int(),
147
+ ...timingShape
148
+ }).strict();
149
+ var ResourceListErrorPayloadSchema = z.object({
150
+ ...failureShape
151
+ }).strict();
152
+ var ResourceReadStartPayloadSchema = z.object({
153
+ uri: z.string(),
154
+ /** The caller's own request params, PII-scrubbed (SPEC §7).
155
+ *
156
+ * ⚠ Nullable because the SCHEMA permits it, not because this producer
157
+ * emits it: `withBaton`'s `paramsBag` answers `{}` for an absent bag,
158
+ * matching `baton-proxy` (`dict(params) if params else {}` — it never
159
+ * emits null). A consumer must still read both, since the schema admits
160
+ * both and a third producer may choose either. */
161
+ params: z.record(z.string(), z.unknown()).nullable().default(null)
162
+ }).strict();
163
+ var ResourceReadEndPayloadSchema = z.object({
164
+ uri: z.string(),
165
+ ...timingShape
166
+ }).strict();
167
+ var ResourceReadErrorPayloadSchema = z.object({
168
+ uri: z.string(),
169
+ ...failureShape
170
+ }).strict();
171
+ var PromptListStartPayloadSchema = z.object({}).strict();
172
+ var PromptListEndPayloadSchema = z.object({
173
+ count: z.number().int(),
174
+ ...timingShape
175
+ }).strict();
176
+ var PromptListErrorPayloadSchema = z.object({
177
+ ...failureShape
178
+ }).strict();
179
+ var PromptGetStartPayloadSchema = z.object({
180
+ name: z.string(),
181
+ /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
182
+ * where the request supplied none — see `ResourceReadStartPayloadSchema`'s
183
+ * `params` for why the schema is nullable anyway. */
184
+ params: z.record(z.string(), z.unknown()).nullable().default(null)
185
+ }).strict();
186
+ var PromptGetEndPayloadSchema = z.object({
187
+ name: z.string(),
188
+ ...timingShape
189
+ }).strict();
190
+ var PromptGetErrorPayloadSchema = z.object({
191
+ name: z.string(),
192
+ ...failureShape
193
+ }).strict();
88
194
  var ToolCallStartEventSchema = z.object({
89
195
  ...envelopeShape,
90
196
  event_type: z.literal("tool_call_start").default("tool_call_start"),
@@ -110,12 +216,84 @@ var SurfaceSnapshotEventSchema = z.object({
110
216
  event_type: z.literal("surface_snapshot").default("surface_snapshot"),
111
217
  payload: SurfaceSnapshotPayloadSchema
112
218
  }).strict();
219
+ var ResourceListStartEventSchema = z.object({
220
+ ...envelopeShape,
221
+ event_type: z.literal("resource_list_start").default("resource_list_start"),
222
+ payload: ResourceListStartPayloadSchema
223
+ }).strict();
224
+ var ResourceListEndEventSchema = z.object({
225
+ ...envelopeShape,
226
+ event_type: z.literal("resource_list_end").default("resource_list_end"),
227
+ payload: ResourceListEndPayloadSchema
228
+ }).strict();
229
+ var ResourceListErrorEventSchema = z.object({
230
+ ...envelopeShape,
231
+ event_type: z.literal("resource_list_error").default("resource_list_error"),
232
+ payload: ResourceListErrorPayloadSchema
233
+ }).strict();
234
+ var ResourceReadStartEventSchema = z.object({
235
+ ...envelopeShape,
236
+ event_type: z.literal("resource_read_start").default("resource_read_start"),
237
+ payload: ResourceReadStartPayloadSchema
238
+ }).strict();
239
+ var ResourceReadEndEventSchema = z.object({
240
+ ...envelopeShape,
241
+ event_type: z.literal("resource_read_end").default("resource_read_end"),
242
+ payload: ResourceReadEndPayloadSchema
243
+ }).strict();
244
+ var ResourceReadErrorEventSchema = z.object({
245
+ ...envelopeShape,
246
+ event_type: z.literal("resource_read_error").default("resource_read_error"),
247
+ payload: ResourceReadErrorPayloadSchema
248
+ }).strict();
249
+ var PromptListStartEventSchema = z.object({
250
+ ...envelopeShape,
251
+ event_type: z.literal("prompt_list_start").default("prompt_list_start"),
252
+ payload: PromptListStartPayloadSchema
253
+ }).strict();
254
+ var PromptListEndEventSchema = z.object({
255
+ ...envelopeShape,
256
+ event_type: z.literal("prompt_list_end").default("prompt_list_end"),
257
+ payload: PromptListEndPayloadSchema
258
+ }).strict();
259
+ var PromptListErrorEventSchema = z.object({
260
+ ...envelopeShape,
261
+ event_type: z.literal("prompt_list_error").default("prompt_list_error"),
262
+ payload: PromptListErrorPayloadSchema
263
+ }).strict();
264
+ var PromptGetStartEventSchema = z.object({
265
+ ...envelopeShape,
266
+ event_type: z.literal("prompt_get_start").default("prompt_get_start"),
267
+ payload: PromptGetStartPayloadSchema
268
+ }).strict();
269
+ var PromptGetEndEventSchema = z.object({
270
+ ...envelopeShape,
271
+ event_type: z.literal("prompt_get_end").default("prompt_get_end"),
272
+ payload: PromptGetEndPayloadSchema
273
+ }).strict();
274
+ var PromptGetErrorEventSchema = z.object({
275
+ ...envelopeShape,
276
+ event_type: z.literal("prompt_get_error").default("prompt_get_error"),
277
+ payload: PromptGetErrorPayloadSchema
278
+ }).strict();
113
279
  var EventSchema = z.discriminatedUnion("event_type", [
114
280
  ToolCallStartEventSchema,
115
281
  ToolCallEndEventSchema,
116
282
  ToolCallErrorEventSchema,
117
283
  AnnotationEventSchema,
118
- SurfaceSnapshotEventSchema
284
+ SurfaceSnapshotEventSchema,
285
+ ResourceListStartEventSchema,
286
+ ResourceListEndEventSchema,
287
+ ResourceListErrorEventSchema,
288
+ ResourceReadStartEventSchema,
289
+ ResourceReadEndEventSchema,
290
+ ResourceReadErrorEventSchema,
291
+ PromptListStartEventSchema,
292
+ PromptListEndEventSchema,
293
+ PromptListErrorEventSchema,
294
+ PromptGetStartEventSchema,
295
+ PromptGetEndEventSchema,
296
+ PromptGetErrorEventSchema
119
297
  ]);
120
298
 
121
299
  // src/scrub.ts
@@ -410,6 +588,7 @@ var HttpSink = class _HttpSink {
410
588
  };
411
589
 
412
590
  // src/integrations/mcp/withBaton.ts
591
+ import { AsyncLocalStorage } from "async_hooks";
413
592
  import { v7 as uuidv72 } from "uuid";
414
593
 
415
594
  // src/integrations/mcp/annotation.ts
@@ -464,6 +643,11 @@ function roundMetaCoordinates(meta) {
464
643
  import { createHmac } from "crypto";
465
644
 
466
645
  // src/_text.ts
646
+ function exceedsCodePoints(value, max) {
647
+ if (value.length <= max) return false;
648
+ if (value.length > 2 * max) return true;
649
+ return [...value].length > max;
650
+ }
467
651
  function capCodePoints(value, max) {
468
652
  if (value.length <= max) return value;
469
653
  return [...value].slice(0, max).join("");
@@ -474,6 +658,13 @@ var PRINCIPAL_SOURCE_ASSERTED = "asserted";
474
658
  var PRINCIPAL_FORM_HASHED = "hashed";
475
659
  var PRINCIPAL_FORM_RAW = "raw";
476
660
  var RAW_PRINCIPAL_ID_MAX_LEN = 128;
661
+ var DISPLAY_NAME_MAX_LEN = 128;
662
+ var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
663
+ function wireDisplayName(value) {
664
+ if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
665
+ if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
666
+ return value;
667
+ }
477
668
  var PRINCIPAL_ID_MODE_HASHED = "hashed";
478
669
  var PRINCIPAL_ID_MODE_RAW = "raw";
479
670
  var FORM_BY_MODE = {
@@ -509,7 +700,7 @@ function normalizePrincipal(result) {
509
700
  if (canonicalize(candidate.principalId) === "") return null;
510
701
  const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
511
702
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
512
- return { principalId: candidate.principalId, issuer };
703
+ return typeof candidate.displayName === "string" ? { principalId: candidate.principalId, issuer, displayName: candidate.displayName } : { principalId: candidate.principalId, issuer };
513
704
  }
514
705
  function principalFor(principal, options) {
515
706
  let id;
@@ -523,7 +714,14 @@ function principalFor(principal, options) {
523
714
  issuer: principal.issuer ?? null
524
715
  });
525
716
  }
526
- return { id, source: PRINCIPAL_SOURCE_ASSERTED, form: FORM_BY_MODE[options.mode] };
717
+ const wire = {
718
+ id,
719
+ source: PRINCIPAL_SOURCE_ASSERTED,
720
+ form: FORM_BY_MODE[options.mode]
721
+ };
722
+ const displayName = wireDisplayName(principal.displayName);
723
+ if (displayName !== null) wire.display_name = displayName;
724
+ return wire;
527
725
  }
528
726
 
529
727
  // src/integrations/mcp/llmText.ts
@@ -684,6 +882,10 @@ async function emit(sink, build) {
684
882
  }
685
883
 
686
884
  // src/integrations/mcp/mcpTypes.ts
885
+ function extraAuthInfo(extra) {
886
+ const found = extra.authInfo ?? extra.http?.authInfo;
887
+ return found !== null && typeof found === "object" ? found : null;
888
+ }
687
889
  function extraMeta(extra) {
688
890
  const direct = extra._meta;
689
891
  if (direct) return direct;
@@ -728,7 +930,8 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
728
930
  headers: extraHeaders(extra),
729
931
  meta: extraMeta(extra),
730
932
  toolName,
731
- arguments: args
933
+ arguments: args,
934
+ authInfo: extraAuthInfo(extra)
732
935
  };
733
936
  }
734
937
  function warnIfIdentityCannotResolve(config) {
@@ -775,6 +978,24 @@ async function resolveCallPrincipal(hook, call, options) {
775
978
  }
776
979
  }
777
980
 
981
+ // src/integrations/mcp/safeScrub.ts
982
+ var warned = /* @__PURE__ */ new Set();
983
+ function scrubOrNull(scrubber, value, field) {
984
+ if (value === null) return null;
985
+ try {
986
+ return scrubber(value);
987
+ } catch (err) {
988
+ if (!warned.has(field)) {
989
+ warned.add(field);
990
+ process.stderr.write(
991
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${String(err)}
992
+ `
993
+ );
994
+ }
995
+ return null;
996
+ }
997
+ }
998
+
778
999
  // src/integrations/mcp/runtimeAdapter.ts
779
1000
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
780
1001
  var CLIENT_NAME_MAX_LEN = 128;
@@ -783,7 +1004,7 @@ function clean(name, scrubber) {
783
1004
  if (typeof name !== "string" || !name) return null;
784
1005
  let cleaned = name;
785
1006
  if (scrubber) {
786
- const scrubbed = scrubber(cleaned);
1007
+ const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
787
1008
  if (typeof scrubbed !== "string") return null;
788
1009
  cleaned = scrubbed;
789
1010
  }
@@ -859,7 +1080,11 @@ function registerAnnotationTool(server, options) {
859
1080
  server,
860
1081
  scrubber: options.scrubber
861
1082
  }) ?? UNKNOWN_AGENT_RUNTIME;
862
- const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
1083
+ const scrubbedMeta = scrubOrNull(
1084
+ options.scrubber,
1085
+ meta ? roundMetaCoordinates(meta) : null,
1086
+ "_meta"
1087
+ );
863
1088
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
864
1089
  if (args.signal_type === void 0) {
865
1090
  options.tracker?.mark(sessionId);
@@ -890,6 +1115,7 @@ function registerAnnotationTool(server, options) {
890
1115
  // Agent-facing names -> wire keys, as with `overall_task`
891
1116
  // below: `user_goal` is stored as `intent`, `expected_result` as
892
1117
  // `expected_outcome`.
1118
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
893
1119
  intent: options.scrubber(args.user_goal),
894
1120
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
895
1121
  // `signal_type` is a closed enum — nothing to scrub. The task label
@@ -904,8 +1130,10 @@ function registerAnnotationTool(server, options) {
904
1130
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
905
1131
  // split the injected params use (`overall_task` -> `call_workflow`):
906
1132
  // renaming the param must not move the key the console groups on.
1133
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
907
1134
  workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
908
1135
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1136
+ // 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
1137
  context: args.context ? options.scrubber(args.context) : null
910
1138
  }
911
1139
  })
@@ -1120,8 +1348,68 @@ function sealKey(dsn) {
1120
1348
  return dsn;
1121
1349
  }
1122
1350
 
1351
+ // src/integrations/mcp/errorResult.ts
1352
+ var TOOL_ERROR_TYPE = "tool_error";
1353
+ var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
1354
+ var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
1355
+ function requestSideFailureKind(entry) {
1356
+ if (entry == null) return "unknown_tool";
1357
+ if (entry.enabled === false) return "tool_disabled";
1358
+ return TASK_MODES.has(entry.execution?.taskSupport) ? void 0 : "invalid_argument";
1359
+ }
1360
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1361
+ function isErrorResult(value) {
1362
+ try {
1363
+ if (typeof value !== "object" || value === null) return false;
1364
+ return Boolean(value.isError);
1365
+ } catch {
1366
+ return false;
1367
+ }
1368
+ }
1369
+ function errorText(value) {
1370
+ const parts = [];
1371
+ try {
1372
+ const content = value?.content;
1373
+ if (!Array.isArray(content)) return "";
1374
+ for (const part of content) {
1375
+ const text = part?.text;
1376
+ if (typeof text !== "string") continue;
1377
+ const trimmed = text.trim();
1378
+ if (trimmed) parts.push(trimmed);
1379
+ }
1380
+ } catch {
1381
+ return "";
1382
+ }
1383
+ return parts.join("\n");
1384
+ }
1385
+ var RESULT_CAPTURE_MODES = ["full", "off"];
1386
+ var WITHHELD = "off";
1387
+ function endResultFields(mode, result, scrubber) {
1388
+ switch (mode) {
1389
+ case WITHHELD:
1390
+ return { result: null, result_capture: WITHHELD };
1391
+ case "full":
1392
+ return { result: scrubber(result) };
1393
+ }
1394
+ }
1395
+ function returnedErrorFields(mode, result, errorBody2, scrubber) {
1396
+ return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
1397
+ }
1398
+ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1399
+ switch (mode) {
1400
+ case WITHHELD:
1401
+ return { error_body: "", result: null, result_capture: WITHHELD };
1402
+ case "full":
1403
+ return { error_body: errorBody2(text()), result: scrubber(result) };
1404
+ }
1405
+ }
1406
+ function requestSideErrorFields(text, errorBody2) {
1407
+ return { error_body: errorBody2(text), result: null };
1408
+ }
1409
+
1123
1410
  // src/integrations/mcp/config.ts
1124
1411
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1412
+ var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1125
1413
  var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1126
1414
  function resolveTenantId(explicit, vendorId) {
1127
1415
  if (explicit) return explicit;
@@ -1232,6 +1520,14 @@ function validateBatonConfig(config) {
1232
1520
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1233
1521
  );
1234
1522
  }
1523
+ if (config.resultCaptureMode !== void 0 && !RESULT_CAPTURE_MODE_SET.has(config.resultCaptureMode)) {
1524
+ throw new Error(
1525
+ `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
1526
+ );
1527
+ }
1528
+ if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
1529
+ throw new Error("BatonConfig.scrubber must be a function.");
1530
+ }
1235
1531
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1236
1532
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1237
1533
  }
@@ -1277,34 +1573,6 @@ var DisabledSink = class {
1277
1573
  }
1278
1574
  };
1279
1575
 
1280
- // src/integrations/mcp/errorResult.ts
1281
- var TOOL_ERROR_TYPE = "tool_error";
1282
- var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1283
- function isErrorResult(value) {
1284
- try {
1285
- if (typeof value !== "object" || value === null) return false;
1286
- return Boolean(value.isError);
1287
- } catch {
1288
- return false;
1289
- }
1290
- }
1291
- function errorText(value) {
1292
- const parts = [];
1293
- try {
1294
- const content = value?.content;
1295
- if (!Array.isArray(content)) return "";
1296
- for (const part of content) {
1297
- const text = part?.text;
1298
- if (typeof text !== "string") continue;
1299
- const trimmed = text.trim();
1300
- if (trimmed) parts.push(trimmed);
1301
- }
1302
- } catch {
1303
- return "";
1304
- }
1305
- return parts.join("\n");
1306
- }
1307
-
1308
1576
  // src/integrations/mcp/handle.ts
1309
1577
  var BatonHandle = class {
1310
1578
  sink;
@@ -1558,6 +1826,8 @@ function buildSeamAugmentations(options) {
1558
1826
  // src/integrations/mcp/withBaton.ts
1559
1827
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
1560
1828
  var wired = /* @__PURE__ */ new WeakSet();
1829
+ var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1830
+ var callSlots = new AsyncLocalStorage();
1561
1831
  var SurfaceState = class {
1562
1832
  constructor(serverMeta) {
1563
1833
  this.serverMeta = serverMeta;
@@ -1612,105 +1882,137 @@ var SurfaceState = class {
1612
1882
  function errorBody(ctx, text) {
1613
1883
  return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1614
1884
  }
1615
- function batonWrap(nameRef, original, ctx) {
1616
- return async (...callArgs) => {
1617
- const toolName = nameRef.current;
1618
- await maybeEmitSurfaceSnapshot(ctx);
1619
- const extra = callArgs[callArgs.length - 1];
1620
- const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1621
- const meta = extraMeta(extra);
1622
- const runtime = detectAgentRuntime(meta, {
1623
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1624
- // `_meta`; 1.x leaves them in. Both are handed over — see
1625
- // `mcpTypes.extraEnvelope`.
1626
- envelope: extraEnvelope(extra),
1627
- // Tier 2's carrier: neither peer puts client identity on the
1628
- // handler context, both expose the cached handshake on the server.
1629
- server: ctx.server,
1630
- scrubber: ctx.scrubber
1631
- }) ?? UNKNOWN_AGENT_RUNTIME;
1632
- const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
1633
- const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1634
- const dispositions = ctx.paramRegistry.get(toolName);
1635
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1636
- const rawExpected = extractGoalParam(
1637
- params,
1638
- EXPECTED_RESULT_PARAM_NAME,
1639
- toolName,
1640
- dispositions
1641
- );
1642
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);
1643
- const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1644
- const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1645
- const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1646
- const callId = uuidv72();
1647
- const principal = await resolveCallPrincipal(
1648
- ctx.resolvePrincipal,
1649
- { extra, toolName, arguments: params },
1650
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1651
- );
1652
- const common = {
1653
- tenant_id: ctx.tenantId,
1654
- vendor_id: ctx.vendorId,
1655
- session_id: sessionId,
1656
- consent_token: ctx.consentToken,
1657
- agent_runtime: runtime,
1658
- // The five `...common` sites below are the tool-call legs — start, end,
1659
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1660
- // annotation, the same five Python stamps (`middleware.py`
1661
- // 503/547/586/644/674; it was four until the returned shape landed
1662
- // there too). `surface_snapshot` is deliberately NOT among them: it
1663
- // describes the SERVER and is captured outside any call, so there is no
1664
- // caller to name (register D5).
1665
- principal,
1666
- // Same five stamps, same exclusion: a surface_snapshot describes the
1667
- // SERVER and is captured outside any call, so it has no caller's
1668
- // transport to name any more than it has a caller to name.
1669
- transport_observed: observeTransport(extra),
1670
- runtime_meta: scrubbedMeta
1671
- };
1672
- if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1673
- await emit(
1674
- ctx.sink,
1675
- () => AnnotationEventSchema.parse({
1676
- ...common,
1677
- sequence_number: ctx.counter.next(sessionId),
1678
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1679
- payload: {
1680
- intent: scrubbedIntent,
1681
- expected_outcome: scrubbedExpected,
1682
- intent_source: INTENT_SOURCE_PARAM,
1683
- tool_name: toolName
1684
- }
1685
- })
1686
- );
1687
- }
1885
+ function errorTypeOf(err) {
1886
+ return err instanceof Error ? err.constructor.name : "Error";
1887
+ }
1888
+ function messageOf(err) {
1889
+ return err instanceof Error ? err.message : String(err);
1890
+ }
1891
+ async function resolveEnvelopeParts(ctx, extra) {
1892
+ const meta = extraMeta(extra);
1893
+ const runtime = detectAgentRuntime(meta, {
1894
+ // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1895
+ // `_meta`; 1.x leaves them in. Both are handed over — see
1896
+ // `mcpTypes.extraEnvelope`.
1897
+ envelope: extraEnvelope(extra),
1898
+ // Tier 2's carrier: neither peer puts client identity on the
1899
+ // handler context, both expose the cached handshake on the server.
1900
+ server: ctx.server,
1901
+ scrubber: ctx.scrubber
1902
+ }) ?? UNKNOWN_AGENT_RUNTIME;
1903
+ const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1904
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1905
+ return { sessionId, runtime, scrubbedMeta };
1906
+ }
1907
+ async function openCall(ctx, toolName, extra, params, registered = true) {
1908
+ await maybeEmitSurfaceSnapshot(ctx);
1909
+ const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1910
+ const dispositions = ctx.paramRegistry.get(toolName);
1911
+ const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
1912
+ const rawExpected = extractGoalParam(
1913
+ params,
1914
+ EXPECTED_RESULT_PARAM_NAME,
1915
+ toolName,
1916
+ dispositions,
1917
+ registered
1918
+ );
1919
+ const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
1920
+ const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
1921
+ const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
1922
+ const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
1923
+ const callId = uuidv72();
1924
+ const principal = await resolveCallPrincipal(
1925
+ ctx.resolvePrincipal,
1926
+ { extra, toolName, arguments: params },
1927
+ { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1928
+ );
1929
+ const common = {
1930
+ tenant_id: ctx.tenantId,
1931
+ vendor_id: ctx.vendorId,
1932
+ session_id: sessionId,
1933
+ consent_token: ctx.consentToken,
1934
+ agent_runtime: runtime,
1935
+ // The five `...common` sites below are the tool-call legs — start, end,
1936
+ // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1937
+ // annotation, the same five Python stamps (`middleware.py`
1938
+ // 503/547/586/644/674; it was four until the returned shape landed
1939
+ // there too). `surface_snapshot` is deliberately NOT among them: it
1940
+ // describes the SERVER and is captured outside any call, so there is no
1941
+ // caller to name (register D5).
1942
+ principal,
1943
+ // Same five stamps, same exclusion: a surface_snapshot describes the
1944
+ // SERVER and is captured outside any call, so it has no caller's
1945
+ // transport to name any more than it has a caller to name.
1946
+ transport_observed: observeTransport(extra),
1947
+ runtime_meta: scrubbedMeta
1948
+ };
1949
+ if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
1688
1950
  await emit(
1689
1951
  ctx.sink,
1690
- () => ToolCallStartEventSchema.parse({
1952
+ () => AnnotationEventSchema.parse({
1691
1953
  ...common,
1692
- call_id: callId,
1693
1954
  sequence_number: ctx.counter.next(sessionId),
1694
1955
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1695
1956
  payload: {
1696
- tool_name: toolName,
1697
- params: ctx.scrubber(params),
1698
- call_intent: scrubbedIntent,
1699
- call_expected: scrubbedExpected,
1700
- call_workflow: scrubbedWorkflow,
1701
- intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
1957
+ intent: scrubbedIntent,
1958
+ expected_outcome: scrubbedExpected,
1959
+ intent_source: INTENT_SOURCE_PARAM,
1960
+ tool_name: toolName
1702
1961
  }
1703
1962
  })
1704
1963
  );
1964
+ }
1965
+ await emit(
1966
+ ctx.sink,
1967
+ () => ToolCallStartEventSchema.parse({
1968
+ ...common,
1969
+ call_id: callId,
1970
+ sequence_number: ctx.counter.next(sessionId),
1971
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1972
+ payload: {
1973
+ tool_name: toolName,
1974
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for params
1975
+ params: ctx.scrubber(params),
1976
+ call_intent: scrubbedIntent,
1977
+ call_expected: scrubbedExpected,
1978
+ call_workflow: scrubbedWorkflow,
1979
+ intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
1980
+ }
1981
+ })
1982
+ );
1983
+ return { common, callId, sessionId };
1984
+ }
1985
+ function batonWrap(nameRef, original, ctx) {
1986
+ return async (...callArgs) => {
1987
+ const toolName = nameRef.current;
1988
+ const slot = callSlots.getStore();
1989
+ if (slot) slot.innerFired = true;
1990
+ const extra = callArgs[callArgs.length - 1];
1991
+ const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1992
+ const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);
1993
+ const terminate = async (build, replacement) => {
1994
+ if (!slot) {
1995
+ await emit(ctx.sink, build);
1996
+ return;
1997
+ }
1998
+ const earlier = slot.flushTerminal;
1999
+ if (earlier !== null) await earlier(CLEAN_OUTCOME);
2000
+ slot.flushTerminal = async (outcome) => {
2001
+ await emit(
2002
+ ctx.sink,
2003
+ () => replacement !== null && outcome.failed ? replacement(outcome) : build()
2004
+ );
2005
+ };
2006
+ };
2007
+ const parkFailure = (build) => terminate(build, null);
2008
+ const parkSuccess = (build, replacement) => terminate(build, replacement);
1705
2009
  const startedAt = performance.now();
1706
2010
  let result;
1707
2011
  try {
1708
2012
  result = await original(...callArgs);
1709
2013
  } catch (err) {
1710
2014
  const durationMs2 = Math.round(performance.now() - startedAt);
1711
- const message = err instanceof Error ? err.message : String(err);
1712
- await emit(
1713
- ctx.sink,
2015
+ await parkFailure(
1714
2016
  () => ToolCallErrorEventSchema.parse({
1715
2017
  ...common,
1716
2018
  call_id: callId,
@@ -1718,17 +2020,26 @@ function batonWrap(nameRef, original, ctx) {
1718
2020
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1719
2021
  payload: {
1720
2022
  tool_name: toolName,
1721
- error_type: err instanceof Error ? err.constructor.name : "Error",
1722
- error_body: errorBody(ctx, message),
2023
+ error_type: errorTypeOf(err),
2024
+ // ⚠ KEPT under `resultCaptureMode: "off"`, and that is the rule's
2025
+ // shape rather than an exception to it: the rule is keyed on
2026
+ // PROVENANCE, and a thrown error's message is the vendor's own
2027
+ // code speaking about a call that returned nothing (SPEC
2028
+ // §11.4.3(1)). A switch written as "drop `error_body`" would
2029
+ // delete the highest-value diagnostic the product has.
2030
+ error_body: errorBody(ctx, messageOf(err)),
1723
2031
  duration_ms: durationMs2,
1724
2032
  // Explicit, though the field is `.optional()` and this is its
1725
2033
  // absent value. The schema is deliberately not an emitter (see
1726
2034
  // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1727
- // key would be missing — and Python's `tool_call_error` vector
1728
- // carries `result: null`, so the cross-SDK key-set check in
1729
- // `emitterConformance.test.ts` is what would say so. Each of the
1730
- // two failure shapes declares which it is, the same reason
1731
- // Python's emitter made the parameter positional-without-default.
2035
+ // key would be missing. Each of the two failure shapes declares
2036
+ // which it is, the same reason Python's emitter made the parameter
2037
+ // positional-without-default.
2038
+ //
2039
+ // ⚠ Guarded by `errorResult.test.ts`'s `toContain("result")`, NOT by
2040
+ // the cross-SDK key-set check — measured by removing this line. Why,
2041
+ // at one site: `endResultFields` in `errorResult.ts`. SPEC §11.4.3
2042
+ // states the same void rationale and wants the same amendment.
1732
2043
  result: null
1733
2044
  }
1734
2045
  })
@@ -1737,8 +2048,7 @@ function batonWrap(nameRef, original, ctx) {
1737
2048
  }
1738
2049
  const durationMs = Math.round(performance.now() - startedAt);
1739
2050
  if (isErrorResult(result)) {
1740
- await emit(
1741
- ctx.sink,
2051
+ await parkFailure(
1742
2052
  () => ToolCallErrorEventSchema.parse({
1743
2053
  ...common,
1744
2054
  call_id: callId,
@@ -1747,36 +2057,105 @@ function batonWrap(nameRef, original, ctx) {
1747
2057
  payload: {
1748
2058
  tool_name: toolName,
1749
2059
  error_type: TOOL_ERROR_TYPE,
1750
- error_body: errorBody(ctx, errorText(result)),
1751
2060
  duration_ms: durationMs,
1752
- // The whole envelope. ⚠ On this producer that is the same shape
1753
- // `tool_call_end.result` records, which is NOT what Python's
1754
- // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1755
- // holds that claim and names the test that enforces it.
1756
- result: ctx.scrubber(result)
2061
+ // Both remaining members are unwrapped FROM the result on this
2062
+ // shape, so one projection decides them together and owns the
2063
+ // scrubber call. `error_type` is NOT result-derived and is passed
2064
+ // regardless: the call still failed (SPEC §11.2.6).
2065
+ //
2066
+ // ⚠ Under `"full"` `result` is the whole envelope, and on this
2067
+ // producer that is the same shape `tool_call_end.result` records —
2068
+ // which is NOT what Python's contrast says.
2069
+ // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
2070
+ // names the test that enforces it.
2071
+ ...returnedErrorFields(
2072
+ ctx.resultCaptureMode,
2073
+ result,
2074
+ (text) => errorBody(ctx, text),
2075
+ ctx.scrubber
2076
+ )
1757
2077
  }
1758
2078
  })
1759
2079
  );
1760
2080
  return result;
1761
2081
  }
1762
- await emit(
1763
- ctx.sink,
2082
+ await parkSuccess(
1764
2083
  () => ToolCallEndEventSchema.parse({
1765
2084
  ...common,
1766
2085
  call_id: callId,
1767
2086
  sequence_number: ctx.counter.next(sessionId),
1768
2087
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1769
- payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
2088
+ payload: {
2089
+ tool_name: toolName,
2090
+ duration_ms: durationMs,
2091
+ ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
2092
+ }
2093
+ }),
2094
+ // The handler returned something this sensor reads as a success, and
2095
+ // then the outer seam saw the call fail anyway — so what failed is the
2096
+ // producer's own conversion of the output (SPEC §11.4.3's
2097
+ // `output_schema_mismatch`). Correcting this is the whole point of the
2098
+ // second seam: without it this is a `tool_call_end` for a call the
2099
+ // CALLER saw fail, which is a success the product invented.
2100
+ (outcome) => ToolCallErrorEventSchema.parse({
2101
+ ...common,
2102
+ call_id: callId,
2103
+ sequence_number: ctx.counter.next(sessionId),
2104
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2105
+ payload: {
2106
+ tool_name: toolName,
2107
+ // The lane the OUTER came back on, not this one's: on 2.x the
2108
+ // conversion failure is converted to a returned `isError` inside
2109
+ // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2110
+ // right there. A throw out of the handler is unreachable on
2111
+ // either major today for this lane; spelled anyway, because the
2112
+ // alternative is a crash on the day it stops being.
2113
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2114
+ // ⚠ The INNER's measurement — the vendor's handler duration —
2115
+ // not the outer's. Every other leg means the same thing by this
2116
+ // member, and widening it here for one failure kind would make
2117
+ // `duration_ms` mean two things in one column.
2118
+ duration_ms: durationMs,
2119
+ failure_kind: OUTPUT_SCHEMA_MISMATCH,
2120
+ // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2121
+ // kinds.** The message quotes the value the tool returned
2122
+ // ("`'not-an-int'` is not of type `integer`"), so it is
2123
+ // result-derived by provenance and goes — which leaves
2124
+ // `failure_kind` as the ONLY surviving signal for this failure
2125
+ // under `"off"`, and is the measurement that justified putting
2126
+ // the member on the wire at all.
2127
+ //
2128
+ // ⚠ `result` is what the CLIENT received — the SDK's own error
2129
+ // envelope — not the vendor's rejected return value. §11.4.3
2130
+ // asks for the envelope that holds the flag and the reason, and
2131
+ // this package's own invariant is that it agrees with the
2132
+ // caller. Recording the rejected output TOO would need a member
2133
+ // nothing on the wire has; the loss is deliberate and worth
2134
+ // knowing when debugging one of these.
2135
+ ...resultDerivedFields(
2136
+ ctx.resultCaptureMode,
2137
+ () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2138
+ // ⚠ `null` on the `raised` lane, never `undefined`, and the
2139
+ // union is what forces the branch rather than a comment: the
2140
+ // scrubber would answer `undefined` and DROP the key, where the
2141
+ // sibling raise lane a few lines up declares `result: null`
2142
+ // explicitly, for the reason `ToolCallErrorPayloadSchema`
2143
+ // records. One shape for "no result object existed", not two.
2144
+ outcome.raised ? null : outcome.result ?? null,
2145
+ (text) => errorBody(ctx, text),
2146
+ ctx.scrubber
2147
+ )
2148
+ }
1770
2149
  })
1771
2150
  );
1772
2151
  return result;
1773
2152
  };
1774
2153
  }
1775
- function extractGoalParam(args, paramName, toolName, dispositions) {
2154
+ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
1776
2155
  if (!(paramName in args)) return null;
1777
2156
  const disposition = dispositions ? dispositions[paramName] : void 0;
1778
2157
  if (disposition === "native") return null;
1779
- if (disposition === void 0) {
2158
+ if (disposition === void 0 && registered) {
1780
2159
  process.stderr.write(
1781
2160
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
1782
2161
  `
@@ -1835,12 +2214,29 @@ function captureAndInject(name, entry, ctx) {
1835
2214
  }
1836
2215
  var TOOLS_LIST_METHOD = "tools/list";
1837
2216
  var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
1838
- function installToolsListSeam(lowLevel, ctx) {
2217
+ var TOOLS_CALL_METHOD = "tools/call";
2218
+ var TOOLS_CALL_SEAM = /* @__PURE__ */ Symbol("batonToolsCallSeam");
2219
+ function installRequestSeam(lowLevel, method, seamTag, wrap) {
1839
2220
  const table = lowLevel._requestHandlers;
1840
2221
  const originalSet = lowLevel.setRequestHandler;
1841
2222
  if (!(table instanceof Map) || typeof originalSet !== "function") return;
1842
2223
  const handlers = table;
1843
2224
  const setRequestHandler = originalSet;
2225
+ const wrapCurrent = () => {
2226
+ const handler = handlers.get(method);
2227
+ if (typeof handler !== "function" || handler[seamTag]) return;
2228
+ const seamed = wrap(handler);
2229
+ seamed[seamTag] = true;
2230
+ handlers.set(method, seamed);
2231
+ };
2232
+ wrapCurrent();
2233
+ lowLevel.setRequestHandler = (...args) => {
2234
+ const registered = setRequestHandler.apply(lowLevel, args);
2235
+ wrapCurrent();
2236
+ return registered;
2237
+ };
2238
+ }
2239
+ function installToolsListSeam(lowLevel, ctx) {
1844
2240
  const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
1845
2241
  const advertise = (result) => {
1846
2242
  try {
@@ -1853,22 +2249,273 @@ function installToolsListSeam(lowLevel, ctx) {
1853
2249
  return result;
1854
2250
  }
1855
2251
  };
1856
- const wrapCurrent = () => {
1857
- const handler = handlers.get(TOOLS_LIST_METHOD);
1858
- if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
1859
- const seamed = (...args) => {
1860
- const out = handler(...args);
1861
- return isThenable(out) ? out.then(advertise) : advertise(out);
2252
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {
2253
+ const out = handler(...args);
2254
+ return isThenable(out) ? out.then(advertise) : advertise(out);
2255
+ });
2256
+ }
2257
+ var LIFECYCLE_SEAMS = {
2258
+ resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2259
+ resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2260
+ promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2261
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2262
+ };
2263
+ function installLifecycleSeam(lowLevel, ctx, spec) {
2264
+ installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
2265
+ const request = args[0];
2266
+ const requestParams = request?.params ?? {};
2267
+ const extra = args[1];
2268
+ const opened = await openLifecycleCall(ctx, spec, requestParams, extra);
2269
+ const fire = async (schema, payload) => {
2270
+ if (opened === null) return;
2271
+ await emit(
2272
+ ctx.sink,
2273
+ () => schema.parse({
2274
+ ...opened.common,
2275
+ sequence_number: ctx.counter.next(opened.sessionId),
2276
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2277
+ payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
2278
+ })
2279
+ );
1862
2280
  };
1863
- seamed[TOOLS_LIST_SEAM] = true;
1864
- handlers.set(TOOLS_LIST_METHOD, seamed);
1865
- };
1866
- wrapCurrent();
1867
- lowLevel.setRequestHandler = (...args) => {
1868
- const registered = setRequestHandler.apply(lowLevel, args);
1869
- wrapCurrent();
1870
- return registered;
1871
- };
2281
+ await fire(spec.schemas.start, spec.startParams(requestParams));
2282
+ const startedAt = performance.now();
2283
+ const elapsed = () => Math.round(performance.now() - startedAt);
2284
+ try {
2285
+ const result = await handler(...args);
2286
+ await fire(spec.schemas.end, {
2287
+ ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
2288
+ duration_ms: elapsed()
2289
+ });
2290
+ return result;
2291
+ } catch (err) {
2292
+ await fire(spec.schemas.error, {
2293
+ error_type: errorTypeOf(err),
2294
+ // KEPT under every capture mode: a failed FETCH's message is the
2295
+ // producer's own diagnostic, not anything a resource returned, so
2296
+ // nothing here is result-derived (SPEC §11.4.4). The scrub and the cap
2297
+ // are `scrubLifecyclePayload`'s, in that order.
2298
+ error_body: messageOf(err),
2299
+ duration_ms: elapsed()
2300
+ });
2301
+ throw err;
2302
+ }
2303
+ });
2304
+ }
2305
+ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2306
+ try {
2307
+ const parts = await resolveEnvelopeParts(ctx, extra);
2308
+ return {
2309
+ sessionId: parts.sessionId,
2310
+ subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
2311
+ common: {
2312
+ tenant_id: ctx.tenantId,
2313
+ vendor_id: ctx.vendorId,
2314
+ session_id: parts.sessionId,
2315
+ consent_token: ctx.consentToken,
2316
+ agent_runtime: parts.runtime,
2317
+ transport_observed: observeTransport(extra),
2318
+ runtime_meta: parts.scrubbedMeta
2319
+ }
2320
+ };
2321
+ } catch (err) {
2322
+ process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
2323
+ `);
2324
+ return null;
2325
+ }
2326
+ }
2327
+ var NO_PARAMS = () => EMPTY_PARAMS;
2328
+ var EMPTY_PARAMS = Object.freeze({});
2329
+ var LIFECYCLE_SPECS = [
2330
+ {
2331
+ method: "resources/list",
2332
+ seamTag: LIFECYCLE_SEAMS.resourceList,
2333
+ schemas: {
2334
+ start: ResourceListStartEventSchema,
2335
+ end: ResourceListEndEventSchema,
2336
+ error: ResourceListErrorEventSchema
2337
+ },
2338
+ // ⚠ `resources` ALONE. Resource TEMPLATES are a separate MCP method with
2339
+ // their own result array and are deliberately not added in, matching the
2340
+ // proxy — so a template-only server reports 0, which §11.4.4 says a
2341
+ // consumer MUST NOT read as "this server has no resources".
2342
+ countKey: "resources",
2343
+ startParams: NO_PARAMS
2344
+ },
2345
+ {
2346
+ method: "resources/read",
2347
+ seamTag: LIFECYCLE_SEAMS.resourceRead,
2348
+ schemas: {
2349
+ start: ResourceReadStartEventSchema,
2350
+ end: ResourceReadEndEventSchema,
2351
+ error: ResourceReadErrorEventSchema
2352
+ },
2353
+ subjectKey: "uri",
2354
+ // ⚠ The whole params bag MINUS `_meta`, so `uri` lands here as well as in
2355
+ // its own member. That duplication is the proxy's and is reproduced on
2356
+ // purpose: the dedicated member is what a consumer reads, the bag is what
2357
+ // the caller actually sent, and a producer that stripped `uri` out could no
2358
+ // longer say the second thing. `_meta` is excluded because it rides the
2359
+ // envelope as `runtime_meta` already.
2360
+ startParams: (params) => ({ params: paramsBag(params) })
2361
+ },
2362
+ {
2363
+ method: "prompts/list",
2364
+ seamTag: LIFECYCLE_SEAMS.promptList,
2365
+ schemas: {
2366
+ start: PromptListStartEventSchema,
2367
+ end: PromptListEndEventSchema,
2368
+ error: PromptListErrorEventSchema
2369
+ },
2370
+ countKey: "prompts",
2371
+ startParams: NO_PARAMS
2372
+ },
2373
+ {
2374
+ method: "prompts/get",
2375
+ seamTag: LIFECYCLE_SEAMS.promptGet,
2376
+ schemas: {
2377
+ start: PromptGetStartEventSchema,
2378
+ end: PromptGetEndEventSchema,
2379
+ error: PromptGetErrorEventSchema
2380
+ },
2381
+ subjectKey: "name",
2382
+ // ⚠ `arguments` ALONE, NOT the whole bag — the opposite of the resource
2383
+ // read above, so `name` does NOT appear inside `params`. The two are
2384
+ // inconsistent in the producer the shapes came from; the inconsistency is
2385
+ // reproduced rather than tidied, because a consumer reading one producer
2386
+ // and a second producer reading the other must agree.
2387
+ startParams: (params) => ({
2388
+ params: paramsBag(params["arguments"])
2389
+ })
2390
+ }
2391
+ ];
2392
+ function installLifecycleSeams(lowLevel, ctx) {
2393
+ for (const spec of LIFECYCLE_SPECS) installLifecycleSeam(lowLevel, ctx, spec);
2394
+ }
2395
+ function stringSubject(value) {
2396
+ return typeof value === "string" ? value : "";
2397
+ }
2398
+ function countOf(result, key) {
2399
+ const list = result?.[key];
2400
+ return Array.isArray(list) ? list.length : 0;
2401
+ }
2402
+ function paramsBag(bag) {
2403
+ if (!bag || typeof bag !== "object") return {};
2404
+ const out = {};
2405
+ for (const key of Object.keys(bag)) {
2406
+ if (key !== "_meta") out[key] = bag[key];
2407
+ }
2408
+ return out;
2409
+ }
2410
+ function scrubLifecyclePayload(ctx, raw) {
2411
+ const scrubbed = ctx.scrubber(raw);
2412
+ const body = scrubbed?.["error_body"];
2413
+ if (typeof body !== "string") return scrubbed;
2414
+ return { ...scrubbed, error_body: capCodePoints(body, ERROR_BODY_MAX_CODE_POINTS) };
2415
+ }
2416
+ function dispatchSlot(entry) {
2417
+ if (typeof entry.executor === "function") return "executor";
2418
+ if (typeof entry.handler === "function") return "handler";
2419
+ return void 0;
2420
+ }
2421
+ function dispatchTarget(entry) {
2422
+ const slot = dispatchSlot(entry);
2423
+ return slot === void 0 ? void 0 : entry[slot];
2424
+ }
2425
+ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2426
+ installRequestSeam(
2427
+ lowLevel,
2428
+ TOOLS_CALL_METHOD,
2429
+ TOOLS_CALL_SEAM,
2430
+ (handler) => async (...args) => {
2431
+ const slot = { innerFired: false, flushTerminal: null };
2432
+ let outcome = CLEAN_OUTCOME;
2433
+ try {
2434
+ const result = await callSlots.run(slot, () => handler(...args));
2435
+ outcome = { failed: isErrorResult(result), raised: false, result };
2436
+ return result;
2437
+ } catch (err) {
2438
+ outcome = { failed: true, raised: true, err };
2439
+ throw err;
2440
+ } finally {
2441
+ await settleCall(slot, outcome, args, toolEntry, ctx);
2442
+ }
2443
+ }
2444
+ );
2445
+ }
2446
+ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2447
+ try {
2448
+ if (slot.flushTerminal !== null) {
2449
+ const flush = slot.flushTerminal;
2450
+ slot.flushTerminal = null;
2451
+ await flush(outcome);
2452
+ return;
2453
+ }
2454
+ if (slot.innerFired) return;
2455
+ if (!outcome.failed) return;
2456
+ await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2457
+ } catch (err) {
2458
+ process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2459
+ `);
2460
+ }
2461
+ }
2462
+ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2463
+ const request = args[0];
2464
+ const toolName = request?.params?.name;
2465
+ if (typeof toolName !== "string") return;
2466
+ if (toolName === ctx.annotationToolName) return;
2467
+ const entry = toolEntry(toolName);
2468
+ if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2469
+ const params = { ...request?.params?.arguments ?? {} };
2470
+ const { common, callId, sessionId } = await openCall(
2471
+ ctx,
2472
+ toolName,
2473
+ args[1],
2474
+ params,
2475
+ entry != null
2476
+ );
2477
+ const failureKind = requestSideFailureKind(entry);
2478
+ await emit(
2479
+ ctx.sink,
2480
+ () => ToolCallErrorEventSchema.parse({
2481
+ ...common,
2482
+ call_id: callId,
2483
+ sequence_number: ctx.counter.next(sessionId),
2484
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2485
+ payload: {
2486
+ tool_name: toolName,
2487
+ // The lane the SDK rejected on, which is NOT the same across majors
2488
+ // for one failure: 1.x converts all three to a returned `isError`
2489
+ // inside its own `try` (`mcp.js:101-108`), v2 THROWS the first two
2490
+ // and returns the third. So the same customer-visible failure is
2491
+ // `"tool_error"` on one major and `"ProtocolError"` on the other —
2492
+ // measured 2026-10-01, and deliberately not special-cased: this
2493
+ // member is §11.4.3's RAISE/RETURN discriminator and it is reporting
2494
+ // the shape faithfully. `failure_kind` is what makes the two
2495
+ // comparable, which is the member's whole justification.
2496
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2497
+ // ⚠ `null`, not 0. The vendor's handler never ran, so there is no
2498
+ // handler duration to report; the time this call did spend was spent
2499
+ // in the SDK's validator, which is not what any other event means by
2500
+ // this member. §11.4 types it nullable for cases like this one.
2501
+ duration_ms: null,
2502
+ // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
2503
+ // `.optional()` accepts `undefined` and keeps the KEY in its output,
2504
+ // so the plain form writes a present-but-undefined member — invisible
2505
+ // to a JSON-serialising sink and plainly visible to a vendor-supplied
2506
+ // one that iterates keys. SPEC §11.4.3 says a producer that cannot
2507
+ // determine the kind MUST OMIT the member, and omitting is what this
2508
+ // spells.
2509
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
2510
+ // KEPT under `"off"` — see `requestSideErrorFields`, which takes no
2511
+ // capture mode because nothing here is derived from a result.
2512
+ ...requestSideErrorFields(
2513
+ outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2514
+ (text) => errorBody(ctx, text)
2515
+ )
2516
+ }
2517
+ })
2518
+ );
1872
2519
  }
1873
2520
  function isThenable(value) {
1874
2521
  return typeof value?.then === "function";
@@ -1876,20 +2523,13 @@ function isThenable(value) {
1876
2523
  function wrapIfNeeded(nameRef, entry, ctx) {
1877
2524
  if (!entry || typeof entry !== "object") return;
1878
2525
  const mutable = entry;
1879
- if (typeof mutable.executor === "function") {
1880
- if (mutable.executor[BATON_WRAPPED]) return;
1881
- const originalExecutor = mutable.executor;
1882
- const wrapper2 = batonWrap(nameRef, originalExecutor, ctx);
1883
- wrapper2[BATON_WRAPPED] = true;
1884
- mutable.executor = wrapper2;
1885
- return;
1886
- }
1887
- if (typeof mutable.handler !== "function") return;
1888
- if (mutable.handler[BATON_WRAPPED]) return;
1889
- const original = mutable.handler;
1890
- const wrapper = batonWrap(nameRef, original, ctx);
2526
+ const slot = dispatchSlot(mutable);
2527
+ if (slot === void 0) return;
2528
+ const target = mutable[slot];
2529
+ if (target[BATON_WRAPPED]) return;
2530
+ const wrapper = batonWrap(nameRef, target, ctx);
1891
2531
  wrapper[BATON_WRAPPED] = true;
1892
- mutable.handler = wrapper;
2532
+ mutable[slot] = wrapper;
1893
2533
  }
1894
2534
  function wireEntry(name, entry, ctx) {
1895
2535
  if (name === ctx.annotationToolName) return;
@@ -2044,6 +2684,7 @@ function withBaton(server, supplied = {}) {
2044
2684
  scrubber,
2045
2685
  annotationToolName,
2046
2686
  intentParamMode,
2687
+ resultCaptureMode: config.resultCaptureMode ?? "full",
2047
2688
  paramRegistry: /* @__PURE__ */ new Map(),
2048
2689
  resolvePrincipal: config.resolvePrincipal,
2049
2690
  principalIdMode: config.principalIdMode ?? "hashed",
@@ -2061,6 +2702,22 @@ function withBaton(server, supplied = {}) {
2061
2702
  });
2062
2703
  internals.server._instructions = instructions;
2063
2704
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
2705
+ installToolsCallSeam(
2706
+ internals.server,
2707
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
2708
+ // object, so `registry["constructor"]` answers `Object` and
2709
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
2710
+ // so the "a tool we did not wrap" guard would decline to report, and a
2711
+ // caller-visible `Tool constructor disabled` would reach the client with
2712
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
2713
+ // exactly the kind of failure the seam exists to make visible.
2714
+ (name) => {
2715
+ const registry = internals._registeredTools;
2716
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
2717
+ },
2718
+ ctx
2719
+ );
2720
+ installLifecycleSeams(internals.server, ctx);
2064
2721
  const resolvedAnnotationToolName = registerAnnotationTool(server, {
2065
2722
  sink,
2066
2723
  counter: ctx.counter,
@@ -2104,6 +2761,38 @@ function withBaton(server, supplied = {}) {
2104
2761
  annotationToolName: resolvedAnnotationToolName
2105
2762
  });
2106
2763
  }
2764
+
2765
+ // src/integrations/mcp/oauthHooks.ts
2766
+ function claimsOf(context) {
2767
+ try {
2768
+ const extra = context.authInfo?.extra;
2769
+ return extra !== null && typeof extra === "object" ? extra : null;
2770
+ } catch {
2771
+ return null;
2772
+ }
2773
+ }
2774
+ function stringClaim(claims, name) {
2775
+ const value = claims[name];
2776
+ return typeof value === "string" && pythonStrip(value) !== "" ? value : null;
2777
+ }
2778
+ function principalFromOAuthSub(context) {
2779
+ const claims = claimsOf(context);
2780
+ if (claims === null) return null;
2781
+ const sub = stringClaim(claims, "sub");
2782
+ const iss = claims.iss;
2783
+ return sub === null ? null : { principalId: sub, issuer: typeof iss === "string" && iss !== "" ? iss : null };
2784
+ }
2785
+ function principalFromOAuthEmail(context) {
2786
+ const claims = claimsOf(context);
2787
+ if (claims === null) return null;
2788
+ const email = stringClaim(claims, "email");
2789
+ if (email === null) return null;
2790
+ const at = email.lastIndexOf("@");
2791
+ return {
2792
+ principalId: email,
2793
+ displayName: at > 0 ? email.slice(0, at) : null
2794
+ };
2795
+ }
2107
2796
  export {
2108
2797
  AnnotationEventSchema,
2109
2798
  AnnotationPayloadSchema,
@@ -2117,6 +2806,30 @@ export {
2117
2806
  PRINCIPAL_FORM_RAW,
2118
2807
  PRINCIPAL_SOURCE_ASSERTED,
2119
2808
  PrincipalWireSchema,
2809
+ PromptGetEndEventSchema,
2810
+ PromptGetEndPayloadSchema,
2811
+ PromptGetErrorEventSchema,
2812
+ PromptGetErrorPayloadSchema,
2813
+ PromptGetStartEventSchema,
2814
+ PromptGetStartPayloadSchema,
2815
+ PromptListEndEventSchema,
2816
+ PromptListEndPayloadSchema,
2817
+ PromptListErrorEventSchema,
2818
+ PromptListErrorPayloadSchema,
2819
+ PromptListStartEventSchema,
2820
+ PromptListStartPayloadSchema,
2821
+ ResourceListEndEventSchema,
2822
+ ResourceListEndPayloadSchema,
2823
+ ResourceListErrorEventSchema,
2824
+ ResourceListErrorPayloadSchema,
2825
+ ResourceListStartEventSchema,
2826
+ ResourceListStartPayloadSchema,
2827
+ ResourceReadEndEventSchema,
2828
+ ResourceReadEndPayloadSchema,
2829
+ ResourceReadErrorEventSchema,
2830
+ ResourceReadErrorPayloadSchema,
2831
+ ResourceReadStartEventSchema,
2832
+ ResourceReadStartPayloadSchema,
2120
2833
  SDK_VERSION,
2121
2834
  Scrubber,
2122
2835
  StdoutSink,
@@ -2130,6 +2843,8 @@ export {
2130
2843
  ToolCallStartPayloadSchema,
2131
2844
  hashPrincipalId,
2132
2845
  identityScrub,
2846
+ principalFromOAuthEmail,
2847
+ principalFromOAuthSub,
2133
2848
  safeWrite,
2134
2849
  withBaton
2135
2850
  };