@goodtiming/baton-sdk 0.3.6 → 0.4.0

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
@@ -1,200 +1,81 @@
1
- # @goodtiming/baton-sdk (TypeScript)
1
+ # @goodtiming/baton-sdk
2
2
 
3
- *The TypeScript counterpart to [`baton-sdk`](https://github.com/good-timing/baton) (Python) — structured signal capture for agent-mediated tool use over MCP.*
3
+ **Pre-1.0.** The public API is not yet stable.
4
4
 
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).
5
+ MCP standardizes how agents discover and call your tools. It does not capture *why* a call happened or whether it helped the user. Baton instruments those interactions on the vendor side by wrapping your MCP server. It captures intent, the tool calls, expected outcomes and observed outcomes, plus friction signals, and hands each one to a sink.
6
6
 
7
- ## Why this exists
7
+ **The docs are at [goodtiming.ai/docs.html#typescript](https://goodtiming.ai/docs.html#typescript)**: the configuration reference, what this package captures, and what is not here yet. This page is the short version. The [Python SDK](https://pypi.org/project/baton-sdk/) takes the same DSN and emits the same events.
8
8
 
9
- Most production MCP servers are TypeScript, not Python — see the [design note](https://github.com/good-timing/baton-internal) (private) for the motivating research. `baton-sdk` (Python) can't reach that half of the ecosystem. This package is the TS-native way in, wire-compatible with the Python SDK by construction (see [Wire compatibility](#wire-compatibility) below).
9
+ ## Install
10
10
 
11
- ## What's here
12
-
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
- - `StdoutSink` — JSONL to a writable stream (default `process.stderr` — MCP stdio transport reserves stdout for JSON-RPC framing).
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)` — 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
- - Intent-param injection: `user_goal`/`expected_result`/`overall_task` string params are spliced onto every wrapped tool's advertised schema (`intentParamMode: "required"` by default, which advertises only `user_goal` as required in `tools/list` and never enforces it, so a call without it is still served; `"optional"`, which advertises none as required; 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
- - `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
- - 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`.
20
-
21
- `FileSink` / `MultiSink` are deliberately not here yet — see [What's deferred](#whats-deferred).
22
-
23
- ## What's deferred
24
-
25
- **Intent-param injection for non-zod schemas (v2 only).** v2's primary `registerTool` overload accepts any `StandardSchemaWithJSON` — ArkType, Valibot, or a hand-rolled object — and its `ZodRawShape` overload is marked `@deprecated`. A non-zod schema has no `.shape` to splice `user_goal`/`expected_result`/`overall_task` into, so such a tool is still wrapped and still emits `tool_call_*`; it just advertises no intent params. Making injection work there means decorating the schema's `~standard.jsonSchema.input()`, which advertises correctly but leaves validation with the vendor's own schema, so the injected params could not be required. Stated here rather than discovered later.
26
-
27
- **The `createMcpHandler` deployment shape (v2).** v2's flagship HTTP model builds a fresh `McpServer` per request, which would make `withBaton` run per request and turn the fallback session id, the sequence counter and the surface-snapshot dedup into request-lifetime state. Unscoped.
28
-
29
- **MRTR handling.** Investigated 2026-08-09 and **that finding is now corrected**: it concluded "blocked upstream — nothing to duck-type against," on the strength of `npm view @modelcontextprotocol/sdk` showing `1.30.0` with no `2.0.0`, beta or `next` tag. That query was scoped to a package name the 2.0 line never used, so it could not have seen the release; the detail recorded as reassuring — 1.30.0 landing one day *before* the spec — was in fact the last release before the split. MCP 2026-07-28's MRTR mechanism (`InputRequiredResult`/`input_responses`/`request_state`) ships in Python's `mcp==2.0.0` **and** in `@modelcontextprotocol/server@2.0.0`, whose type declarations carry `InputRequired` and `requestState` throughout. So there is something to port against now, and with v2 support landed MRTR is no longer behind anything — it is simply the next piece of work, and v2's **exported** type guards (`isInputRequiredResult`, `isTaskAugmentedRequestParams`) make it easier to port against than Python's duck-typed adapter. Separately and still true: the *different* multi-round-trip mechanism 1.x already has — Tasks, object handlers with `createTask` — doesn't reach the code `withBaton` wraps at all. Traced through `mcp.js`'s `CallToolRequestSchema` handler, a plain-function tool (the only kind `wrapIfNeeded` wraps) always resolves as one `await handler(args, extra)` with no server-side re-invocation; only object handlers with `createTask` take the poll/resume path, and those are already skipped by `wrapIfNeeded`'s `typeof handler !== "function"` check on the 1.x path — a separate known gap, see the module docstring in `withBaton.ts`.
30
-
31
- The low-level `Server` adapter (only the high-level `McpServer` is supported) is also not here. Neither blocks `npm publish` the way the instructions+annotate-tool pair did — see CHANGELOG.md for what's shipped.
32
-
33
- ## Usage
34
-
35
- ```bash
11
+ ```sh
36
12
  npm install @goodtiming/baton-sdk
37
13
  ```
38
14
 
15
+ Node 20+. Both major versions of the official MCP TypeScript SDK are supported, and both are **optional** peer dependencies: `@modelcontextprotocol/sdk` **1.30+** or `@modelcontextprotocol/server` 2.x. You install whichever one your server already uses and nothing else. The 1.x floor is `^1.30.0`; an older 1.x will not satisfy the peer range.
16
+
17
+ ## Quickstart
18
+
39
19
  ```typescript
40
20
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
41
21
  import { withBaton } from "@goodtiming/baton-sdk";
22
+ import { z } from "zod";
42
23
 
43
24
  const server = new McpServer({ name: "your-vendor-mcp", version: "1.0.0" });
44
25
  const handle = withBaton(server, {
45
- dsn: "https://baton_pk_...@ingest.goodtiming.ai/ten_7cd4c8cf.../your-vendor",
26
+ dsn: "https://baton_pk_...@baton.goodtiming.ai/ten_.../your-vendor",
46
27
  });
47
28
  // handle.annotationToolName === "your-vendor-mcp_annotate", from the server's own name
48
29
 
49
- // register tools before or after withBaton — both are captured
30
+ // register tools before or after withBaton; both are captured
50
31
  server.registerTool("lookup", { inputSchema: { name: z.string() } }, async ({ name }) => {
51
32
  /* ... */
52
33
  });
53
34
  ```
54
35
 
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.
36
+ 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.
59
37
 
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.
38
+ **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.
66
39
 
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:
40
+ 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.
69
41
 
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
42
+ Sending to your own collector instead, or trying the package before you have a key, means naming the parts rather than passing a DSN: [Without a DSN](https://goodtiming.ai/docs.html#without-dsn). That section's examples are Python. The config field names carry over as camelCase, and `HttpSink` takes its options as an object: `new HttpSink(url, { apiKey })`. Its timeouts do **not** carry over. Python's `request_timeout_seconds` / `backoff_base_seconds` / `backoff_max_seconds` / `circuit_breaker_reset_seconds` are `requestTimeoutMs` / `backoffBaseMs` / `backoffMaxMs` / `circuitBreakerResetMs` here, in milliseconds rather than seconds, and there is no equivalent of `shutdown_flush_timeout_seconds`.
80
43
 
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.
44
+ ## PII scrubbing
84
45
 
85
- ```typescript
86
- import { withBaton, HttpSink } from "@goodtiming/baton-sdk";
46
+ **On by default**, a rule-for-rule port of the Python SDK's ruleset: email, `Bearer` values, `sk-*` and `AKIA*` keys, JWTs, phone numbers, Luhn-checked card numbers, plus force-redaction on sensitive field names. Pass `identityScrub` to opt out, or supply your own `(value: unknown) => unknown`.
87
47
 
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
- ```
48
+ **It is pattern matching, not a guarantee.** `{"name": "Jane Doe"}` passes through untouched. Decide what your server puts in tool params and results on that basis. [What it does and does not catch](https://goodtiming.ai/docs.html#pii).
95
49
 
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
- "principal_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
- ```
50
+ ## Turning capture off
124
51
 
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
-
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.
173
-
174
- Same shape as Python's `mcp`/`fastmcp` peer relationship: the vendor's own copy, already in their tree.
52
+ `BATON_DISABLED=1` in the environment of the process running the server, and the SDK installs nothing at all. The switch belongs to whoever RUNS the server. [The long version](https://goodtiming.ai/docs.html#off-switch).
175
53
 
176
- ## Wire compatibility
54
+ Checking it worked: `handle.sink` is still an object, so finding one there is not a sign the switch failed. It is the sink you passed if you passed one, and a `DisabledSink` otherwise. Either way nothing writes to it, because nothing is wrapped.
177
55
 
178
- This is the load-bearing constraint (per [CHARTER](https://github.com/good-timing/baton/blob/main/docs/CHARTER.md) §3 rule 3): TS-emitted events must be JSON-identical in shape to Python-emitted ones, so the Console never has to branch on which SDK produced an event. `baton-spec` (submoduled at `baton-spec/`) is the neutral schema repo both SDKs are checked against, and it's enforced at two levels:
56
+ ## What is not here yet
179
57
 
180
- - **Schema** (`test/conformance.test.ts`) — validates every event type against `baton-spec/events.schema.json` (ajv) and round-trips the real, Python-captured fixtures in `baton-spec/vectors/*.json` through this package's Zod schemas byte-for-byte.
181
- - **Emitter** (`test/emitterConformance.test.ts`) — drives a real tool call through `withBaton` and diffs the *emitted* events against those same vectors, field-for-field. The scenario mirrors `baton-spec/scripts/generate.py`, the script that produced the vectors by driving the identical scenario through the Python SDK. Envelope and payload key sets must match exactly; values must match except for a short, individually-justified exemption list (`event_id`, `session_id`, `captured_at`, `sdk_version`, timings, and the genuinely language-specific bits like `error_type` and the FastMCP-vs-Zod-derived tool schemas). Event ordering and `sequence_number` assignment are asserted against the Python run too.
58
+ None of it blocks the quickstart above.
182
59
 
183
- The schema check alone can't catch an emitter that populates a field Python leaves null, starts `sequence_number` at 0, or orders events differently — hence the second level. No Python toolchain is needed in CI: the vectors are themselves real Python-emitted envelopes, so they *are* the cross-SDK reference. When the Python SDK's wire output changes, `generate.py` is re-run and the updated vectors arrive through a submodule bump — which is exactly what should fail these tests.
60
+ - Only `StdoutSink` and `HttpSink`. `FileSink` and `MultiSink` are deferred; the Python package has all four.
61
+ - Only the high-level `McpServer`. The low-level `Server` is not wrapped.
62
+ - **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.
63
+ - 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.
64
+ - The per-request `createMcpHandler` deployment shape is unscoped.
184
65
 
185
- That is not hypothetical: the submodule was pinned at the initial schema commit while Python had moved on to `call_expected`/`call_workflow`, so both conformance levels were passing against a superseded contract. Bumping to `d5e25ea` failed three tests and surfaced the real gap — `overall_task` injection was missing entirely, meaning a TS-sourced session carried no `call_workflow` for the Console to group tasks by. **Keep the submodule current; a stale pin makes these tests pass loudly and prove nothing.**
66
+ ## Wire compatibility
186
67
 
187
- ## Development
68
+ Events from this package must be JSON-identical in shape to the Python SDK's, so a collector never branches on which SDK produced one. Both are checked against [baton-spec](https://github.com/good-timing/baton-spec), a neutral schema repo: every event type is validated against the shared JSON Schema, and this package's emitter is diffed field-by-field against captured Python output for the same scenario.
188
69
 
189
- ```sh
190
- git clone --recurse-submodules https://github.com/good-timing/baton-ts.git
191
- cd baton-ts
192
- npm install
193
- npm run ci # lint + typecheck + test + build — the canonical gate, matches CI
194
- ```
70
+ Keeping that submodule current is load-bearing for contributors: a stale pin makes these tests pass loudly and prove nothing. See [`CONTRIBUTING.md`](https://github.com/good-timing/baton-ts/blob/main/CONTRIBUTING.md).
195
71
 
196
- If you cloned without `--recurse-submodules`, run `git submodule update --init` before `npm test` — the conformance tests read fixtures from `baton-spec/`.
72
+ ## More
197
73
 
198
- ## Canonical docs
74
+ | | |
75
+ |---|---|
76
+ | [goodtiming.ai/docs.html#typescript](https://goodtiming.ai/docs.html#typescript) | The docs: configuration, what it captures, the Console |
77
+ | [`docs/SPEC.md`](https://github.com/good-timing/baton/blob/main/docs/SPEC.md) | The wire protocol, in the `baton` repo. Applies here too |
78
+ | [`docs/CHARTER.md`](https://github.com/good-timing/baton/blob/main/docs/CHARTER.md) | Why the SDK is thin. Read before architectural changes |
79
+ | [`CHANGELOG.md`](https://github.com/good-timing/baton-ts/blob/main/CHANGELOG.md) | What has shipped |
199
80
 
200
- This repo has no `CHARTER.md`/`SPEC.md` of its own — those live in [`baton`](https://github.com/good-timing/baton) (`docs/CHARTER.md`, `docs/SPEC.md`) and apply here too. Read those before making architectural changes to this package.
81
+ Apache-2.0.