@goodtiming/baton-sdk 0.2.0 → 0.3.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  *The TypeScript counterpart to [`baton-sdk`](https://github.com/good-timing/baton) (Python) — structured signal capture for agent-mediated tool use over MCP.*
4
4
 
5
- **Status: published — [`@goodtiming/baton-sdk@0.1.0`](https://www.npmjs.com/package/@goodtiming/baton-sdk) on npm.** `withBaton` instruments a high-level `McpServer` — **either** official SDK major, 1.x (`@modelcontextprotocol/sdk`) or v2 (`@modelcontextprotocol/server`): wraps every tool call, injects server `instructions`, registers the `<vendor>_annotate` tool (SPEC §5.1.1–§5.1.2), injects `user_goal`/`expected_result`/`overall_task` intent params on every wrapped tool's schema, captures a `surface_snapshot` of the vendor-true surface, and PII-scrubs every payload with the same default ruleset the Python SDK ships. What's still not here: intent-param injection for **non-zod** schemas on v2, MRTR (Python's `_is_mrtr_pause`/`_is_mrtr_continuation`), and the low-level `Server` adapter — see [What's deferred](#whats-deferred).
5
+ **Status: published — [`@goodtiming/baton-sdk@0.3.0`](https://www.npmjs.com/package/@goodtiming/baton-sdk) on npm.** `withBaton` instruments a high-level `McpServer` — **either** official SDK major, 1.x (`@modelcontextprotocol/sdk`) or v2 (`@modelcontextprotocol/server`): wraps every tool call, injects server `instructions`, registers the `<vendor>_annotate` tool (SPEC §5.1.1–§5.1.2), injects `user_goal`/`expected_result`/`overall_task` intent params on every wrapped tool's schema, captures a `surface_snapshot` of the vendor-true surface, and PII-scrubs every payload with the same default ruleset the Python SDK ships. What's still not here: intent-param injection for **non-zod** schemas on v2, MRTR (Python's `_is_mrtr_pause`/`_is_mrtr_continuation`), and the low-level `Server` adapter — see [What's deferred](#whats-deferred).
6
6
 
7
7
  ## Why this exists
8
8
 
@@ -13,7 +13,7 @@ Most production MCP servers are TypeScript, not Python — see the [design note]
13
13
  - `Event` — a Zod-validated discriminated union over the five event types (`tool_call_start`, `tool_call_end`, `tool_call_error`, `annotation`, `surface_snapshot`), field-for-field with the Python SDK's Pydantic models.
14
14
  - `StdoutSink` — JSONL to a writable stream (default `process.stderr` — MCP stdio transport reserves stdout for JSON-RPC framing).
15
15
  - `HttpSink` — `POST {url}/v0/events` with bearer auth, bounded buffer, retry with backoff, circuit breaker. The contract any Baton-compatible collector consumes.
16
- - `withBaton(server, config)` — wraps every tool call on a high-level `McpServer` from either SDK major (both optional peer dependencies) and emits `tool_call_start` / `tool_call_end` / `tool_call_error`. Works regardless of whether tools are registered before or after `withBaton` runs, and survives a tool's `.update()`/`.remove()` after the fact too (see the module docstring in `src/integrations/mcp/withBaton.ts` for why that ordering/mutation independence is load-bearing, not incidental). Also injects server `instructions` and registers the `<vendor>_annotate` tool so the calling agent can supply structured intent/outcome/friction signal — same behavioral contract as Python's adapters, ported byte-for-byte (verified against the Python SDK's actual rendered output, not just eyeballed).
16
+ - `withBaton(server, config)` — takes a packed `dsn` (the one string from /account) or the parts named individually, and wraps every tool call on a high-level `McpServer` from either SDK major (both optional peer dependencies) and emits `tool_call_start` / `tool_call_end` / `tool_call_error`. Works regardless of whether tools are registered before or after `withBaton` runs, and survives a tool's `.update()`/`.remove()` after the fact too (see the module docstring in `src/integrations/mcp/withBaton.ts` for why that ordering/mutation independence is load-bearing, not incidental). Also injects server `instructions` and registers the `<vendor>_annotate` tool so the calling agent can supply structured intent/outcome/friction signal — same behavioral contract as Python's adapters, ported byte-for-byte (verified against the Python SDK's actual rendered output, not just eyeballed).
17
17
  - Intent-param injection — `user_goal`/`expected_result`/`overall_task` string params are spliced onto every wrapped tool's advertised schema (`intentParamMode: "optional"` by default, `"required"` — which promotes only `user_goal` — or `"off"`), stripped before the vendor handler runs, and surfaced as `tool_call_start.payload.call_intent`/`call_expected`/`call_workflow`/`intent_source` plus a synthesised proactive `annotation` (at most one per session). `call_intent`/`call_expected` are call-scoped diagnostics that reword freely; `call_workflow` is the task-label grouping key the Console segments sessions on, which is why its injected param description carries an explicit repeat-the-exact-string contract. This is the capture path that survives runtimes which drop `instructions` entirely (notably Claude Desktop). A tool that already declares one of these names itself is left alone for that field (`"native"` disposition) — its value is forwarded to the vendor untouched, not captured as intent. A tool registered with no `inputSchema` at all is left alone regardless of mode, so a zero-arg handler's calling convention never changes underneath it.
18
18
  - `surface_snapshot` capture — the vendor-true (pre-injection) `server_info`/`capabilities`/`instructions`/tool list, hashed and emitted at most once per observed hash (lazily, on the first tool call — the high-level `McpServer` exposes no `tools/list` hook to capture on eagerly). Baton's own additions (the annotate tool, the injected params) are reported separately under `seam_augmentations`, never folded into the vendor-true snapshot.
19
19
  - PII scrubbing — every payload (tool params/results, `_meta`, intent strings, error bodies) runs through `Scrubber` before it reaches any sink, **on by default**. The ruleset is a rule-for-rule port of Python's `baton.scrub` (email, `Bearer` values, `sk-*` keys, `AKIA*` keys, JWTs, phone numbers, Luhn-checked card numbers, plus force-redaction on sensitive field names) — parity verified by mirroring Python's test matrix case-for-case *and* by diffing both implementations' output over a shared corpus. Pass `identityScrub` to opt out explicitly, or supply your own `(value: unknown) => unknown`.
@@ -38,37 +38,137 @@ npm install @goodtiming/baton-sdk
38
38
 
39
39
  ```typescript
40
40
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
41
- import { withBaton, StdoutSink } from "@goodtiming/baton-sdk";
41
+ import { withBaton } from "@goodtiming/baton-sdk";
42
42
 
43
43
  const server = new McpServer({ name: "your-vendor-mcp", version: "1.0.0" });
44
44
  const handle = withBaton(server, {
45
- vendorId: "your-vendor", // the SERVER
46
- tenantId: "ten_7cd4c8cf", // the ACCOUNT — not the same thing
47
- vendorDisplayName: "Your Vendor",
48
- consentToken: process.env.BATON_CONSENT_TOKEN!,
49
- sink: new StdoutSink(), // swap in HttpSink(...) to ship to a collector
45
+ dsn: "https://baton_pk_...@ingest.goodtiming.ai/ten_7cd4c8cf.../your-vendor",
50
46
  });
51
47
  // handle.annotationToolName === "your-vendor_annotate"
52
48
 
53
- // `tenantId` names the ACCOUNT the collector authenticates; `vendorId` names
54
- // the server whose surface is captured. One account wraps many servers, so
55
- // sending the account id in both slots collapses them into one. Resolved
56
- // explicit → `BATON_TENANT_ID` → `vendorId`; that last fallback is a
57
- // migration shim, not a supported configuration.
58
- //
59
- // Stated on its own line on purpose — it is the diff your reviewer reads. If
60
- // you would rather keep it out of source, leave `tenantId` off entirely and
61
- // set `BATON_TENANT_ID` in the environment; the SDK reads it. Do NOT write
62
- // `process.env.BATON_TENANT_ID!` — `tenantId` is optional, so the `!` buys no
63
- // check and an unset variable silently falls back to `vendorId`, which is the
64
- // collapse described above wearing the look of a configured account.
65
-
66
49
  // register tools before or after withBaton — both are captured
67
50
  server.registerTool("lookup", { inputSchema: { name: z.string() } }, async ({ name }) => {
68
51
  /* ... */
69
52
  });
70
53
  ```
71
54
 
55
+ That one string is the whole configuration. Copy it from **/account**, where
56
+ it is labelled DSN. It packs four values — the collector to send to, your
57
+ workspace, this server, and the key that binds them — and the SDK unpacks them
58
+ and builds the sink itself.
59
+
60
+ **If you distribute your server, put the DSN in your source.** A stdio server
61
+ runs on your user's machine, spawned by their MCP client — and the official
62
+ client SDKs pass it a fixed six-variable allowlist (`HOME`, `LOGNAME`, `PATH`,
63
+ `SHELL`, `TERM`, `USER`), plus whatever that user wrote in their own client
64
+ config. Nothing from your `.env` is in either list, so a server configured that
65
+ way captures nothing while appearing to work.
66
+
67
+ If you would rather not put it in source — a hosted server, where the process
68
+ starts from your own environment — set `BATON_DSN` instead and pass nothing:
69
+
70
+ ```typescript
71
+ const handle = withBaton(server); // reads BATON_DSN
72
+ ```
73
+
74
+ An explicit `dsn` wins over `BATON_DSN`, and both win over every other
75
+ `BATON_*` variable. That last rule matters when you **re-onboard** a server:
76
+ the new DSN beats the old install's leftover `.env`, rather than the stale file
77
+ quietly filing your events under the previous server's name.
78
+
79
+ ### Without a DSN
80
+
81
+ Two cases do not have one: you are sending to **your own collector** rather than
82
+ a hosted one, or you are trying the package out before you have a key. Name the
83
+ parts instead.
84
+
85
+ ```typescript
86
+ import { withBaton, HttpSink } from "@goodtiming/baton-sdk";
87
+
88
+ const handle = withBaton(server, {
89
+ vendorId: "your-vendor", // the SERVER whose surface is captured
90
+ tenantId: "ten_7cd4c8cf", // the ACCOUNT the collector authenticates
91
+ vendorDisplayName: "Your Vendor",
92
+ sink: new HttpSink("https://your-collector.example.com", { apiKey: "..." }),
93
+ });
94
+ ```
95
+
96
+ Leave `sink` off and events go to stderr as JSON Lines — the quickest way to
97
+ see that capture works at all, and the fastest way to see exactly what is
98
+ collected. One real line from that stream, pretty-printed:
99
+
100
+ ```json
101
+ {
102
+ "event_id": "01a091a9-24d0-732e-9e92-8165c2018a93",
103
+ "tenant_id": "ten_7cd4c8cf9a0e4b1d8f2a6c3e5b7d9f10",
104
+ "vendor_id": "your-vendor",
105
+ "session_id": "sdk-01a091a9-24c8-72c8-a64e-e49164e1f568",
106
+ "sequence_number": 3,
107
+ "captured_at": "2026-09-11T18:09:36.463Z",
108
+ "consent_token": "customer-consented",
109
+ "sdk_version": "ts-0.3.0",
110
+ "agent_runtime": "unknown",
111
+ "user_id": null,
112
+ "runtime_meta": null,
113
+ "event_type": "tool_call_start",
114
+ "payload": {
115
+ "tool_name": "lookup",
116
+ "params": { "name": "ACME Corp" },
117
+ "call_intent": "check the ACME account",
118
+ "call_expected": null,
119
+ "call_workflow": null,
120
+ "intent_source": "injected_param"
121
+ }
122
+ }
123
+ ```
124
+
125
+ `params` is the tool's own arguments, scrubbed. `call_intent` is what the
126
+ calling agent said it was trying to do, captured through the injected
127
+ `user_goal` param. The matching `tool_call_end` carries the result and a
128
+ duration; a `surface_snapshot` of your tool list goes out once per session.
129
+
130
+ `vendorId` and `tenantId` are different things, and one account wraps many
131
+ servers — put the account id in both and two servers render as one, whose label
132
+ flips to whichever deployed last. A DSN carries both, so this form is the only
133
+ one that can get it wrong. `tenantId` resolves explicit → `BATON_TENANT_ID` →
134
+ `vendorId`, and that last fallback is a migration shim: an unset
135
+ `BATON_TENANT_ID` produces the collapse rather than an error.
136
+
137
+ Every other option — the intent-param mode, a session-id resolver, your own
138
+ scrubber — is set the same way with or without a DSN. Passing a `dsn` **and** an
139
+ explicit `vendorId`, `tenantId` or `sink` throws: two sources for one value
140
+ cannot be reconciled without guessing, and a wrong guess routes a server's
141
+ traffic under someone else's identity. `consentToken` defaults to a value the
142
+ SDK supplies, so you never carry one.
143
+
144
+ ### Turning capture off
145
+
146
+ `BATON_DISABLED=1` in the environment of the process running the server, and
147
+ this package installs nothing at all: no tool wrapping, no annotation tool, no
148
+ instructions rewrite, no collector connection. (`handle.sink` is still an
149
+ object — a `DisabledSink` that holds no key, opens no socket and discards what
150
+ it is given — so finding one there is not a sign the switch failed.) Your server starts and behaves exactly as it
151
+ would with the `withBaton` line deleted. It is read once at startup, it never
152
+ writes to stdout (which is the JSON-RPC stream), and it cannot make your server
153
+ fail to boot — a config this package would otherwise refuse is accepted and
154
+ ignored while the switch is on.
155
+
156
+ The switch belongs to whoever RUNS the server. For a server you distribute,
157
+ that is your user. For one you host, it is you — your users cannot set an
158
+ environment variable on your machine, and there is no per-user opt-out today.
159
+
160
+ **If you pass this on to your users, say where the variable goes.** For a
161
+ server started by an MCP client, it belongs in the `env` block for your server
162
+ in that client's config file — **not in their shell**. MCP clients spawn
163
+ servers with a fixed, short allowlist of environment variables — six names on
164
+ macOS and Linux, a different dozen on Windows — and `BATON_DISABLED` is on
165
+ neither, so an exported one never reaches your process.
166
+ Someone who follows "set the environment variable" gets a server that is still
167
+ capturing and believes it is not.
168
+
169
+ What you tell your users about what is captured is yours to write, on your own
170
+ surface. This package does not put words in your README beyond the switch.
171
+
72
172
  Both `@modelcontextprotocol/sdk` (1.x) and `@modelcontextprotocol/server` (v2) are declared as **optional** peer dependencies: install whichever your server is built on, and nothing here resolves the other. This package imports neither — not at runtime, and not as a type, so a v2-only tree typechecks as well as it runs. `withBaton` takes the exported structural `SupportedMcpServer` type that both majors' `McpServer` classes satisfy, which is also how you annotate the parameter in your own code.
73
173
 
74
174
  Same shape as Python's `mcp`/`fastmcp` peer relationship: the vendor's own copy, already in their tree.
package/dist/index.cjs CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  AnnotationEventSchema: () => AnnotationEventSchema,
34
34
  AnnotationPayloadSchema: () => AnnotationPayloadSchema,
35
35
  BatonHandle: () => BatonHandle,
36
+ DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
36
37
  DEPTH_LIMIT: () => DEPTH_LIMIT,
37
38
  EventSchema: () => EventSchema,
38
39
  EventTypeSchema: () => EventTypeSchema,
@@ -55,7 +56,7 @@ __export(index_exports, {
55
56
  module.exports = __toCommonJS(index_exports);
56
57
 
57
58
  // src/version.ts
58
- var SDK_VERSION = "ts-0.2.0";
59
+ var SDK_VERSION = "ts-0.3.1";
59
60
 
60
61
  // src/events.ts
61
62
  var import_zod = require("zod");
@@ -97,6 +98,7 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
97
98
  tools: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
98
99
  seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
99
100
  }).strict();
101
+ var DEFAULT_CONSENT_TOKEN = "customer-consented";
100
102
  var envelopeShape = {
101
103
  event_id: import_zod.z.uuid().default(() => (0, import_uuid.v7)()),
102
104
  tenant_id: import_zod.z.string(),
@@ -320,6 +322,25 @@ var HttpSink = class _HttpSink {
320
322
  );
321
323
  this.fetchImpl = options.fetchImpl ?? fetch;
322
324
  }
325
+ /**
326
+ * What this sink shows when something prints it — never the bearer.
327
+ *
328
+ * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
329
+ * hangs off `BatonHandle.sink` and off the resolved config, so
330
+ * `console.log(handle.sink)` or a structured logger serialising either one
331
+ * wrote a publishable key into the vendor's logs. Found by the S2 test that
332
+ * asserts the DSN's own string does not survive resolution: it does not, and
333
+ * the key was one field further down. Same treatment as the parsed DSN —
334
+ * `toJSON` for serialisers, the inspect symbol for `console.log`, and
335
+ * `Symbol.for` rather than importing `node:util`, since this package runs on
336
+ * runtimes that have no such module.
337
+ */
338
+ toJSON() {
339
+ return { url: this.url, apiKey: "<key>" };
340
+ }
341
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
342
+ return this.toJSON();
343
+ }
323
344
  async write(event) {
324
345
  if (this.closed) throw new Error("HttpSink is closed");
325
346
  this.enqueue(event);
@@ -513,11 +534,6 @@ function extraMeta(extra) {
513
534
  // src/integrations/mcp/runtimeAdapter.ts
514
535
  function detectAgentRuntime(meta) {
515
536
  if (!meta) return null;
516
- const batonMeta = meta["baton"];
517
- if (batonMeta && typeof batonMeta === "object") {
518
- const runtime = batonMeta["agent_runtime"];
519
- if (typeof runtime === "string" && runtime) return runtime;
520
- }
521
537
  for (const key of Object.keys(meta)) {
522
538
  if (key.startsWith("claudecode/")) return "claude-code";
523
539
  }
@@ -622,8 +638,194 @@ function registerAnnotationTool(server, options) {
622
638
  return name;
623
639
  }
624
640
 
625
- // src/integrations/mcp/config.ts
641
+ // src/dsn.ts
626
642
  var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
643
+ var WORKSPACE_PATTERN = /^ten_[0-9a-fA-F]{32}$/;
644
+ var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
645
+ var NOT_IN_A_KEY = /[\x00\n\r]/;
646
+ var PUBLISHABLE_PREFIX = "baton_pk_";
647
+ var SECRET_PREFIX = "baton_sk_";
648
+ var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
649
+ function looksLikeAKey(value) {
650
+ return value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX);
651
+ }
652
+ function containsKey(value) {
653
+ return sweep(value) !== value;
654
+ }
655
+ 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";
656
+ function warn(message) {
657
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
658
+ process.emitWarning(message);
659
+ }
660
+ }
661
+ function splitDsn(raw) {
662
+ const schemeEnd = raw.indexOf("://");
663
+ if (schemeEnd === -1) return null;
664
+ const scheme = raw.slice(0, schemeEnd).toLowerCase();
665
+ const rest = raw.slice(schemeEnd + 3);
666
+ const end = rest.search(/[/?#]/);
667
+ if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
668
+ const netloc = rest.slice(0, end);
669
+ if (rest[end] !== "/") {
670
+ return { scheme, netloc, slash: "", path: "" };
671
+ }
672
+ const afterSlash = rest.slice(end + 1);
673
+ const pathEnd = afterSlash.search(/[?#]/);
674
+ return {
675
+ scheme,
676
+ netloc,
677
+ slash: "/",
678
+ path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd)
679
+ };
680
+ }
681
+ function splitKeyFromAuthority(netloc) {
682
+ const index = netloc.lastIndexOf("@");
683
+ if (index === -1) return { key: "", at: false, authority: netloc };
684
+ return { key: netloc.slice(0, index), at: true, authority: netloc.slice(index + 1) };
685
+ }
686
+ function redact(raw) {
687
+ const parts = splitDsn(raw);
688
+ if (parts === null) return "<dsn>";
689
+ const { at, authority } = splitKeyFromAuthority(parts.netloc);
690
+ const assembled = at ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}` : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;
691
+ return sweep(assembled);
692
+ }
693
+ function sweep(message) {
694
+ return message.replace(KEY_RUN, "<key>");
695
+ }
696
+ function fail(message) {
697
+ throw new Error(sweep(message));
698
+ }
699
+ function dsnFromEnvironment() {
700
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
701
+ return fromEnv ? fromEnv : void 0;
702
+ }
703
+ function selectDsn(explicit, supplied, door) {
704
+ const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
705
+ if (explicit) {
706
+ if (conflicts.length > 0) {
707
+ fail(
708
+ `${door} got both a dsn and an explicit ${conflicts[0]} \u2014 the dsn already supplies it. Drop one: the dsn is the single value from /account, and ${conflicts[0]} is what it unpacks to.`
709
+ );
710
+ }
711
+ return explicit;
712
+ }
713
+ const ambient = dsnFromEnvironment();
714
+ if (ambient === void 0) return void 0;
715
+ if (conflicts.length > 0) {
716
+ warn(
717
+ `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.`
718
+ );
719
+ return void 0;
720
+ }
721
+ return ambient;
722
+ }
723
+ function parseDsn(raw) {
724
+ if (typeof raw !== "string" || raw.trim() === "") {
725
+ fail("dsn must be a non-empty string");
726
+ }
727
+ const dsn = raw.trim();
728
+ if (looksLikeAKey(dsn)) {
729
+ fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
730
+ }
731
+ const safe = redact(dsn);
732
+ const parts = splitDsn(dsn);
733
+ if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
734
+ fail(
735
+ `dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
736
+ );
737
+ }
738
+ const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
739
+ if (!at || !key) {
740
+ if (looksLikeAKey(parts.netloc)) {
741
+ fail(
742
+ `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
743
+ );
744
+ }
745
+ const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
746
+ const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
747
+ fail(
748
+ `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
749
+ );
750
+ }
751
+ if (NOT_IN_A_KEY.test(key)) {
752
+ fail(
753
+ `dsn ${safe} has a line break or a null inside its key \u2014 those can never be sent in an Authorization header, so this DSN could not have worked. Check for a line wrap where the value was copied.`
754
+ );
755
+ }
756
+ if (key.includes(":")) {
757
+ fail(
758
+ `dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
759
+ );
760
+ }
761
+ if (!authority) {
762
+ fail(`dsn ${safe} has no host`);
763
+ }
764
+ if (NOT_IN_A_HOST.test(authority)) {
765
+ fail(
766
+ `dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
767
+ );
768
+ }
769
+ let hostReason = null;
770
+ let parsedAuthority = null;
771
+ try {
772
+ parsedAuthority = new URL(`${parts.scheme}://${authority}`);
773
+ } catch (error) {
774
+ hostReason = error instanceof Error ? error.constructor.name : "Error";
775
+ }
776
+ if (parsedAuthority === null) {
777
+ fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
778
+ }
779
+ const segments = parts.path.split("/").filter((segment) => segment !== "");
780
+ const [workspace, server, ...extra] = segments;
781
+ if (workspace === void 0 || server === void 0 || extra.length > 0) {
782
+ fail(
783
+ `dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_<32 hex>/<server>. A missing server is never defaulted: it is what the key is bound to.`
784
+ );
785
+ }
786
+ for (const [slot, segment] of [
787
+ ["workspace", workspace],
788
+ ["server", server]
789
+ ]) {
790
+ if (containsKey(segment)) {
791
+ fail(
792
+ `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_<32 hex>/<server>`
793
+ );
794
+ }
795
+ }
796
+ if (!WORKSPACE_PATTERN.test(workspace)) {
797
+ fail(
798
+ `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
799
+ );
800
+ }
801
+ if (!VENDOR_ID_PATTERN.test(server)) {
802
+ fail(
803
+ `dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
804
+ );
805
+ }
806
+ if (key.startsWith(SECRET_PREFIX)) {
807
+ warn(
808
+ `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.`
809
+ );
810
+ }
811
+ return sealKey({
812
+ origin: `${parts.scheme}://${authority}`,
813
+ tenantId: workspace,
814
+ vendorId: server,
815
+ key
816
+ });
817
+ }
818
+ function sealKey(dsn) {
819
+ const shown = { origin: dsn.origin, tenantId: dsn.tenantId, vendorId: dsn.vendorId, key: "<key>" };
820
+ Object.defineProperty(dsn, "toJSON", { value: () => shown, enumerable: false });
821
+ Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
822
+ value: () => shown,
823
+ enumerable: false
824
+ });
825
+ return dsn;
826
+ }
827
+
828
+ // src/integrations/mcp/config.ts
627
829
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
628
830
  function resolveTenantId(explicit, vendorId) {
629
831
  if (explicit) return explicit;
@@ -631,7 +833,62 @@ function resolveTenantId(explicit, vendorId) {
631
833
  if (fromEnv) return fromEnv;
632
834
  return vendorId;
633
835
  }
836
+ function resolveBatonConfig(config) {
837
+ const dsnString = selectDsn(
838
+ config.dsn,
839
+ {
840
+ // Truthiness per field, mirroring Python's `bool()` / `is not None`
841
+ // split: an empty `vendorId` is an unset one, while an explicitly
842
+ // supplied `tenantId` or `sink` is a conflict whatever it holds.
843
+ vendorId: Boolean(config.vendorId),
844
+ tenantId: config.tenantId !== void 0,
845
+ sink: config.sink !== void 0
846
+ },
847
+ "BatonConfig"
848
+ );
849
+ if (dsnString === void 0) {
850
+ const defaulted = {
851
+ ...config,
852
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
853
+ };
854
+ validateBatonConfig(defaulted);
855
+ return defaulted;
856
+ }
857
+ const dsn = parseDsn(dsnString);
858
+ const rest = { ...config };
859
+ delete rest.dsn;
860
+ const identity = {
861
+ ...rest,
862
+ vendorId: dsn.vendorId,
863
+ tenantId: dsn.tenantId,
864
+ // `??`, for the same reason as `consentToken` directly below, and the
865
+ // inconsistency was worth fixing rather than mirroring: with no dsn,
866
+ // `vendorDisplayName: ""` is REFUSED by validation; with one, `||` quietly
867
+ // substituted the server slug. One input, two answers, decided by whether
868
+ // a dsn happens to be present — and this string reaches the calling agent
869
+ // in the server instructions and the annotation tool description, which is
870
+ // the whitelabel obligation the validator cites when it refuses the empty
871
+ // one. ⚠ Python uses `or` here and still has the inconsistency.
872
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
873
+ // `??`, not `||`: an explicit empty string must survive to the validation
874
+ // below and be REFUSED there, rather than be quietly replaced by the
875
+ // default it was deliberately not left as.
876
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
877
+ };
878
+ validateBatonConfig(identity);
879
+ return {
880
+ ...identity,
881
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events`
882
+ // itself, exactly as it does for an explicitly-constructed sink.
883
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
884
+ };
885
+ }
634
886
  function validateBatonConfig(config) {
887
+ if (!config.vendorId) {
888
+ throw new Error(
889
+ "BatonConfig needs a vendorId \u2014 either directly, or via a dsn whose last path segment names the server (see /account)."
890
+ );
891
+ }
635
892
  if (!VENDOR_ID_PATTERN.test(config.vendorId)) {
636
893
  throw new Error(
637
894
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
@@ -642,6 +899,11 @@ function validateBatonConfig(config) {
642
899
  "BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
643
900
  );
644
901
  }
902
+ if (config.consentToken !== void 0 && !config.consentToken) {
903
+ throw new Error(
904
+ "BatonConfig.consentToken was set to an empty string, and events without a valid consent_token MUST be rejected by the consumer per SPEC \xA72.3. Omit it to take the SDK's default."
905
+ );
906
+ }
645
907
  if (!config.consentToken) {
646
908
  throw new Error(
647
909
  "BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
@@ -654,6 +916,38 @@ function validateBatonConfig(config) {
654
916
  }
655
917
  }
656
918
 
919
+ // src/optout.ts
920
+ var SWITCH = "BATON_DISABLED";
921
+ var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
922
+ function captureDisabled() {
923
+ const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
924
+ if (value !== void 0 && !OFF_VALUES.has(value.trim().toLowerCase())) {
925
+ return SWITCH;
926
+ }
927
+ return null;
928
+ }
929
+ function logDisabled(switchName, surface) {
930
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
931
+ process.emitWarning(
932
+ `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
933
+ );
934
+ }
935
+ }
936
+ var DisabledSink = class {
937
+ // The parameter is omitted rather than named-and-ignored: a narrower
938
+ // signature satisfies `Sink` in TypeScript, and there is nothing to do with
939
+ // an event that cannot arrive.
940
+ async write() {
941
+ return;
942
+ }
943
+ async flush() {
944
+ return;
945
+ }
946
+ async aclose() {
947
+ return;
948
+ }
949
+ };
950
+
657
951
  // src/integrations/mcp/handle.ts
658
952
  var BatonHandle = class {
659
953
  sink;
@@ -1169,8 +1463,25 @@ function wireEntry(name, entry, ctx) {
1169
1463
  };
1170
1464
  }
1171
1465
  }
1172
- function withBaton(server, config) {
1173
- validateBatonConfig(config);
1466
+ function withBaton(server, supplied = {}) {
1467
+ const disabledBy = captureDisabled();
1468
+ if (disabledBy !== null) {
1469
+ logDisabled(disabledBy, "withBaton");
1470
+ return new BatonHandle({
1471
+ // A sink the VENDOR constructed is held rather than dropped, so their
1472
+ // `handle.aclose()` still releases it — we took ownership of that object
1473
+ // the moment they passed it, and the switch does not undo that. Nothing
1474
+ // writes to it: nothing is wrapped.
1475
+ sink: supplied.sink ?? new DisabledSink(),
1476
+ // Empty, and a constant, because when the switch is on nothing was
1477
+ // resolved: inventing a session id would put a real identifier on a
1478
+ // handle whose whole meaning is that no events exist under it.
1479
+ vendorId: "",
1480
+ sessionId: "baton-disabled",
1481
+ annotationToolName: ""
1482
+ });
1483
+ }
1484
+ const config = resolveBatonConfig(supplied);
1174
1485
  const sink = config.sink ?? new StdoutSink();
1175
1486
  const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
1176
1487
  const intentParamMode = config.intentParamMode ?? "optional";
@@ -1289,6 +1600,7 @@ function withBaton(server, config) {
1289
1600
  AnnotationEventSchema,
1290
1601
  AnnotationPayloadSchema,
1291
1602
  BatonHandle,
1603
+ DEFAULT_CONSENT_TOKEN,
1292
1604
  DEPTH_LIMIT,
1293
1605
  EventSchema,
1294
1606
  EventTypeSchema,