@goodtiming/baton-sdk 0.5.3 → 0.5.5

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/README.md CHANGED
@@ -110,7 +110,7 @@ withBaton(server, {
110
110
 
111
111
  ⚠ **They read the claims from `authInfo.extra`.** The MCP SDK's `AuthInfo` has no `claims` field, so these hooks expect your token verifier to put the decoded JWT claims (`sub`, `iss`, `email`) at the top level of `extra`. If yours keeps them elsewhere, write the three-line hook that reads them from there. A token exists only on HTTP with auth configured; on stdio, write a hook that names the user from whatever you authenticated them with.
112
112
 
113
- The hook runs on every tool call and every `tools/list` request, before your handler. On a `tools/list` request `toolName` is `null` and `arguments` is empty, so a hook that names the person from the headers or `authInfo` needs no change. If it has not answered after 5 seconds, the SDK stops waiting and that request is sent without a principal. That covers an async hook waiting on a slow lookup. A hook that blocks synchronously cannot be interrupted, so keep the work in it async.
113
+ The hook runs on every tool call, every `tools/list` request and every resource and prompt request (list, read, get), before your handler. On a request that is not a tool call `toolName` is `null` and `arguments` is empty, so a hook that names the person from the headers or `authInfo` needs no change. If it has not answered after 5 seconds, the SDK stops waiting and that request is sent without a principal. That covers an async hook waiting on a slow lookup. A hook that blocks synchronously cannot be interrupted, so keep the work in it async.
114
114
 
115
115
  The id is sent exactly as your hook returns it, so the hook decides what is safe to send. To send a pseudonym instead, hash the id inside your hook and return `form: "hashed"` with it.
116
116
 
@@ -190,6 +190,9 @@ with `could not parse ${body.slice(0, 200)}`, that content leaves your process
190
190
  under a mode you set to stop exactly that. Throw a message that names the
191
191
  resource, not its contents.
192
192
 
193
+ These events carry the principal your `resolvePrincipal` hook returns
194
+ ([Who is calling](#who-is-calling)).
195
+
193
196
  ## Tool listings
194
197
 
195
198
  Every `tools/list` request emits a `tool_list_start` and then a
package/dist/index.cjs CHANGED
@@ -93,7 +93,7 @@ __export(index_exports, {
93
93
  module.exports = __toCommonJS(index_exports);
94
94
 
95
95
  // src/version.ts
96
- var SDK_VERSION = "ts-0.5.3";
96
+ var SDK_VERSION = "ts-0.5.5";
97
97
 
98
98
  // src/events.ts
99
99
  var import_zod = require("zod");
@@ -199,6 +199,7 @@ var ToolCallErrorPayloadSchema = import_zod.z.object({
199
199
  var AnnotationPayloadSchema = import_zod.z.object({
200
200
  intent: import_zod.z.string().nullable().default(null),
201
201
  expected_outcome: import_zod.z.string().nullable().default(null),
202
+ what_happened: import_zod.z.string().nullable().default(null),
202
203
  signal_type: import_zod.z.string().nullable().default(null),
203
204
  workflow: import_zod.z.string().nullable().default(null),
204
205
  suggested_improvement: import_zod.z.string().nullable().default(null),
@@ -239,6 +240,7 @@ var envelopeShape = {
239
240
  agent_runtime: import_zod.z.string().default("unknown"),
240
241
  principal: PrincipalWireSchema.nullable().default(null),
241
242
  transport_observed: import_zod.z.string().nullable().default(null),
243
+ session_id_origin: import_zod.z.string().nullable().default(null),
242
244
  client_observed: ClientObservedSchema.nullable().default(null),
243
245
  call_id: import_zod.z.string().nullable().default(null),
244
246
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
@@ -864,30 +866,21 @@ function principalFor(principal, onUnregisteredForm) {
864
866
  // src/integrations/mcp/llmText.ts
865
867
  var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} usage and friction SDK. Use \`${annotationToolName}\` to report when a ${vendorDisplayName} tool call goes wrong, or when a tool you needed does not exist, so ${vendorDisplayName} can improve their product. See that tool's description for field-level detail.
866
868
 
867
- AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` again with signal_type (REQUIRED) \u2014 one of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other \u2014 and suggested_improvement (REQUIRED whenever you can articulate one).
869
+ AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` with what_happened (REQUIRED, your own words, NOT a category), tool_name (REQUIRED) and suggested_improvement (REQUIRED whenever you can articulate one).
868
870
 
869
- IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` with signal_type='feature_gap' AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
871
+ IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` once per user request, not per call, with what_happened and tool_name (none if no tool) AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
870
872
  var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Report a ${vendorDisplayName} tool call that went wrong \u2014 call this AFTER a call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. Do NOT call it before a tool call or to narrate normal successful work.
871
873
 
872
874
  Fields:
873
875
  - user_goal: one sentence on what the user is trying to accomplish.
876
+ - what_happened: REQUIRED on a report. 1-2 plain sentences in YOUR OWN WORDS: what you asked for, what came back, and why it was unusable. Do NOT pick a category or invent a label \u2014 describe it.
877
+ - tool_name: REQUIRED on a report. The ${vendorDisplayName} tool that went wrong. Write none if no tool exists for the request.
874
878
  - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
875
879
  - overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.
876
- - signal_type: reactive-only \u2014 omit on a proactive annotation. Set only once a tool call has returned an unhelpful result. One of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other.
877
- - suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
878
- - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. For signal_type='feature_gap' also missing_capability_field and requested_capability.`;
880
+ - suggested_improvement: A concrete sentence about what product change would have helped.
881
+ - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
879
882
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
880
883
  var INSTRUCTIONS_LENGTH_CAP = 1500;
881
- var SIGNAL_TYPES = [
882
- "failure",
883
- "retry_loop",
884
- "dead_end",
885
- "parameter_confusion",
886
- "slow_performance",
887
- "abandonment",
888
- "feature_gap",
889
- "other"
890
- ];
891
884
  function renderServerInstructions(options) {
892
885
  return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
893
886
  }
@@ -1221,11 +1214,27 @@ function observeClient(extra, options) {
1221
1214
 
1222
1215
  // src/integrations/mcp/sessionResolution.ts
1223
1216
  async function resolveSessionId(fallbackSessionId, extra) {
1224
- if (typeof extra.sessionId === "string" && extra.sessionId) return extra.sessionId;
1225
- return fallbackSessionId;
1217
+ if (typeof extra.sessionId === "string" && extra.sessionId) {
1218
+ return { sessionId: extra.sessionId, origin: "observed" };
1219
+ }
1220
+ const fromHeader = sessionIdFromHeader(extra);
1221
+ if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
1222
+ return { sessionId: fallbackSessionId, origin: "minted" };
1223
+ }
1224
+ function sessionIdFromHeader(extra) {
1225
+ try {
1226
+ const value = extraHeaders(extra)?.get("mcp-session-id")?.trim();
1227
+ return value ? value : null;
1228
+ } catch {
1229
+ return null;
1230
+ }
1226
1231
  }
1227
1232
 
1228
1233
  // src/integrations/mcp/annotation.ts
1234
+ var TOOL_NAME_PARAM_NAME = "tool_name";
1235
+ function isReport(whatHappened) {
1236
+ return typeof whatHappened === "string" && whatHappened.trim() !== "";
1237
+ }
1229
1238
  function registerAnnotationTool(server, options) {
1230
1239
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
1231
1240
  const description = buildAnnotationToolDescription({
@@ -1238,23 +1247,38 @@ function registerAnnotationTool(server, options) {
1238
1247
  inputSchema: {
1239
1248
  user_goal: import_zod2.z.string(),
1240
1249
  expected_result: import_zod2.z.string().optional(),
1241
- signal_type: import_zod2.z.enum(SIGNAL_TYPES).optional(),
1250
+ what_happened: import_zod2.z.string().optional(),
1251
+ // Nullable so a report whose agent sends an explicit null is taken,
1252
+ // not rejected by validation.
1253
+ tool_name: import_zod2.z.string().nullable().optional(),
1242
1254
  overall_task: import_zod2.z.string().optional(),
1243
1255
  suggested_improvement: import_zod2.z.string().optional(),
1244
1256
  context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
1245
1257
  }
1246
1258
  },
1247
1259
  async (args, extra) => {
1260
+ const whatHappened = args.what_happened;
1261
+ if (!isReport(whatHappened)) {
1262
+ return {
1263
+ content: [
1264
+ {
1265
+ type: "text",
1266
+ text: JSON.stringify({
1267
+ ok: false,
1268
+ error: `${name} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`
1269
+ })
1270
+ }
1271
+ ]
1272
+ };
1273
+ }
1274
+ const reportedTool = args.tool_name ?? null;
1248
1275
  const meta = extraMeta(extra);
1249
1276
  const scrubbedMeta = scrubOrNull(
1250
1277
  options.scrubber,
1251
1278
  meta ? roundMetaCoordinates(meta) : null,
1252
1279
  "_meta"
1253
1280
  );
1254
- const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
1255
- if (args.signal_type === void 0) {
1256
- options.tracker?.mark(sessionId);
1257
- }
1281
+ const { sessionId, origin } = await resolveSessionId(options.fallbackSessionId, extra);
1258
1282
  const principal = await resolveCallPrincipal(
1259
1283
  options.resolvePrincipal,
1260
1284
  { extra, toolName: name, arguments: args }
@@ -1270,6 +1294,7 @@ function registerAnnotationTool(server, options) {
1270
1294
  consent_token: options.consentToken,
1271
1295
  principal,
1272
1296
  transport_observed: observeTransport(extra),
1297
+ session_id_origin: origin,
1273
1298
  client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1274
1299
  runtime_meta: scrubbedMeta,
1275
1300
  payload: {
@@ -1279,15 +1304,10 @@ function registerAnnotationTool(server, options) {
1279
1304
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1280
1305
  intent: options.scrubber(args.user_goal),
1281
1306
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
1282
- // `signal_type` is a closed enum — nothing to scrub. The task label
1283
- // is agent-authored free text ("processing invoice for
1284
- // bob@example.com" is a realistic value), so it IS scrubbed.
1285
- // Python's annotation.py does NOT scrub this field — a shared
1286
- // gap found 2026-08-11, fixed here and flagged for the sibling
1287
- // rather than mirrored. Not a wire divergence: scrubbing changes
1288
- // content, not shape, and it's deterministic, so the
1289
- // exact-string continuity rung 3b groups on survives.
1290
- signal_type: args.signal_type ?? null,
1307
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1308
+ what_happened: options.scrubber(whatHappened),
1309
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1310
+ tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
1291
1311
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
1292
1312
  // split the injected params use (`overall_task` -> `call_workflow`):
1293
1313
  // renaming the param must not move the key the console groups on.
@@ -1757,11 +1777,6 @@ var ProactiveTracker = class {
1757
1777
  this.emitted.add(sessionId);
1758
1778
  return true;
1759
1779
  }
1760
- /** Mark the slot claimed without emitting here (the annotation tool's own
1761
- * handler already emitted the annotation event itself). */
1762
- mark(sessionId) {
1763
- this.emitted.add(sessionId);
1764
- }
1765
1780
  };
1766
1781
 
1767
1782
  // src/integrations/mcp/sessionCounter.ts
@@ -2039,12 +2054,12 @@ function messageOf(err) {
2039
2054
  async function resolveEnvelopeParts(ctx, extra) {
2040
2055
  const meta = extraMeta(extra);
2041
2056
  const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
2042
- const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
2043
- return { sessionId, scrubbedMeta };
2057
+ const session = await resolveSessionId(ctx.fallbackSessionId, extra);
2058
+ return { ...session, scrubbedMeta };
2044
2059
  }
2045
2060
  async function openCall(ctx, toolName, extra, params, registered = true) {
2046
2061
  await maybeEmitSurfaceSnapshot(ctx);
2047
- const { sessionId, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2062
+ const { sessionId, origin, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2048
2063
  const dispositions = ctx.paramRegistry.get(toolName);
2049
2064
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2050
2065
  const rawExpected = extractGoalParam(
@@ -2073,6 +2088,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2073
2088
  // outside any call, so it has no caller, transport or client to name.
2074
2089
  principal,
2075
2090
  transport_observed: observeTransport(extra),
2091
+ session_id_origin: origin,
2076
2092
  client_observed: observeClient(extra, ctx),
2077
2093
  runtime_meta: scrubbedMeta
2078
2094
  };
@@ -2373,8 +2389,8 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2373
2389
  };
2374
2390
  }
2375
2391
  function installToolsListSeam(lowLevel, ctx) {
2376
- const names = requiredParamNames(ctx.intentParamMode);
2377
- const isInjected = (toolName, paramName) => ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
2392
+ const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
2393
+ const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
2378
2394
  const advertise = (result) => {
2379
2395
  try {
2380
2396
  return advertiseIntentParamsRequired(result, names, isInjected);
@@ -2443,7 +2459,11 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2443
2459
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2444
2460
  try {
2445
2461
  const parts = await resolveEnvelopeParts(ctx, extra);
2446
- const principal = spec.resolvesPrincipal ? await resolveCallPrincipal(ctx.resolvePrincipal, { extra, toolName: null, arguments: {} }) : null;
2462
+ const principal = await resolveCallPrincipal(ctx.resolvePrincipal, {
2463
+ extra,
2464
+ toolName: null,
2465
+ arguments: {}
2466
+ });
2447
2467
  return {
2448
2468
  sessionId: parts.sessionId,
2449
2469
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
@@ -2454,6 +2474,7 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2454
2474
  consent_token: ctx.consentToken,
2455
2475
  principal,
2456
2476
  transport_observed: observeTransport(extra),
2477
+ session_id_origin: parts.origin,
2457
2478
  client_observed: observeClient(extra, ctx),
2458
2479
  runtime_meta: parts.scrubbedMeta
2459
2480
  }
@@ -2537,8 +2558,7 @@ var LIFECYCLE_SPECS = [
2537
2558
  error: ToolListErrorEventSchema
2538
2559
  },
2539
2560
  countKey: "tools",
2540
- startParams: NO_PARAMS,
2541
- resolvesPrincipal: true
2561
+ startParams: NO_PARAMS
2542
2562
  }
2543
2563
  ];
2544
2564
  function installLifecycleSeams(lowLevel, ctx) {
@@ -2792,6 +2812,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2792
2812
  tenant_id: tenantId,
2793
2813
  vendor_id: config.vendorId,
2794
2814
  session_id: sessionId,
2815
+ session_id_origin: "minted",
2795
2816
  consent_token: config.consentToken,
2796
2817
  sequence_number: counter2.next(sessionId),
2797
2818
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2868,7 +2889,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2868
2889
  intentParamMode
2869
2890
  });
2870
2891
  internals.server._instructions = instructions;
2871
- if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
2892
+ installToolsListSeam(internals.server, ctx);
2872
2893
  installToolsCallSeam(
2873
2894
  internals.server,
2874
2895
  // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
@@ -2898,8 +2919,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2898
2919
  // The RESOLVED name, never `config.annotationToolName`: handing over the
2899
2920
  // raw override and letting the registration re-derive would register
2900
2921
  // `srv-..._annotate` while the instructions name the server-derived one.
2901
- annotationToolName,
2902
- tracker
2922
+ annotationToolName
2903
2923
  });
2904
2924
  const existing = internals._registeredTools;
2905
2925
  if (existing) {