@goodtiming/baton-sdk 0.3.5 → 0.3.7
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 +41 -160
- package/dist/index.cjs +134 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -6
- package/dist/index.d.ts +18 -6
- package/dist/index.js +134 -14
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,200 +1,81 @@
|
|
|
1
|
-
# @goodtiming/baton-sdk
|
|
1
|
+
# @goodtiming/baton-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Pre-1.0.** The public API is not yet stable.
|
|
4
4
|
|
|
5
|
-
|
|
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
|
-
|
|
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
|
-
|
|
9
|
+
## Install
|
|
10
10
|
|
|
11
|
-
|
|
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: "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
|
-
- `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_...@
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
`
|
|
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
|
-
|
|
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
|
-
|
|
56
|
+
## What is not here yet
|
|
179
57
|
|
|
180
|
-
|
|
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
|
-
|
|
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
|
-
|
|
66
|
+
## Wire compatibility
|
|
186
67
|
|
|
187
|
-
|
|
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
|
-
|
|
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
|
-
|
|
72
|
+
## More
|
|
197
73
|
|
|
198
|
-
|
|
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
|
-
|
|
81
|
+
Apache-2.0.
|
package/dist/index.cjs
CHANGED
|
@@ -58,7 +58,7 @@ __export(index_exports, {
|
|
|
58
58
|
module.exports = __toCommonJS(index_exports);
|
|
59
59
|
|
|
60
60
|
// src/version.ts
|
|
61
|
-
var SDK_VERSION = "ts-0.3.
|
|
61
|
+
var SDK_VERSION = "ts-0.3.7";
|
|
62
62
|
|
|
63
63
|
// src/events.ts
|
|
64
64
|
var import_zod = require("zod");
|
|
@@ -112,6 +112,7 @@ var envelopeShape = {
|
|
|
112
112
|
sdk_version: import_zod.z.string().default(SDK_VERSION),
|
|
113
113
|
agent_runtime: import_zod.z.string().default("unknown"),
|
|
114
114
|
principal_id: import_zod.z.string().nullable().default(null),
|
|
115
|
+
transport_observed: import_zod.z.string().nullable().default(null),
|
|
115
116
|
call_id: import_zod.z.string().nullable().default(null),
|
|
116
117
|
runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
|
|
117
118
|
};
|
|
@@ -452,6 +453,51 @@ var import_uuid2 = require("uuid");
|
|
|
452
453
|
// src/integrations/mcp/annotation.ts
|
|
453
454
|
var import_zod2 = require("zod");
|
|
454
455
|
|
|
456
|
+
// src/metaCoordinates.ts
|
|
457
|
+
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
458
|
+
var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
459
|
+
function isPlainObject2(value) {
|
|
460
|
+
if (typeof value !== "object" || value === null) return false;
|
|
461
|
+
const proto = Object.getPrototypeOf(value);
|
|
462
|
+
return proto === Object.prototype || proto === null;
|
|
463
|
+
}
|
|
464
|
+
function toOneDecimal(value) {
|
|
465
|
+
const magnitude = Math.abs(value);
|
|
466
|
+
if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
|
|
467
|
+
const tenths = Math.floor(magnitude * 10);
|
|
468
|
+
const even = tenths % 2 === 0 ? tenths : tenths + 1;
|
|
469
|
+
return (Math.sign(value) * even / 10).toFixed(1);
|
|
470
|
+
}
|
|
471
|
+
return value.toFixed(1);
|
|
472
|
+
}
|
|
473
|
+
function roundCoordinate(value) {
|
|
474
|
+
if (typeof value === "number") {
|
|
475
|
+
return Number.isFinite(value) && !Number.isInteger(value) ? Number(toOneDecimal(value)) : void 0;
|
|
476
|
+
}
|
|
477
|
+
if (typeof value === "string" && DECIMAL_STRING.test(value)) {
|
|
478
|
+
return toOneDecimal(Number(value));
|
|
479
|
+
}
|
|
480
|
+
return void 0;
|
|
481
|
+
}
|
|
482
|
+
function walk(value, depth) {
|
|
483
|
+
if (depth >= DEPTH_LIMIT) return value;
|
|
484
|
+
if (isPlainObject2(value)) {
|
|
485
|
+
const out = {};
|
|
486
|
+
for (const [k, v] of Object.entries(value)) {
|
|
487
|
+
const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
|
|
488
|
+
out[k] = rounded ?? walk(v, depth + 1);
|
|
489
|
+
}
|
|
490
|
+
return out;
|
|
491
|
+
}
|
|
492
|
+
if (Array.isArray(value)) {
|
|
493
|
+
return value.map((item) => walk(item, depth + 1));
|
|
494
|
+
}
|
|
495
|
+
return value;
|
|
496
|
+
}
|
|
497
|
+
function roundMetaCoordinates(meta) {
|
|
498
|
+
return walk(meta, 0);
|
|
499
|
+
}
|
|
500
|
+
|
|
455
501
|
// src/identity.ts
|
|
456
502
|
var import_node_crypto = require("crypto");
|
|
457
503
|
|
|
@@ -561,11 +607,13 @@ var USER_GOAL_PARAM_NAME = "user_goal";
|
|
|
561
607
|
var EXPECTED_RESULT_PARAM_NAME = "expected_result";
|
|
562
608
|
var OVERALL_TASK_PARAM_NAME = "overall_task";
|
|
563
609
|
var INTENT_SOURCE_PARAM = "injected_param";
|
|
564
|
-
var
|
|
610
|
+
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).";
|
|
611
|
+
var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
|
|
612
|
+
var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
|
|
565
613
|
var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
|
|
566
614
|
var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. Short stable label for the broader task this call serves (e.g. 'prepare campaign approval'). REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.";
|
|
567
|
-
function buildUserGoalParamDescription() {
|
|
568
|
-
return USER_GOAL_PARAM_DESCRIPTION;
|
|
615
|
+
function buildUserGoalParamDescription(options = {}) {
|
|
616
|
+
return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
|
|
569
617
|
}
|
|
570
618
|
function buildOverallTaskParamDescription() {
|
|
571
619
|
return OVERALL_TASK_PARAM_DESCRIPTION;
|
|
@@ -678,6 +726,14 @@ function extraEnvelope(extra) {
|
|
|
678
726
|
const envelope = extra.mcpReq?.envelope;
|
|
679
727
|
return envelope ?? null;
|
|
680
728
|
}
|
|
729
|
+
function observeTransport(extra) {
|
|
730
|
+
try {
|
|
731
|
+
const carrier = extra.http?.req ?? extra.requestInfo;
|
|
732
|
+
return carrier ? "http" : "no-http-request";
|
|
733
|
+
} catch {
|
|
734
|
+
return "read-failed";
|
|
735
|
+
}
|
|
736
|
+
}
|
|
681
737
|
function extraHeaders(extra) {
|
|
682
738
|
const fromV2 = extra.http?.req?.headers;
|
|
683
739
|
if (fromV2 && typeof fromV2.get === "function") return fromV2;
|
|
@@ -835,7 +891,7 @@ function registerAnnotationTool(server, options) {
|
|
|
835
891
|
server,
|
|
836
892
|
scrubber: options.scrubber
|
|
837
893
|
}) ?? UNKNOWN_AGENT_RUNTIME;
|
|
838
|
-
const scrubbedMeta = meta ? options.scrubber(meta) : null;
|
|
894
|
+
const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
|
|
839
895
|
const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
|
|
840
896
|
if (args.signal_type === void 0) {
|
|
841
897
|
options.tracker?.mark(sessionId);
|
|
@@ -860,6 +916,7 @@ function registerAnnotationTool(server, options) {
|
|
|
860
916
|
consent_token: options.consentToken,
|
|
861
917
|
agent_runtime: runtime,
|
|
862
918
|
principal_id: principalId,
|
|
919
|
+
transport_observed: observeTransport(extra),
|
|
863
920
|
runtime_meta: scrubbedMeta,
|
|
864
921
|
payload: {
|
|
865
922
|
// Agent-facing names -> wire keys, as with `overall_task`
|
|
@@ -1387,28 +1444,28 @@ function toJsonSchemaCompat(schema, opts) {
|
|
|
1387
1444
|
var import_zod3 = require("zod");
|
|
1388
1445
|
var import_v3 = require("zod/v3");
|
|
1389
1446
|
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
1390
|
-
function injectGoalParams(inputSchema) {
|
|
1447
|
+
function injectGoalParams(inputSchema, intentParamMode) {
|
|
1391
1448
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
1392
1449
|
if (!objSchema) return { schema: inputSchema, dispositions: {} };
|
|
1393
1450
|
const existingShape = getObjectShape(objSchema) ?? {};
|
|
1394
1451
|
const values = Object.values(existingShape);
|
|
1395
1452
|
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
1396
1453
|
const zodImpl = useV4 ? import_zod3.z : import_v3.z;
|
|
1397
|
-
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl);
|
|
1454
|
+
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
1398
1455
|
if (Object.keys(toInject).length === 0)
|
|
1399
1456
|
return { schema: inputSchema, dispositions };
|
|
1400
1457
|
const mergedShape = { ...existingShape, ...toInject };
|
|
1401
1458
|
const newSchema = objectFromShape(mergedShape);
|
|
1402
1459
|
return { schema: newSchema, dispositions };
|
|
1403
1460
|
}
|
|
1404
|
-
function buildIntentFields(existingShape, zodImpl) {
|
|
1461
|
+
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
1405
1462
|
const dispositions = {};
|
|
1406
1463
|
const toInject = {};
|
|
1407
1464
|
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
1408
1465
|
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
1409
1466
|
} else {
|
|
1410
1467
|
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
1411
|
-
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription());
|
|
1468
|
+
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
1412
1469
|
}
|
|
1413
1470
|
for (const [name, buildDescription] of [
|
|
1414
1471
|
[EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
|
|
@@ -1423,17 +1480,35 @@ function buildIntentFields(existingShape, zodImpl) {
|
|
|
1423
1480
|
}
|
|
1424
1481
|
return { dispositions, toInject };
|
|
1425
1482
|
}
|
|
1426
|
-
function injectGoalParamsV2(inputSchema) {
|
|
1483
|
+
function injectGoalParamsV2(inputSchema, intentParamMode) {
|
|
1427
1484
|
const candidate = inputSchema;
|
|
1428
1485
|
const shape = candidate?.shape;
|
|
1429
1486
|
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
1430
1487
|
return { schema: inputSchema, dispositions: {} };
|
|
1431
1488
|
}
|
|
1432
|
-
const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z);
|
|
1489
|
+
const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
|
|
1433
1490
|
if (Object.keys(toInject).length === 0)
|
|
1434
1491
|
return { schema: inputSchema, dispositions };
|
|
1435
1492
|
return { schema: candidate.extend(toInject), dispositions };
|
|
1436
1493
|
}
|
|
1494
|
+
function advertiseUserGoalRequired(result, isInjected) {
|
|
1495
|
+
const tools = result?.tools;
|
|
1496
|
+
if (!Array.isArray(tools)) return result;
|
|
1497
|
+
let changed = false;
|
|
1498
|
+
const advertised = tools.map((tool) => {
|
|
1499
|
+
const entry = tool;
|
|
1500
|
+
if (typeof entry?.name !== "string" || !isInjected(entry.name)) return tool;
|
|
1501
|
+
const schema = entry.inputSchema;
|
|
1502
|
+
if (!schema || typeof schema !== "object") return tool;
|
|
1503
|
+
const declared = schema.required ?? [];
|
|
1504
|
+
if (!Array.isArray(declared)) return tool;
|
|
1505
|
+
const required = declared;
|
|
1506
|
+
if (required.includes(USER_GOAL_PARAM_NAME)) return tool;
|
|
1507
|
+
changed = true;
|
|
1508
|
+
return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };
|
|
1509
|
+
});
|
|
1510
|
+
return changed ? { ...result, tools: advertised } : result;
|
|
1511
|
+
}
|
|
1437
1512
|
function toolInputJsonSchema(inputSchema) {
|
|
1438
1513
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
1439
1514
|
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
@@ -1555,7 +1630,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
1555
1630
|
server: ctx.server,
|
|
1556
1631
|
scrubber: ctx.scrubber
|
|
1557
1632
|
}) ?? UNKNOWN_AGENT_RUNTIME;
|
|
1558
|
-
const scrubbedMeta = meta ? ctx.scrubber(meta) : null;
|
|
1633
|
+
const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
|
|
1559
1634
|
const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
1560
1635
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
1561
1636
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
|
|
@@ -1587,6 +1662,10 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
1587
1662
|
// NOT among them: it describes the SERVER and is captured outside any
|
|
1588
1663
|
// call, so there is no caller to name (register D5).
|
|
1589
1664
|
principal_id: principalId,
|
|
1665
|
+
// Same four stamps, same exclusion: a surface_snapshot describes the
|
|
1666
|
+
// SERVER and is captured outside any call, so it has no caller's
|
|
1667
|
+
// transport to name any more than it has a caller to name.
|
|
1668
|
+
transport_observed: observeTransport(extra),
|
|
1590
1669
|
runtime_meta: scrubbedMeta
|
|
1591
1670
|
};
|
|
1592
1671
|
if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
|
|
@@ -1710,7 +1789,7 @@ function captureAndInject(name, entry, ctx) {
|
|
|
1710
1789
|
if (ctx.intentParamMode === "off") return;
|
|
1711
1790
|
const isV2 = typeof mutable.executor === "function";
|
|
1712
1791
|
try {
|
|
1713
|
-
const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema) : injectGoalParams(mutable.inputSchema);
|
|
1792
|
+
const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema, ctx.intentParamMode) : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);
|
|
1714
1793
|
if (Object.keys(dispositions).length > 0) {
|
|
1715
1794
|
mutable.inputSchema = schema;
|
|
1716
1795
|
ctx.bustSchemaMemo(name);
|
|
@@ -1721,6 +1800,46 @@ function captureAndInject(name, entry, ctx) {
|
|
|
1721
1800
|
} catch {
|
|
1722
1801
|
}
|
|
1723
1802
|
}
|
|
1803
|
+
var TOOLS_LIST_METHOD = "tools/list";
|
|
1804
|
+
var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
|
|
1805
|
+
function installToolsListSeam(lowLevel, ctx) {
|
|
1806
|
+
const table = lowLevel._requestHandlers;
|
|
1807
|
+
const originalSet = lowLevel.setRequestHandler;
|
|
1808
|
+
if (!(table instanceof Map) || typeof originalSet !== "function") return;
|
|
1809
|
+
const handlers = table;
|
|
1810
|
+
const setRequestHandler = originalSet;
|
|
1811
|
+
const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
|
|
1812
|
+
const advertise = (result) => {
|
|
1813
|
+
try {
|
|
1814
|
+
return advertiseUserGoalRequired(result, isInjected);
|
|
1815
|
+
} catch (err) {
|
|
1816
|
+
process.stderr.write(
|
|
1817
|
+
`baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
|
|
1818
|
+
`
|
|
1819
|
+
);
|
|
1820
|
+
return result;
|
|
1821
|
+
}
|
|
1822
|
+
};
|
|
1823
|
+
const wrapCurrent = () => {
|
|
1824
|
+
const handler = handlers.get(TOOLS_LIST_METHOD);
|
|
1825
|
+
if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
|
|
1826
|
+
const seamed = (...args) => {
|
|
1827
|
+
const out = handler(...args);
|
|
1828
|
+
return isThenable(out) ? out.then(advertise) : advertise(out);
|
|
1829
|
+
};
|
|
1830
|
+
seamed[TOOLS_LIST_SEAM] = true;
|
|
1831
|
+
handlers.set(TOOLS_LIST_METHOD, seamed);
|
|
1832
|
+
};
|
|
1833
|
+
wrapCurrent();
|
|
1834
|
+
lowLevel.setRequestHandler = (...args) => {
|
|
1835
|
+
const registered = setRequestHandler.apply(lowLevel, args);
|
|
1836
|
+
wrapCurrent();
|
|
1837
|
+
return registered;
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
function isThenable(value) {
|
|
1841
|
+
return typeof value?.then === "function";
|
|
1842
|
+
}
|
|
1724
1843
|
function wrapIfNeeded(nameRef, entry, ctx) {
|
|
1725
1844
|
if (!entry || typeof entry !== "object") return;
|
|
1726
1845
|
const mutable = entry;
|
|
@@ -1811,7 +1930,7 @@ function withBaton(server, supplied = {}) {
|
|
|
1811
1930
|
const config = resolveBatonConfig(supplied, serverName);
|
|
1812
1931
|
const sink = config.sink ?? new StdoutSink();
|
|
1813
1932
|
const annotationToolName = resolveAnnotationToolName(serverName, config);
|
|
1814
|
-
const intentParamMode = config.intentParamMode ?? "
|
|
1933
|
+
const intentParamMode = config.intentParamMode ?? "required";
|
|
1815
1934
|
const counter = new SessionCounter();
|
|
1816
1935
|
const fallbackSessionId = `sdk-${(0, import_uuid2.v7)()}`;
|
|
1817
1936
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
@@ -1908,6 +2027,7 @@ function withBaton(server, supplied = {}) {
|
|
|
1908
2027
|
annotationToolName
|
|
1909
2028
|
});
|
|
1910
2029
|
internals.server._instructions = instructions;
|
|
2030
|
+
if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
|
|
1911
2031
|
const resolvedAnnotationToolName = registerAnnotationTool(server, {
|
|
1912
2032
|
sink,
|
|
1913
2033
|
counter: ctx.counter,
|