@goodtiming/baton-sdk 0.5.7 → 0.5.8

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
@@ -25,7 +25,6 @@ const server = new McpServer({ name: "your-vendor-mcp", version: "1.0.0" });
25
25
  const handle = withBaton(server, {
26
26
  dsn: "https://baton_pk_...@baton.goodtiming.ai/ten_.../your-vendor",
27
27
  });
28
- // handle.annotationToolName === "your-vendor-mcp_annotate", from the server's own name
29
28
 
30
29
  // register tools before or after withBaton; both are captured
31
30
  server.registerTool("lookup", { inputSchema: { name: z.string() } }, async ({ name }) => {
@@ -35,6 +34,8 @@ server.registerTool("lookup", { inputSchema: { name: z.string() } }, async ({ na
35
34
 
36
35
  Copy the DSN from **/account**. It packs four values: the collector to send to, your workspace, this server, and the key that binds them. The SDK unpacks them and builds the sink itself.
37
36
 
37
+ **Installing changes what your server advertises.** Each tool handler is wrapped, one sentence is added below your server's own `instructions`, and a `user_goal` parameter is added to every tool's schema and stripped again before your handler sees it. With `reportMode: "on"`, a `<vendor>_annotate` tool is also registered (named from your server's own name, so `your-vendor-mcp_annotate` here), and the added text tells the agent when to report a problem with it. [What gets injected](https://goodtiming.ai/docs.html#injected-tools).
38
+
38
39
  **If you distribute your server, put the DSN in your source.** A stdio server runs on your user's machine, spawned by their MCP client. The official client SDKs pass it a fixed six-variable allowlist (`HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM`, `USER`), plus whatever that user wrote in their own client config. Nothing from your `.env` is in either list, so a server configured that way captures nothing while appearing to work.
39
40
 
40
41
  For a hosted server, where the process starts from your own environment, set `BATON_DSN` and call `withBaton(server)` with no config. An explicit `dsn` wins over `BATON_DSN`, and both win over every other `BATON_*` variable. That ordering matters when you **re-onboard** a server: the new DSN beats the old install's leftover `.env`, rather than filing your events under the previous server's name.
@@ -109,7 +110,7 @@ app.use((req, res, next) =>
109
110
  - **`wrap(toolName, fn)`** returns `fn` traced on every call, for code with no single place to put `trace()`. A single plain-object argument is recorded as `params`.
110
111
  - **`annotate(...)`** and `trace.annotate(...)` send a report your code relays from the agent.
111
112
 
112
- `INTENT_PARAMS` holds the names and wording of the three params `withBaton` adds to MCP tools. Use them to ask for the same values in your own API, then pass the answers to `trace()`.
113
+ `INTENT_PARAMS` holds the name and wording of the one param `withBaton` adds to MCP tools. Use them to ask for the same values in your own API, then pass the answers to `trace()`.
113
114
 
114
115
  Capture never throws into your code. Only the constructor throws, on a bad config. Call `await baton.aclose()` at shutdown.
115
116
 
@@ -244,7 +245,7 @@ None of it blocks the quickstart above.
244
245
 
245
246
  - Only `StdoutSink` and `HttpSink`. `FileSink` and `MultiSink` are deferred; the Python package has all four.
246
247
  - Only the high-level `McpServer`. The low-level `Server` is not wrapped.
247
- - **Task-based tools are not wrapped, and are not left alone either.** A 1.x tool registered with an object at `.handler` rather than a function produces no `tool_call_*` events at all, and nothing reports that. It still gets the intent parameters added to its advertised schema, because injection runs before the wrap is skipped and the strip only happens inside the wrapper. So `user_goal`, `expected_result` and `overall_task` can arrive in your own handler's arguments. Tools on the same server registered the ordinary way are unaffected. ⚠ **The request-level seam above does not rescue this one**: it reports only on tools this package wrapped, so a task-based tool emits nothing even for a rejected argument, where an unknown tool now emits a `tool_call_error`.
248
+ - **Task-based tools are not wrapped, and are not left alone either.** A 1.x tool registered with an object at `.handler` rather than a function produces no `tool_call_*` events at all, and nothing reports that. It still gets the intent parameters added to its advertised schema, because injection runs before the wrap is skipped and the strip only happens inside the wrapper. So `user_goal` can arrive in your own handler's arguments. Tools on the same server registered the ordinary way are unaffected. ⚠ **The request-level seam above does not rescue this one**: it reports only on tools this package wrapped, so a task-based tool emits nothing even for a rejected argument, where an unknown tool now emits a `tool_call_error`.
248
249
  - Intent parameters need a Zod schema. On the 2.x SDK a tool registered with a non-Zod standard schema is still wrapped and still emits `tool_call_*`; it just advertises no intent parameters.
249
250
  - v2's `createMcpHandler` is untested. A server built per request by your own code is supported: see [A server per request](#a-server-per-request).
250
251
 
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  EventSchema: () => EventSchema,
40
40
  EventTypeSchema: () => EventTypeSchema,
41
41
  HttpSink: () => HttpSink,
42
+ INTENT_INSTRUCTIONS: () => INTENT_INSTRUCTIONS,
42
43
  INTENT_PARAMS: () => INTENT_PARAMS,
43
44
  PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
44
45
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
@@ -96,7 +97,7 @@ __export(index_exports, {
96
97
  module.exports = __toCommonJS(index_exports);
97
98
 
98
99
  // src/version.ts
99
- var SDK_VERSION = "ts-0.5.7";
100
+ var SDK_VERSION = "ts-0.5.8";
100
101
 
101
102
  // src/events.ts
102
103
  var import_zod = require("zod");
@@ -866,25 +867,22 @@ function principalFor(principal, onUnregisteredForm) {
866
867
  }
867
868
 
868
869
  // src/integrations/mcp/llmText.ts
869
- 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.
870
+ var REPORT_POINTER_TEMPLATE = (vendorDisplayName, annotationToolName) => `Use \`${annotationToolName}\` to report a ${vendorDisplayName} tool call that went wrong, or a request no tool covers; its description says when and how.`;
871
+ var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
872
+ var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Report a ${vendorDisplayName} tool call that went wrong, so ${vendorDisplayName} can fix it. Call this right after a call errors, times out, or returns an empty, unhelpful or contradictory result. Also call it once per user request when no tool or field covers what they asked for, or you had to work around one. Do not call it before a tool call or for normal successful work.
870
873
 
871
- 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).
872
-
873
- 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.`;
874
- 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.
874
+ A report does not replace the work: after it, work out why the call failed, fix the input and try again (do not repeat the same failing call), and still answer the user.
875
875
 
876
876
  Fields:
877
- - user_goal: one sentence on what the user is trying to accomplish.
878
- - 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.
879
- - tool_name: REQUIRED on a report. The ${vendorDisplayName} tool that went wrong. Write none if no tool exists for the request.
880
- - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
881
- - 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.
882
- - suggested_improvement: A concrete sentence about what product change would have helped.
877
+ - user_goal: the same ${USER_GOAL_FORMAT} as on this server's other tools.
878
+ - what_happened: REQUIRED. 1-2 plain sentences in your own words: what you asked for, what came back, and why it was unusable. Not a category.
879
+ - tool_name: REQUIRED. The ${vendorDisplayName} tool that went wrong, or none if no tool exists for the request.
880
+ - suggested_improvement: one concrete sentence on the product change that would have helped.
883
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.`;
884
882
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
885
883
  var INSTRUCTIONS_LENGTH_CAP = 1500;
886
884
  function renderServerInstructions(options) {
887
- return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
885
+ return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
888
886
  }
889
887
  function fitsInstructionsCap(options) {
890
888
  return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
@@ -896,7 +894,7 @@ function buildServerInstructions(options) {
896
894
  `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.`
897
895
  );
898
896
  }
899
- return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
897
+ return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
900
898
  }
901
899
  function buildAnnotationToolDescription(options) {
902
900
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -904,39 +902,68 @@ function buildAnnotationToolDescription(options) {
904
902
  var USER_GOAL_PARAM_NAME = "user_goal";
905
903
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
906
904
  var OVERALL_TASK_PARAM_NAME = "overall_task";
905
+ var RETIRED_PARAM_NAMES = [EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME];
907
906
  var INTENT_SOURCE_PARAM = "injected_param";
908
907
  var INTENT_SOURCE_LIBRARY = "library_arg";
909
- var USER_GOAL_PARAM_BODY = "One sentence: what the user is actually trying to accomplish with this call (their goal, not a restatement of the arguments).";
908
+ var USER_GOAL_PARAM_BODY = `Write it as ${USER_GOAL_FORMAT}. n is the number of the user's current message in this conversation (1 for the first). Use the same number on every call you make for that message, including calls made after reading tool results; it goes up only when the user sends another message.`;
910
909
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
911
910
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
912
- var EXPECTED_RESULT_PARAM_BODY = "One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
913
- var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
914
- var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
915
- var OVERALL_TASK_PARAM_BODY = "The number of the user's current message in this conversation (1 for the first), a colon, then a short stable label for the broader task this call serves (e.g. '3: prepare campaign approval'). Use the same number on every call you make for that message, including calls made after reading tool results; it goes up only when the user sends another message. REPEAT the exact same label text after the colon on every call serving the same task, across messages; change the label only when the user starts a different task.";
916
- var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
917
- var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
918
- var INSTRUCTIONS_SUBAGENT_CLAUSE = "\n\nWhen you hand work to a subagent that may call this server's tools, tell it the number of the user's current message in this conversation, and that it must start overall_task with that number on every call to this server's tools. This applies only to this server's tools.";
911
+ var INSTRUCTIONS_SUBAGENT_CLAUSE = "\n\nWhen you hand work to a subagent that may call this server's tools, tell it the number of the user's current message in this conversation, and that it must start user_goal with that number on every call to this server's tools. This applies only to this server's tools.";
912
+ var INTENT_INSTRUCTIONS = INSTRUCTIONS_SUBAGENT_CLAUSE.trim();
919
913
  function buildUserGoalParamDescription(options = {}) {
920
914
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
921
915
  }
922
- function buildOverallTaskParamDescription(options = {}) {
923
- return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
916
+ function requiredParamNames(intentParamMode) {
917
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME] : [];
924
918
  }
925
- function buildExpectedResultParamDescription(options = {}) {
926
- return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
919
+ function declaresParam(schema, name) {
920
+ const props = schema?.properties;
921
+ return typeof props === "object" && props !== null && name in props;
927
922
  }
928
- function requiredParamNames(intentParamMode) {
929
- return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
923
+ function instructionsSuffixServed(annotationToolName, served) {
924
+ if (annotationToolName) return true;
925
+ return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
930
926
  }
931
927
  var INTENT_PARAMS = Object.freeze([
932
- Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" }),
933
- Object.freeze({
934
- name: EXPECTED_RESULT_PARAM_NAME,
935
- description: EXPECTED_RESULT_PARAM_BODY,
936
- traceOption: "expectedOutcome"
937
- }),
938
- Object.freeze({ name: OVERALL_TASK_PARAM_NAME, description: OVERALL_TASK_PARAM_BODY, traceOption: "workflow" })
928
+ Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
939
929
  ]);
930
+ var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
931
+ var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
932
+ var OURS_STARTS = [
933
+ new RegExp(
934
+ "^" + REPORT_POINTER_TEMPLATE("\0", "\0").split("\0").map(escapeRegExp).join(".+?")
935
+ ),
936
+ new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
937
+ ];
938
+ function endsInOurs(current2, vendor) {
939
+ if (typeof current2 !== "string") return false;
940
+ const prefix = typeof vendor === "string" && vendor.trim() ? `${vendor}
941
+
942
+ ` : "";
943
+ if (!current2.startsWith(prefix)) return false;
944
+ const rest = current2.slice(prefix.length);
945
+ return OURS_STARTS.some((start) => start.test(rest));
946
+ }
947
+ function withVendorInstructions(server, ours, warn4 = (message) => process.stderr.write(message)) {
948
+ const holder = server;
949
+ const current2 = holder._instructions;
950
+ let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
951
+ if (!endsInOurs(current2, vendor)) {
952
+ vendor = current2;
953
+ holder[VENDOR_INSTRUCTIONS] = vendor;
954
+ }
955
+ if (typeof vendor !== "string" || !vendor.trim()) return ours;
956
+ const combined = `${vendor}
957
+
958
+ ${ours}`;
959
+ if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
960
+ warn4(
961
+ `baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there
962
+ `
963
+ );
964
+ }
965
+ return combined;
966
+ }
940
967
 
941
968
  // src/integrations/mcp/annotationName.ts
942
969
  var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
@@ -1293,12 +1320,10 @@ function registerAnnotationTool(server, options) {
1293
1320
  description,
1294
1321
  inputSchema: {
1295
1322
  user_goal: import_zod2.z.string(),
1296
- expected_result: import_zod2.z.string().optional(),
1297
1323
  what_happened: import_zod2.z.string().optional(),
1298
1324
  // Nullable so a report whose agent sends an explicit null is taken,
1299
1325
  // not rejected by validation.
1300
1326
  tool_name: import_zod2.z.string().nullable().optional(),
1301
- overall_task: import_zod2.z.string().optional(),
1302
1327
  suggested_improvement: import_zod2.z.string().optional(),
1303
1328
  context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
1304
1329
  }
@@ -1345,21 +1370,13 @@ function registerAnnotationTool(server, options) {
1345
1370
  client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1346
1371
  runtime_meta: scrubbedMeta,
1347
1372
  payload: {
1348
- // Agent-facing names -> wire keys, as with `overall_task`
1349
- // below: `user_goal` is stored as `intent`, `expected_result` as
1350
- // `expected_outcome`.
1373
+ // The agent-facing `user_goal` is stored as the wire key `intent`.
1351
1374
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1352
1375
  intent: options.scrubber(args.user_goal),
1353
- expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
1354
1376
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1355
1377
  what_happened: options.scrubber(whatHappened),
1356
1378
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1357
1379
  tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
1358
- // Agent-facing param `overall_task` -> wire key `workflow`, the same
1359
- // split the injected params use (`overall_task` -> `call_workflow`):
1360
- // renaming the param must not move the key the console groups on.
1361
- // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1362
- workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
1363
1380
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1364
1381
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1365
1382
  context: args.context ? options.scrubber(args.context) : null
@@ -1645,7 +1662,8 @@ function scrubbedErrorBody(scrubber, text) {
1645
1662
  }
1646
1663
 
1647
1664
  // src/integrations/mcp/config.ts
1648
- var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1665
+ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
1666
+ var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
1649
1667
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1650
1668
  function resolveTenantId(explicit, vendorId2) {
1651
1669
  if (explicit) return explicit;
@@ -1730,9 +1748,14 @@ function validateBatonConfig(config) {
1730
1748
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
1731
1749
  );
1732
1750
  }
1733
- if (!config.vendorDisplayName) {
1751
+ if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
1752
+ throw new Error(
1753
+ `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
1754
+ );
1755
+ }
1756
+ if (!config.vendorDisplayName && config.reportMode === "on") {
1734
1757
  throw new Error(
1735
- "BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
1758
+ 'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
1736
1759
  );
1737
1760
  }
1738
1761
  if (config.consentToken !== void 0 && !config.consentToken) {
@@ -1745,6 +1768,11 @@ function validateBatonConfig(config) {
1745
1768
  "BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
1746
1769
  );
1747
1770
  }
1771
+ if (config.intentParamMode === "off") {
1772
+ throw new Error(
1773
+ 'BatonConfig.intentParamMode: "off" would leave nothing capturing what the user is trying to do. Use "required" (the default) or "optional".'
1774
+ );
1775
+ }
1748
1776
  if (config.intentParamMode !== void 0 && !INTENT_PARAM_MODES.has(config.intentParamMode)) {
1749
1777
  throw new Error(
1750
1778
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
@@ -1930,17 +1958,14 @@ function injectGoalParams(inputSchema, intentParamMode) {
1930
1958
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1931
1959
  const dispositions = {};
1932
1960
  const toInject = {};
1933
- for (const [name, buildDescription] of [
1934
- [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1935
- [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1936
- [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1937
- ]) {
1938
- if (name in existingShape) {
1939
- dispositions[name] = "native";
1940
- } else {
1941
- dispositions[name] = "injected";
1942
- toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1943
- }
1961
+ for (const name of RETIRED_PARAM_NAMES) {
1962
+ if (name in existingShape) dispositions[name] = "native";
1963
+ }
1964
+ if (USER_GOAL_PARAM_NAME in existingShape) {
1965
+ dispositions[USER_GOAL_PARAM_NAME] = "native";
1966
+ } else {
1967
+ dispositions[USER_GOAL_PARAM_NAME] = "injected";
1968
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1944
1969
  }
1945
1970
  return { dispositions, toInject };
1946
1971
  }
@@ -2020,12 +2045,12 @@ function assembleSurface(serverMeta, tools) {
2020
2045
  function buildSeamAugmentations(options) {
2021
2046
  return {
2022
2047
  injected_tools: [...options.injectedToolNames].sort(),
2023
- intent_param: options.intentParamMode !== "off" ? {
2048
+ intent_param: {
2024
2049
  names: [...options.intentParamNames].sort(),
2025
2050
  required_names: [...options.requiredParamNames].sort(),
2026
2051
  mode: options.intentParamMode
2027
- } : null,
2028
- instructions_suffix: true
2052
+ },
2053
+ instructions_suffix: options.instructionsSuffix
2029
2054
  };
2030
2055
  }
2031
2056
 
@@ -2095,22 +2120,15 @@ async function resolveEnvelopeParts(ctx, extra) {
2095
2120
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
2096
2121
  return { ...session, scrubbedMeta };
2097
2122
  }
2098
- async function openCall(ctx, toolName, extra, params, registered = true) {
2123
+ async function openCall(ctx, toolName, extra, params, retired, registered = true) {
2099
2124
  await maybeEmitSurfaceSnapshot(ctx);
2100
2125
  const { sessionId, origin, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2101
2126
  const dispositions = ctx.paramRegistry.get(toolName);
2102
2127
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2103
- const rawExpected = extractGoalParam(
2104
- params,
2105
- EXPECTED_RESULT_PARAM_NAME,
2106
- toolName,
2107
- dispositions,
2108
- registered
2109
- );
2110
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
2111
2128
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2112
- const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
2113
- const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
2129
+ const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
2130
+ (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
2131
+ );
2114
2132
  const principal = await resolveCallPrincipal(
2115
2133
  ctx.resolvePrincipal,
2116
2134
  { extra, toolName, arguments: params }
@@ -2157,7 +2175,9 @@ function batonWrap(nameRef, original, ctx) {
2157
2175
  if (slot) slot.innerFired = true;
2158
2176
  const extra = callArgs[callArgs.length - 1];
2159
2177
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2160
- const { common, sessionId } = await openCall(ctx, toolName, extra, params);
2178
+ const retired = slot?.retired ?? {};
2179
+ if (slot) slot.retired = {};
2180
+ const { common, sessionId } = await openCall(ctx, toolName, extra, params, retired);
2161
2181
  const terminate = async (build, replacement) => {
2162
2182
  if (!slot) {
2163
2183
  await emit(ctx.sink, build);
@@ -2325,10 +2345,28 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2325
2345
  `
2326
2346
  );
2327
2347
  }
2348
+ return popText(args, paramName);
2349
+ }
2350
+ function popText(args, paramName) {
2351
+ if (!(paramName in args)) return null;
2328
2352
  const raw = args[paramName];
2329
2353
  delete args[paramName];
2330
2354
  return typeof raw === "string" && raw.trim() ? raw : null;
2331
2355
  }
2356
+ function stripRetiredParams(params, ctx) {
2357
+ const toolName = params?.name;
2358
+ const args = params?.arguments;
2359
+ if (typeof toolName !== "string") return {};
2360
+ if (toolName === ctx.annotationToolName) return {};
2361
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
2362
+ const dispositions = ctx.paramRegistry.get(toolName);
2363
+ const retired = {};
2364
+ for (const name of RETIRED_PARAM_NAMES) {
2365
+ if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
2366
+ retired[name] = popText(args, name);
2367
+ }
2368
+ return retired;
2369
+ }
2332
2370
  var MAX_REMEMBERED_SURFACES = 1024;
2333
2371
  async function maybeEmitSurfaceSnapshot(ctx) {
2334
2372
  if (!ctx.surfaceState.dirty) return;
@@ -2348,10 +2386,11 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2348
2386
  if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2349
2387
  emitted.add(digest);
2350
2388
  const seam = buildSeamAugmentations({
2351
- injectedToolNames: [ctx.annotationToolName],
2352
- intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2389
+ injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
2390
+ intentParamNames: [USER_GOAL_PARAM_NAME],
2353
2391
  intentParamMode: ctx.intentParamMode,
2354
- requiredParamNames: requiredParamNames(ctx.intentParamMode)
2392
+ requiredParamNames: requiredParamNames(ctx.intentParamMode),
2393
+ instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
2355
2394
  });
2356
2395
  try {
2357
2396
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
@@ -2362,11 +2401,19 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2362
2401
  ctx.surfaceState.dirty = true;
2363
2402
  }
2364
2403
  }
2404
+ function declaredIntentParams(vendorSchema) {
2405
+ const declared2 = {};
2406
+ for (const name of [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES]) {
2407
+ if (declaresParam(vendorSchema, name)) declared2[name] = "native";
2408
+ }
2409
+ return declared2;
2410
+ }
2365
2411
  function captureAndInject(name, entry, ctx) {
2366
2412
  if (!entry || typeof entry !== "object") return;
2367
2413
  const mutable = entry;
2368
- ctx.surfaceState.noteTool(name, ctx.vendorToolJsonSchema(name, mutable.inputSchema), mutable.description);
2369
- if (ctx.intentParamMode === "off") return;
2414
+ const vendorSchema = ctx.vendorToolJsonSchema(name, mutable.inputSchema);
2415
+ ctx.surfaceState.noteTool(name, vendorSchema, mutable.description);
2416
+ if (declaresParam(vendorSchema, USER_GOAL_PARAM_NAME)) ctx.dropSubagentClause(name);
2370
2417
  const isV2 = typeof mutable.executor === "function";
2371
2418
  try {
2372
2419
  const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema, ctx.intentParamMode) : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);
@@ -2374,9 +2421,10 @@ function captureAndInject(name, entry, ctx) {
2374
2421
  mutable.inputSchema = schema;
2375
2422
  ctx.bustSchemaMemo(name);
2376
2423
  ctx.paramRegistry.set(name, dispositions);
2377
- if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2378
2424
  } else {
2379
- ctx.paramRegistry.delete(name);
2425
+ const declared2 = declaredIntentParams(vendorSchema);
2426
+ if (Object.keys(declared2).length > 0) ctx.paramRegistry.set(name, declared2);
2427
+ else ctx.paramRegistry.delete(name);
2380
2428
  }
2381
2429
  } catch {
2382
2430
  }
@@ -2618,7 +2666,12 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2618
2666
  TOOLS_CALL_METHOD,
2619
2667
  TOOLS_CALL_SEAM,
2620
2668
  (handler) => async (...args) => {
2621
- const slot = { innerFired: false, flushTerminal: null };
2669
+ const request = args[0];
2670
+ const slot = {
2671
+ innerFired: false,
2672
+ flushTerminal: null,
2673
+ retired: stripRetiredParams(request?.params, ctx)
2674
+ };
2622
2675
  let outcome = CLEAN_OUTCOME;
2623
2676
  try {
2624
2677
  const result = await callSlots.run(slot, () => handler(...args));
@@ -2643,13 +2696,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2643
2696
  }
2644
2697
  if (slot.innerFired) return;
2645
2698
  if (!outcome.failed) return;
2646
- await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2699
+ await emitRequestSideFailure(outcome, args, slot.retired, toolEntry, ctx);
2647
2700
  } catch (err) {
2648
2701
  process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2649
2702
  `);
2650
2703
  }
2651
2704
  }
2652
- async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2705
+ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
2653
2706
  const request = args[0];
2654
2707
  const toolName = request?.params?.name;
2655
2708
  if (typeof toolName !== "string") return;
@@ -2657,13 +2710,7 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2657
2710
  const entry = toolEntry(toolName);
2658
2711
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2659
2712
  const params = { ...request?.params?.arguments ?? {} };
2660
- const { common, sessionId } = await openCall(
2661
- ctx,
2662
- toolName,
2663
- args[1],
2664
- params,
2665
- entry != null
2666
- );
2713
+ const { common, sessionId } = await openCall(ctx, toolName, args[1], params, retired, entry != null);
2667
2714
  const failureKind = requestSideFailureKind(entry);
2668
2715
  await emit(
2669
2716
  ctx.sink,
@@ -2781,7 +2828,9 @@ function withBaton(server, supplied = {}) {
2781
2828
  annotationToolName: ""
2782
2829
  });
2783
2830
  }
2784
- return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
2831
+ const resolved = resolveBatonConfig(supplied);
2832
+ warnUnusedReportSettings(resolved);
2833
+ return install(server, supplied, resolved, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
2785
2834
  }
2786
2835
  function createBaton(supplied = {}) {
2787
2836
  const disabledBy = captureDisabled();
@@ -2792,7 +2841,8 @@ function createBaton(supplied = {}) {
2792
2841
  }, flush: () => unused.flush(), aclose: () => unused.aclose() };
2793
2842
  }
2794
2843
  const resolved = resolveBatonConfig(supplied);
2795
- deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2844
+ warnUnusedReportSettings(resolved);
2845
+ if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2796
2846
  const sink = resolved.sink ?? new StdoutSink();
2797
2847
  const config = {
2798
2848
  ...resolved,
@@ -2800,23 +2850,25 @@ function createBaton(supplied = {}) {
2800
2850
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2801
2851
  };
2802
2852
  const emittedSurfaceHashes = /* @__PURE__ */ new Set();
2853
+ const warned2 = /* @__PURE__ */ new Set();
2803
2854
  return {
2804
2855
  wrap: (server) => {
2805
- install(server, supplied, config, emittedSurfaceHashes);
2856
+ install(server, supplied, config, emittedSurfaceHashes, warned2);
2806
2857
  },
2807
2858
  flush: () => sink.flush(),
2808
2859
  aclose: () => sink.aclose()
2809
2860
  };
2810
2861
  }
2811
- function install(server, supplied, resolved, emittedSurfaceHashes) {
2862
+ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
2812
2863
  const internals = server;
2813
2864
  const serverName = usableServerName(() => ({
2814
2865
  name: internals.server._serverInfo?.name,
2815
2866
  className: internals.constructor.name
2816
2867
  }));
2817
- const config = withServerDisplayName(resolved, supplied, serverName);
2868
+ const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
2818
2869
  const sink = config.sink ?? new StdoutSink();
2819
- const annotationToolName = resolveAnnotationToolName(serverName, config);
2870
+ const reports = reportsFor(config);
2871
+ const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
2820
2872
  const intentParamMode = config.intentParamMode ?? "required";
2821
2873
  const counter2 = new SessionCounter();
2822
2874
  const fallbackSessionId = `sdk-${uuid7()}`;
@@ -2848,12 +2900,23 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2848
2900
  const memo = internals._toolInputSchemaJson;
2849
2901
  if (memo && typeof memo === "object") delete memo[name];
2850
2902
  };
2903
+ const warnOnce = (key, message) => {
2904
+ if (warned2.has(key)) return;
2905
+ warned2.add(key);
2906
+ process.stderr.write(message);
2907
+ };
2851
2908
  const dropSubagentClause = (name) => {
2852
2909
  const current2 = internals.server._instructions;
2853
- if (typeof current2 !== "string" || !current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2854
- internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2855
- process.stderr.write(
2856
- `baton: tool ${JSON.stringify(name)} declares its own overall_task, so the subagent sentence was removed from the server instructions; a session that already started keeps it
2910
+ if (current2 === INTENT_INSTRUCTIONS) {
2911
+ internals.server._instructions = "";
2912
+ } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
2913
+ internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2914
+ } else {
2915
+ return;
2916
+ }
2917
+ warnOnce(
2918
+ "native-user-goal",
2919
+ `baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent sentence was removed from the server instructions; a session that already started keeps it
2857
2920
  `
2858
2921
  );
2859
2922
  };
@@ -2895,15 +2958,16 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2895
2958
  vendorToolJsonSchema,
2896
2959
  bustSchemaMemo,
2897
2960
  dropSubagentClause,
2961
+ servedInstructions: () => internals.server._instructions,
2898
2962
  surfaceState,
2899
2963
  emitSurface
2900
2964
  };
2901
- const instructions = buildServerInstructions({
2902
- vendorDisplayName: config.vendorDisplayName,
2903
- annotationToolName,
2904
- intentParamMode
2905
- });
2906
- internals.server._instructions = instructions;
2965
+ const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
2966
+ internals.server._instructions = withVendorInstructions(
2967
+ internals.server,
2968
+ ours,
2969
+ (message) => warnOnce("instructions-length", message)
2970
+ );
2907
2971
  installToolsListSeam(internals.server, ctx);
2908
2972
  installToolsCallSeam(
2909
2973
  internals.server,
@@ -2921,12 +2985,12 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2921
2985
  ctx
2922
2986
  );
2923
2987
  installLifecycleSeams(internals.server, ctx);
2924
- const resolvedAnnotationToolName = registerAnnotationTool(server, {
2988
+ const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
2925
2989
  sink,
2926
2990
  counter: ctx.counter,
2927
2991
  tenantId: ctx.tenantId,
2928
2992
  vendorId: ctx.vendorId,
2929
- vendorDisplayName: config.vendorDisplayName,
2993
+ vendorDisplayName: reports.vendorDisplayName,
2930
2994
  consentToken: ctx.consentToken,
2931
2995
  resolvePrincipal: ctx.resolvePrincipal,
2932
2996
  fallbackSessionId: ctx.fallbackSessionId,
@@ -2955,6 +3019,18 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2955
3019
  annotationToolName: resolvedAnnotationToolName
2956
3020
  });
2957
3021
  }
3022
+ function reportsFor(config) {
3023
+ if (config.reportMode !== "on") return void 0;
3024
+ return { vendorDisplayName: config.vendorDisplayName ?? "" };
3025
+ }
3026
+ function warnUnusedReportSettings(config) {
3027
+ if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
3028
+ process.stderr.write(
3029
+ `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
3030
+ `
3031
+ );
3032
+ }
3033
+ }
2958
3034
 
2959
3035
  // src/integrations/mcp/oauthHooks.ts
2960
3036
  function claimsOf(context) {
@@ -3475,6 +3551,7 @@ var Client = class {
3475
3551
  EventSchema,
3476
3552
  EventTypeSchema,
3477
3553
  HttpSink,
3554
+ INTENT_INSTRUCTIONS,
3478
3555
  INTENT_PARAMS,
3479
3556
  PRINCIPAL_FORM_HASHED,
3480
3557
  PRINCIPAL_FORM_RAW,