@goodtiming/baton-sdk 0.3.2 → 0.3.4

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
@@ -44,7 +44,7 @@ const server = new McpServer({ name: "your-vendor-mcp", version: "1.0.0" });
44
44
  const handle = withBaton(server, {
45
45
  dsn: "https://baton_pk_...@ingest.goodtiming.ai/ten_7cd4c8cf.../your-vendor",
46
46
  });
47
- // handle.annotationToolName === "your-vendor_annotate"
47
+ // handle.annotationToolName === "your-vendor-mcp_annotate", from the server's own name
48
48
 
49
49
  // register tools before or after withBaton — both are captured
50
50
  server.registerTool("lookup", { inputSchema: { name: z.string() } }, async ({ name }) => {
package/dist/index.cjs CHANGED
@@ -49,6 +49,8 @@ __export(index_exports, {
49
49
  ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
50
50
  ToolCallStartEventSchema: () => ToolCallStartEventSchema,
51
51
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
52
+ VENDOR_HASH_SCHEME: () => VENDOR_HASH_SCHEME,
53
+ hashUserId: () => hashUserId,
52
54
  identityScrub: () => identityScrub,
53
55
  safeWrite: () => safeWrite,
54
56
  withBaton: () => withBaton
@@ -56,7 +58,7 @@ __export(index_exports, {
56
58
  module.exports = __toCommonJS(index_exports);
57
59
 
58
60
  // src/version.ts
59
- var SDK_VERSION = "ts-0.3.2";
61
+ var SDK_VERSION = "ts-0.3.4";
60
62
 
61
63
  // src/events.ts
62
64
  var import_zod = require("zod");
@@ -450,33 +452,78 @@ var import_uuid2 = require("uuid");
450
452
  // src/integrations/mcp/annotation.ts
451
453
  var import_zod2 = require("zod");
452
454
 
453
- // src/integrations/mcp/emit.ts
454
- async function emit(sink, build) {
455
- let event;
456
- try {
457
- event = build();
458
- } catch (err) {
459
- process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}
460
- `);
461
- return;
462
- }
463
- await safeWrite(sink, event);
455
+ // src/identity.ts
456
+ var import_node_crypto = require("crypto");
457
+
458
+ // src/_text.ts
459
+ function capCodePoints(value, max) {
460
+ if (value.length <= max) return value;
461
+ return [...value].slice(0, max).join("");
464
462
  }
465
463
 
466
- // src/integrations/mcp/llmText.ts
467
- var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} support-signal SDK. Use \`${annotationToolName}\` to record what the user is trying to do and how each ${vendorDisplayName} tool call went. See that tool's description for field-level detail.
464
+ // src/identity.ts
465
+ var VENDOR_HASH_SCHEME = "v1";
466
+ var RAW_USER_ID_MAX_LEN = 128;
467
+ var USER_ID_MODE_HASHED = "hashed";
468
+ var USER_ID_MODE_RAW = "raw";
469
+ var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
470
+ var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
471
+ var LONE_SURROGATE = /\p{Surrogate}/u;
472
+ function canonicalize(rawPrincipal) {
473
+ return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
474
+ }
475
+ function pythonStrip(value) {
476
+ return value.replace(PYTHON_STRIP, "");
477
+ }
478
+ function hashUserId(rawPrincipal, options) {
479
+ const { tenantId, key, issuer = null, scheme } = options;
480
+ let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
481
+ if (issuer !== null) {
482
+ message += `\0${canonicalize(issuer)}`;
483
+ }
484
+ const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
485
+ const digest = (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
486
+ return `${scheme}:${digest}`;
487
+ }
488
+ function normalizePrincipal(result) {
489
+ if (result === null || typeof result !== "object") return null;
490
+ const candidate = result;
491
+ if (typeof candidate.userId !== "string") return null;
492
+ if (LONE_SURROGATE.test(candidate.userId)) return null;
493
+ if (canonicalize(candidate.userId) === "") return null;
494
+ const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
495
+ const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
496
+ return { userId: candidate.userId, issuer };
497
+ }
498
+ function userIdForPrincipal(principal, options) {
499
+ if (options.mode === USER_ID_MODE_RAW) {
500
+ return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);
501
+ }
502
+ if (options.key === null || options.key === void 0) return null;
503
+ return hashUserId(principal.userId, {
504
+ tenantId: options.tenantId,
505
+ key: options.key,
506
+ issuer: principal.issuer ?? null,
507
+ // Unconditional: this arm has no attested rung, so every principal it
508
+ // hashes is vendor-ASSERTED. A `scheme` option here would be an argument
509
+ // no caller can vary — configurability for a rung the design says is not
510
+ // coming to this SDK.
511
+ scheme: VENDOR_HASH_SCHEME
512
+ });
513
+ }
468
514
 
469
- BEFORE invoking any ${vendorDisplayName} tool, you MUST call \`${annotationToolName}\` with user_goal (REQUIRED), expected_result (REQUIRED), and overall_task (REQUIRED when the request fits a recognizable broader task, e.g., 'morning meeting prep', 'pre-outreach research').
515
+ // src/integrations/mcp/llmText.ts
516
+ 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.
470
517
 
471
518
  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).
472
519
 
473
520
  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.`;
474
- var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Record structured signal about a ${vendorDisplayName} tool call \u2014 what the user is trying to do, and how it went. Populate proactively before the call (user_goal + expected_result + overall_task) and reactively after if the result was unhelpful (signal_type + suggested_improvement).
521
+ 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.
475
522
 
476
523
  Fields:
477
524
  - user_goal: one sentence on what the user is trying to accomplish.
478
525
  - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
479
- - overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research', 'personal scheduling'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task. Skip when the call doesn't fit a recognizable broader task.
526
+ - 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.
480
527
  - 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.
481
528
  - suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
482
529
  - 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.`;
@@ -492,11 +539,14 @@ var SIGNAL_TYPES = [
492
539
  "feature_gap",
493
540
  "other"
494
541
  ];
542
+ function renderServerInstructions(options) {
543
+ return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
544
+ }
545
+ function fitsInstructionsCap(options) {
546
+ return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
547
+ }
495
548
  function buildServerInstructions(options) {
496
- const rendered = SERVER_INSTRUCTIONS_TEMPLATE(
497
- options.vendorDisplayName,
498
- options.annotationToolName
499
- );
549
+ const rendered = renderServerInstructions(options);
500
550
  if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
501
551
  throw new Error(
502
552
  `Rendered server instructions are ${rendered.length} chars, which exceeds the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
@@ -524,6 +574,99 @@ function buildExpectedResultParamDescription() {
524
574
  return EXPECTED_RESULT_PARAM_DESCRIPTION;
525
575
  }
526
576
 
577
+ // src/integrations/mcp/annotationName.ts
578
+ var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
579
+ var SUFFIX = "_annotate";
580
+ var SLUG_CAP = 30;
581
+ var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
582
+ var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
583
+ function isLibraryPlaceholder(serverName, className) {
584
+ const stripped = pythonStrip(serverName);
585
+ if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
586
+ const stem = stripped.replace(RANDOM_SUFFIX, "");
587
+ return stem !== stripped && stem === className;
588
+ }
589
+ function warn(message) {
590
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
591
+ process.emitWarning(message);
592
+ }
593
+ }
594
+ function usableServerName(read) {
595
+ let name;
596
+ let className;
597
+ try {
598
+ ({ name, className } = read());
599
+ } catch {
600
+ warn(
601
+ "baton: reading the server name failed; using the DSN's server segment and {vendorId}_annotate instead."
602
+ );
603
+ return void 0;
604
+ }
605
+ if (typeof name !== "string" || pythonStrip(name) === "") return void 0;
606
+ if (isLibraryPlaceholder(name, typeof className === "string" ? className : "")) {
607
+ return void 0;
608
+ }
609
+ return name;
610
+ }
611
+ function slugServerName(serverName) {
612
+ const mapped = pythonStrip(serverName).toLowerCase().replace(/[^a-z0-9-]/gu, "-");
613
+ const collapsed = mapped.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
614
+ return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, "") || void 0;
615
+ }
616
+ function displayNameFromServer(serverName, tool) {
617
+ if (serverName === void 0) return void 0;
618
+ const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;
619
+ if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {
620
+ warn(
621
+ `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name; keeping the DSN's server segment. Pass vendorDisplayName to choose a shorter one.`
622
+ );
623
+ return void 0;
624
+ }
625
+ return serverName;
626
+ }
627
+ function annotationToolNameFromServer(serverName, vendorDisplayName) {
628
+ if (serverName === void 0) return void 0;
629
+ const slug = slugServerName(serverName);
630
+ if (slug === void 0) return void 0;
631
+ const candidate = `${slug}${SUFFIX}`;
632
+ if (!TOOL_NAME_PATTERN.test(candidate)) return void 0;
633
+ if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
634
+ warn(
635
+ `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the server-instructions budget beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
636
+ );
637
+ return void 0;
638
+ }
639
+ return candidate;
640
+ }
641
+ function deriveAnnotationToolName(vendorId, override) {
642
+ const name = override || `${vendorId}${SUFFIX}`;
643
+ if (!TOOL_NAME_PATTERN.test(name)) {
644
+ throw new Error(
645
+ `Annotation tool name ${JSON.stringify(name)} violates the cross-runtime pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject names with dots or other separators).`
646
+ );
647
+ }
648
+ return name;
649
+ }
650
+ function resolveAnnotationToolName(serverName, config) {
651
+ return deriveAnnotationToolName(
652
+ config.vendorId,
653
+ config.annotationToolName || annotationToolNameFromServer(serverName, config.vendorDisplayName)
654
+ );
655
+ }
656
+
657
+ // src/integrations/mcp/emit.ts
658
+ async function emit(sink, build) {
659
+ let event;
660
+ try {
661
+ event = build();
662
+ } catch (err) {
663
+ process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}
664
+ `);
665
+ return;
666
+ }
667
+ await safeWrite(sink, event);
668
+ }
669
+
527
670
  // src/integrations/mcp/mcpTypes.ts
528
671
  function extraMeta(extra) {
529
672
  const direct = extra._meta;
@@ -535,6 +678,65 @@ function extraEnvelope(extra) {
535
678
  const envelope = extra.mcpReq?.envelope;
536
679
  return envelope ?? null;
537
680
  }
681
+ function extraHeaders(extra) {
682
+ const fromV2 = extra.http?.req?.headers;
683
+ if (fromV2 && typeof fromV2.get === "function") return fromV2;
684
+ const fromV1 = extra.requestInfo?.headers;
685
+ if (fromV1 && typeof fromV1 === "object") {
686
+ const headers = new Headers();
687
+ for (const [name, value] of Object.entries(fromV1)) {
688
+ for (const item of Array.isArray(value) ? value : [value]) {
689
+ if (typeof item !== "string") continue;
690
+ try {
691
+ headers.append(name, item);
692
+ } catch {
693
+ }
694
+ }
695
+ }
696
+ return headers;
697
+ }
698
+ return null;
699
+ }
700
+
701
+ // src/integrations/mcp/userResolution.ts
702
+ function buildUserResolutionContext(extra, toolName, args) {
703
+ return {
704
+ headers: extraHeaders(extra),
705
+ meta: extraMeta(extra),
706
+ toolName,
707
+ arguments: args
708
+ };
709
+ }
710
+ function warnIfIdentityCannotResolve(config) {
711
+ if (config.resolveUser === void 0) return;
712
+ if (config.userIdMode !== USER_ID_MODE_HASHED) return;
713
+ if (config.userIdHmacKey !== void 0) return;
714
+ if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
715
+ process.emitWarning(
716
+ 'baton: resolveUser is configured but no user_id HMAC key is set, so user_id is dropped from every event (events still emit). Set BATON_USER_ID_HMAC_KEY or BatonConfig.userIdHmacKey, or pass userIdMode: "raw" if you intend to emit the subject verbatim.'
717
+ );
718
+ }
719
+ async function resolveCallUserId(hook, call, options) {
720
+ if (hook === void 0) return null;
721
+ let result;
722
+ try {
723
+ const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);
724
+ result = await hook(context);
725
+ } catch {
726
+ return null;
727
+ }
728
+ const principal = normalizePrincipal(result);
729
+ if (principal === null) return null;
730
+ try {
731
+ return userIdForPrincipal(principal, {
732
+ mode: options.mode,
733
+ tenantId: options.tenantId,
734
+ key: options.key
735
+ });
736
+ } catch {
737
+ return null;
738
+ }
739
+ }
538
740
 
539
741
  // src/integrations/mcp/runtimeAdapter.ts
540
742
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
@@ -549,7 +751,7 @@ function clean(name, scrubber) {
549
751
  cleaned = scrubbed;
550
752
  }
551
753
  if (!cleaned) return null;
552
- return [...cleaned].slice(0, CLIENT_NAME_MAX_LEN).join("");
754
+ return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
553
755
  }
554
756
  function declaredOnRequest(meta, envelope) {
555
757
  for (const source of [envelope, meta]) {
@@ -595,16 +797,6 @@ async function resolveSessionId(fallbackSessionId, extra) {
595
797
  }
596
798
 
597
799
  // src/integrations/mcp/annotation.ts
598
- var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
599
- function deriveAnnotationToolName(vendorId, override) {
600
- const name = override || `${vendorId}_annotate`;
601
- if (!TOOL_NAME_PATTERN.test(name)) {
602
- throw new Error(
603
- `Annotation tool name ${JSON.stringify(name)} violates the cross-runtime pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject names with dots or other separators).`
604
- );
605
- }
606
- return name;
607
- }
608
800
  function registerAnnotationTool(server, options) {
609
801
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
610
802
  const description = buildAnnotationToolDescription({
@@ -635,6 +827,15 @@ function registerAnnotationTool(server, options) {
635
827
  if (args.signal_type === void 0) {
636
828
  options.tracker?.mark(sessionId);
637
829
  }
830
+ const userId = await resolveCallUserId(
831
+ options.resolveUser,
832
+ { extra, toolName: name, arguments: args },
833
+ {
834
+ mode: options.userIdMode,
835
+ tenantId: options.tenantId,
836
+ key: options.userIdHmacKey
837
+ }
838
+ );
638
839
  await emit(
639
840
  options.sink,
640
841
  () => AnnotationEventSchema.parse({
@@ -645,6 +846,7 @@ function registerAnnotationTool(server, options) {
645
846
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
646
847
  consent_token: options.consentToken,
647
848
  agent_runtime: runtime,
849
+ user_id: userId,
648
850
  runtime_meta: scrubbedMeta,
649
851
  payload: {
650
852
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -691,7 +893,7 @@ function containsKey(value) {
691
893
  return sweep(value) !== value;
692
894
  }
693
895
  var BARE_KEY_HINT = "this looks like a bare key, not a DSN \u2014 copy the full value from /account, which starts with https:// and ends with your server's name";
694
- function warn(message) {
896
+ function warn2(message) {
695
897
  if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
696
898
  process.emitWarning(message);
697
899
  }
@@ -755,7 +957,7 @@ function selectDsn(explicit, supplied, door) {
755
957
  const ambient = dsnFromEnvironment();
756
958
  if (ambient === void 0) return void 0;
757
959
  if (conflicts.length > 0) {
758
- warn(
960
+ warn2(
759
961
  `baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(", ")} directly, so BATON_DSN is being IGNORED and these events are NOT going to the collector it names. Remove the explicit value to use it, or unset BATON_DSN if it was meant for a different server.`
760
962
  );
761
963
  return void 0;
@@ -851,7 +1053,7 @@ function parseDsn(raw) {
851
1053
  );
852
1054
  }
853
1055
  if (key.startsWith(SECRET_PREFIX)) {
854
- warn(
1056
+ warn2(
855
1057
  `baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
856
1058
  );
857
1059
  }
@@ -882,13 +1084,19 @@ function sealKey(dsn) {
882
1084
 
883
1085
  // src/integrations/mcp/config.ts
884
1086
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1087
+ var USER_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
885
1088
  function resolveTenantId(explicit, vendorId) {
886
1089
  if (explicit) return explicit;
887
1090
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
888
1091
  if (fromEnv) return fromEnv;
889
1092
  return vendorId;
890
1093
  }
891
- function resolveBatonConfig(config) {
1094
+ function resolveUserIdHmacKey(explicit) {
1095
+ if (explicit !== void 0) return explicit;
1096
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_USER_ID_HMAC_KEY : void 0;
1097
+ return fromEnv ? fromEnv : void 0;
1098
+ }
1099
+ function resolveBatonConfig(config, serverName) {
892
1100
  const dsnString = selectDsn(
893
1101
  config.dsn,
894
1102
  {
@@ -924,7 +1132,14 @@ function resolveBatonConfig(config) {
924
1132
  // in the server instructions and the annotation tool description, which is
925
1133
  // the whitelabel obligation the validator cites when it refuses the empty
926
1134
  // one. ⚠ Python uses `or` here and still has the inconsistency.
927
- vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1135
+ //
1136
+ // Between the explicit value and the segment sits the server's own name,
1137
+ // under the guards in `annotationName.ts`: the segment is an opaque
1138
+ // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1139
+ vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1140
+ vendorId: dsn.vendorId,
1141
+ annotationToolName: config.annotationToolName
1142
+ }) ?? dsn.vendorId,
928
1143
  // `??`, not `||`: an explicit empty string must survive to the validation
929
1144
  // below and be REFUSED there, rather than be quietly replaced by the
930
1145
  // default it was deliberately not left as.
@@ -969,6 +1184,17 @@ function validateBatonConfig(config) {
969
1184
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
970
1185
  );
971
1186
  }
1187
+ if (config.resolveUser !== void 0 && typeof config.resolveUser !== "function") {
1188
+ throw new Error("BatonConfig.resolveUser must be a function.");
1189
+ }
1190
+ if (config.userIdHmacKey !== void 0 && typeof config.userIdHmacKey !== "string" && !(config.userIdHmacKey instanceof Uint8Array)) {
1191
+ throw new Error("BatonConfig.userIdHmacKey must be a string or a Uint8Array.");
1192
+ }
1193
+ if (config.userIdMode !== void 0 && !USER_ID_MODES.has(config.userIdMode)) {
1194
+ throw new Error(
1195
+ `BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ${JSON.stringify([...USER_ID_MODES].sort())}.`
1196
+ );
1197
+ }
972
1198
  }
973
1199
 
974
1200
  // src/optout.ts
@@ -1011,8 +1237,9 @@ var BatonHandle = class {
1011
1237
  * when no real per-call session id resolves. Not every event necessarily
1012
1238
  * carries this id; see `withBaton`'s session-resolution order. */
1013
1239
  sessionId;
1014
- /** The resolved annotation tool name (`{vendorId}_annotate` unless
1015
- * overridden via `BatonConfig.annotationToolName`). */
1240
+ /** The resolved annotation tool name: `BatonConfig.annotationToolName` if
1241
+ * set, else derived from the server's own name (`{slug}_annotate`), else
1242
+ * `{vendorId}_annotate`. */
1016
1243
  annotationToolName;
1017
1244
  constructor(options) {
1018
1245
  this.sink = options.sink;
@@ -1194,10 +1421,10 @@ function toolInputJsonSchema(inputSchema) {
1194
1421
  }
1195
1422
 
1196
1423
  // src/integrations/mcp/surface.ts
1197
- var import_node_crypto = require("crypto");
1424
+ var import_node_crypto2 = require("crypto");
1198
1425
  function surfaceHash(surface) {
1199
1426
  const canonical = canonicalJson(surface);
1200
- const digest = (0, import_node_crypto.createHash)("sha256").update(canonical, "utf-8").digest("hex");
1427
+ const digest = (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf-8").digest("hex");
1201
1428
  return `sha256:${digest}`;
1202
1429
  }
1203
1430
  function canonicalJson(value) {
@@ -1320,12 +1547,23 @@ function batonWrap(nameRef, original, ctx) {
1320
1547
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1321
1548
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1322
1549
  const callId = (0, import_uuid2.v7)();
1550
+ const userId = await resolveCallUserId(
1551
+ ctx.resolveUser,
1552
+ { extra, toolName, arguments: params },
1553
+ { mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey }
1554
+ );
1323
1555
  const common = {
1324
1556
  tenant_id: ctx.tenantId,
1325
1557
  vendor_id: ctx.vendorId,
1326
1558
  session_id: sessionId,
1327
1559
  consent_token: ctx.consentToken,
1328
1560
  agent_runtime: runtime,
1561
+ // The four `...common` sites below are the tool-call legs and the
1562
+ // proactive annotation — the same four Python stamps
1563
+ // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1564
+ // NOT among them: it describes the SERVER and is captured outside any
1565
+ // call, so there is no caller to name (register D5).
1566
+ user_id: userId,
1329
1567
  runtime_meta: scrubbedMeta
1330
1568
  };
1331
1569
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -1542,9 +1780,14 @@ function withBaton(server, supplied = {}) {
1542
1780
  annotationToolName: ""
1543
1781
  });
1544
1782
  }
1545
- const config = resolveBatonConfig(supplied);
1783
+ const internals = server;
1784
+ const serverName = usableServerName(() => ({
1785
+ name: internals.server._serverInfo?.name,
1786
+ className: internals.constructor.name
1787
+ }));
1788
+ const config = resolveBatonConfig(supplied, serverName);
1546
1789
  const sink = config.sink ?? new StdoutSink();
1547
- const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
1790
+ const annotationToolName = resolveAnnotationToolName(serverName, config);
1548
1791
  const intentParamMode = config.intentParamMode ?? "optional";
1549
1792
  const counter = new SessionCounter();
1550
1793
  const fallbackSessionId = `sdk-${(0, import_uuid2.v7)()}`;
@@ -1589,7 +1832,6 @@ function withBaton(server, supplied = {}) {
1589
1832
  });
1590
1833
  await sink.write(event);
1591
1834
  };
1592
- const internals = server;
1593
1835
  const bustSchemaMemo = (name) => {
1594
1836
  const memo = internals._toolInputSchemaJson;
1595
1837
  if (memo && typeof memo === "object") delete memo[name];
@@ -1628,12 +1870,16 @@ function withBaton(server, supplied = {}) {
1628
1870
  annotationToolName,
1629
1871
  intentParamMode,
1630
1872
  paramRegistry: /* @__PURE__ */ new Map(),
1873
+ resolveUser: config.resolveUser,
1874
+ userIdMode: config.userIdMode ?? "hashed",
1875
+ userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),
1631
1876
  vendorToolJsonSchema,
1632
1877
  bustSchemaMemo,
1633
1878
  tracker,
1634
1879
  surfaceState,
1635
1880
  emitSurface
1636
1881
  };
1882
+ warnIfIdentityCannotResolve(ctx);
1637
1883
  const instructions = buildServerInstructions({
1638
1884
  vendorDisplayName: config.vendorDisplayName,
1639
1885
  annotationToolName
@@ -1646,9 +1892,21 @@ function withBaton(server, supplied = {}) {
1646
1892
  vendorId: ctx.vendorId,
1647
1893
  vendorDisplayName: config.vendorDisplayName,
1648
1894
  consentToken: ctx.consentToken,
1895
+ // Read off `ctx`, never re-resolved from `config`: the two paths must
1896
+ // agree on the actor, and `userIdMode`/`userIdHmacKey` each have a
1897
+ // default and an env fallback that a second resolution could take
1898
+ // differently. Required (not optional) on the options type ON PURPOSE —
1899
+ // the compiler then refuses a registration that forgets them, which is
1900
+ // the mechanical version of "wiring two of four call sites".
1901
+ resolveUser: ctx.resolveUser,
1902
+ userIdMode: ctx.userIdMode,
1903
+ userIdHmacKey: ctx.userIdHmacKey,
1649
1904
  fallbackSessionId: ctx.fallbackSessionId,
1650
1905
  scrubber: ctx.scrubber,
1651
- annotationToolName: config.annotationToolName,
1906
+ // The RESOLVED name, never `config.annotationToolName`: handing over the
1907
+ // raw override and letting the registration re-derive would register
1908
+ // `srv-..._annotate` while the instructions name the server-derived one.
1909
+ annotationToolName,
1652
1910
  tracker
1653
1911
  });
1654
1912
  const existing = internals._registeredTools;
@@ -1691,6 +1949,8 @@ function withBaton(server, supplied = {}) {
1691
1949
  ToolCallErrorPayloadSchema,
1692
1950
  ToolCallStartEventSchema,
1693
1951
  ToolCallStartPayloadSchema,
1952
+ VENDOR_HASH_SCHEME,
1953
+ hashUserId,
1694
1954
  identityScrub,
1695
1955
  safeWrite,
1696
1956
  withBaton