What is Baton
Baton is actionable product analytics for MCP servers. When a customer's agent calls your server and your API can't meet the request, you often get a 200 with an empty body or a vague error. The customer's intent vanishes with no ticket and no trace. Baton captures that friction at the moment it happens: what the customer was trying to do, the call the agent made, what it expected, and what it got.
You instrument your server once. Whatever agent your customers use (Claude, Cursor, ChatGPT) keeps working exactly as before.
Which path is mine
Three ways to capture. They emit events in the same wire format, but their settings and sinks differ, so check Settings by product. You only need one.
baton-sdk
A server you own. Goes inside it and captures your real customers. Python, TypeScript or Go. Quickstart →
Gateway
Many servers behind a gateway. Capture once, in front of all of them, without touching any. Quickstart →
baton-proxy
A server you don't own, or your own before you change any code. Wraps it from outside. Quickstart →
Instrumenting is two lines. Here is the SDK path in full:
from baton import install_baton install_baton(mcp, dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../acme-kb")
The DSN is one string from /account holding your workspace, this server and the key that binds them, so nothing else needs configuring. You can also run without a key and read the events on your own machine first. Choosing paths →
Next steps
Send events to the Console
Every path can write to your own machine instead. One DSN string swaps the sink for the hosted Console, where friction is deduped and ranked across every customer. Console →
Capture intent, not just calls
The user_goal parameter is how a call carries why it was made. It is what turns an event log into a roadmap. Intent parameters →
Choose a sink
stderr, a file, an https:// collector of your own, or several at once. Sinks →
Check what gets scrubbed
Payloads run through a pattern-based scrubber before they reach any sink. Read what it does and does not catch. PII scrubbing →
capture friction from your customers
Overview
baton-sdk is native instrumentation for vendors who control their MCP server source. One call wires up capture, annotation, and sink routing, with the same wire format as the proxy and no subprocess hop. Because it lives inside what you ship, it captures friction from your real customers, who never have to install anything.
MCP middleware path
Your MCP server calls install_baton(mcp, dsn=…). Two lines. Captures every tool call at the transport boundary. Best for vendors with MCP servers as their primary surface.
Library API path
Code that calls your API wraps each call in client.trace(…). Same event envelope, same sinks, different emission boundary. Best for vendors who ship Skills rather than an MCP server.
baton-sdk is open source under Apache-2.0, and the source lives in the baton repo. The Python package needs 3.11+. There is also a TypeScript SDK, @goodtiming/baton-sdk on npm, and a Go SDK, github.com/good-timing/baton-go. Both are under Apache-2.0, with source in the baton-ts and baton-go repos. All three take the same DSN and emit the same events. Everything on this page applies to Python and TypeScript unless it says otherwise. Go has its own section.
Install
The latest releases are baton-sdk 1.3.0 on PyPI, @goodtiming/baton-sdk 1.0.0 on npm, baton-go v1.0.0 and baton-proxy 0.7.2 on PyPI. See Stability and versions. The >=0.8.8 below is the oldest version a plain install can send to the Console with, not the current one.
| Command | Includes |
|---|---|
| pip install "baton-sdk>=0.8.8" | Needed to send events to a Baton Console. The Console sink is in the core install, so it needs no extra. 0.8.6 is the oldest release the Console accepts, because earlier ones send user_id, which was renamed principal_id. On 0.8.7 and earlier the sink also needed the [http] extra, which a fresh [mcp] or [fastmcp] install did not pull in. |
| pip install baton-sdk | Core. Library API and sinks, the Console sink included. Writes to stderr, a file, or https. |
| pip install "baton-sdk[mcp]" | + the official mcp SDK, mcp>=1.21.1,<3. CI tests mcp 1.21.1, 1.25.0, 1.27.2, 2.0.0 and 2.3.0. |
| pip install "baton-sdk[fastmcp]" | + standalone fastmcp, fastmcp>=2.14,<5. |
| pip install "baton-sdk[all]" | Everything above. |
Quote the extras. zsh, the default shell on macOS, treats square brackets as a pattern and stops with no matches found before pip runs.
Quickstart
The SDK runs in-process inside your server and captures every tool call at the transport boundary, with no subprocess and no change to your tools' code.
The following diagram illustrates where the SDK runs inside your MCP server:
- No second process. The SDK is a library inside your server, so there is nothing extra to deploy, supervise or keep alive.
- Capture is at the transport boundary: the tool name, params, result and error that crossed MCP. The SDK does not reach into your logs or your database.
- The sink is yours to choose, and it is the only thing that leaves the process.
from mcp.server.mcpserver import MCPServer
from baton import install_baton
mcp = MCPServer("Acme Knowledge Base")
install_baton(mcp, dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...")
@mcp.tool()
async def your_tool(...): ...
from mcp.server.fastmcp import FastMCP
from baton import install_baton
mcp = FastMCP("Acme Knowledge Base")
install_baton(mcp, dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...")
@mcp.tool()
async def your_tool(...): ...
from fastmcp import FastMCP
from baton import install_baton
mcp = FastMCP("Acme Knowledge Base")
install_baton(mcp, dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...")
@mcp.tool
def your_tool(...): ...
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { withBaton } from "@goodtiming/baton-sdk";
const server = new McpServer({ name: "acme-knowledge-base", version: "1.0.0" });
withBaton(server, {
dsn: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
});
import (
"context"
"log"
baton "github.com/good-timing/baton-go"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
impl := &mcp.Implementation{Name: "acme-knowledge-base", Version: "1.0.0"}
server := mcp.NewServer(impl, nil)
handle, err := baton.Install(server, impl, nil, baton.Config{
DSN: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
})
if err != nil {
log.Fatal(err)
}
defer handle.Close(context.Background())
That string is the whole configuration. It is the DSN for one server, and it carries four things: a publishable key (baton_pk_…), the host events go to, your workspace id (ten_…) and the server's id (srv-…). The SDK reads all four and builds the sink itself.
install_baton works out which library your server comes from, and raises TypeError before changing anything if the object is not an MCP server it supports. It supports FastMCP (mcp 1.x), MCPServer (mcp 2.x) and standalone fastmcp. The check is on shape, not class, so a subclass of these installs the same way, and our tests cover one on every supported mcp and fastmcp version. If your subclass overrides call_tool to check access or credits, Baton removes user_goal before that check for any tool your server has registered, and a call the check refuses is captured with failure_kind "refused". With result_capture_mode="off" its message is not sent. On fastmcp 2 the library never calls a call_tool override. The low-level mcp.server.lowlevel.Server is not supported. Tools registered before and after the call are both captured.
A default install changes three things on your server.
- One parameter on every tool,
user_goal, removed before your handler runs. It is listed as required, but a call without it is served as usual. Its description is 344 characters. There is no per-tool setting: every wrapped tool gets it. A tool that already has its ownuser_goalargument keeps it. - One sentence in the server instructions, 268 characters, telling the agent to pass the user's message number on to sub-agents. Your own instructions stay first, with ours after a blank line. If any tool has its own
user_goal, the sentence is left out. - No tools. With
report_mode="on"it also adds a tool the agent uses to report problems, named after your server, so a server called"Acme Knowledge Base"getsacme-knowledge-base_annotate. It adds about 1,300 characters of tool description to the tool list, and about 150 to the server instructions, so our instructions come to about 420 in all, after your own.
Sessions on stateless HTTP. When a request carries no session id, each request is its own session, so two clients never share one. Your dashboard groups a person's sessions by principal_id, so to see one person's calls together, pass resolve_principal (see Identity). On stdio there is one session per process.
Getting a DSN
Sign in at baton.goodtiming.ai/account and press Add a server, with a name if you want one. The page shows the new DSN with a Copy button, and every server's DSN stays listed under Publishable keys. The setup agent makes one for you when it wires up a server.
We assign the server id and it never changes. The name is a label on /account and in your workspace picker, and you can rename it there. A publishable key can only write events, and only for the server its DSN names, so it is safe in your source.
Where the DSN goes
A server you distribute, meaning a stdio server started on your user's machine, takes the DSN in source, as above. An MCP client starts a stdio server with a fixed allowlist of environment variables (six names on macOS and Linux) plus whatever the user wrote in their own client config, so a value in your .env never reaches it.
A server you host can read it from the environment. Set BATON_DSN and pass nothing:
install_baton(mcp) # reads BATON_DSN
If BATON_DSN is not set either, and there is no vendor_id, tenant_id or sink, install_baton logs one warning and installs nothing. Your server starts as usual.
An explicit dsn= wins over BATON_DSN, and either one wins over BATON_TENANT_ID (and, for Client, BATON_VENDOR_ID), so a new DSN is never overridden by values an earlier install left in the environment.
baton_pk_… key in place of the DSN stops at startup with a message saying to copy the full value from /account. A secret baton_sk_… key in a DSN works, and logs a warning: it reads and writes everything in your workspace, so it must never ship.Without a DSN
To send to your own collector, or to try the SDK before you have a key, name the parts. Leave out sink and events go to stderr as JSON Lines.
import os
from baton import install_baton, VendorConfig
from baton.sinks import HttpSink
install_baton(mcp, VendorConfig(
vendor_id="acme-kb",
tenant_id="acme",
vendor_display_name="Acme Knowledge Base",
sink=HttpSink("https://collector.example.com", api_key=os.environ["COLLECTOR_KEY"]),
))
vendor_id names the server and tenant_id names the account the collector authenticates. One account holds many servers, so giving both the same value merges every server in it into one. HttpSink posts batches to {url}/v0/events/batch with the key as a bearer token.
A VendorConfig can carry a DSN too, as VendorConfig(dsn=…, scrubber=…), when you want a DSN and other settings. Passing a DSN alongside vendor_id, tenant_id or sink raises, because the DSN already sets them.
| Your server | Adapter, if you import one directly |
|---|---|
| from mcp.server.mcpserver import MCPServer | baton.integrations.official |
| from mcp.server.fastmcp import FastMCP | baton.integrations.official |
| from fastmcp import FastMCP | baton.integrations.standalone |
Configuration
Keyword-only. With a DSN, every other field is optional.
| Field | Default | What it does |
|---|---|---|
| dsn | BATON_DSN | The value from /account. Sets vendor_id, tenant_id and sink, and vendor_display_name when that is unset. |
| vendor_id | — | The server's id. Required without a DSN. Letters, digits, _ and -, up to 48 characters. |
| tenant_id | BATON_TENANT_ID, then vendor_id | The account the collector authenticates. |
| vendor_display_name | your server's name, else the DSN's server id | The name the calling agent reads in the report tool's description and its instructions, with report_mode="on". Required with report_mode="on" when there is no DSN. |
| sink | from the DSN, else StdoutSink() when vendor_id is set | Where events go. See Sinks. |
| annotation_tool_name | from the server's name | Pins the report tool's name, with report_mode="on". Without a usable server name it is {vendor_id}_annotate. |
| scrubber | Scrubber() | Runs on every payload. Pass identity_scrub to turn scrubbing off, or your own callable. See PII scrubbing. |
| intent_param_mode | "required" | Adds one parameter, user_goal, to every tool's input schema and removes it before your handler runs. The agent writes it as '<n>: <what this call is for>; success is <what its result should show>', where n is the number of the user's current message. "required" lists it as required, as an advertisement only: no call fails for leaving it out. "optional" leaves it off the required list. |
| report_mode | "off", "on" with Console settings | "on" adds a tool the agent uses to report a tool call that went wrong, or a request no tool covers, plus instructions saying when to use it. Off, no tool is added and each call's goal still arrives in user_goal. |
| result_capture_mode | "full" | "off" stops sending what your tools return. Requests are still sent. See What leaves your server. |
| settings | "local" | "console" reads capture settings from the Console. Needs a DSN. See Settings from the Console. |
| settings_refresh_s | 60 | How often "console" reads the settings, in seconds. At least 15. |
| resolve_principal | — | A function, sync or async, that says who is behind a call. Unset, no event names anyone. See Identity. |
Servers built per request
If your app builds a new MCP server for each request, do not call install_baton on each one: every call starts its own sender. Create one Baton at startup and wrap each server:
import baton
shared = baton.create_baton(dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...")
def build_server():
server = FastMCP("Acme Knowledge Base")
... # register your tools
shared.wrap(server)
return server
# once, at shutdown, in your async shutdown hook:
# await shared.aclose()
create_baton takes what install_baton takes and checks it at once, so no request fails on a bad setting. Its servers share one sender, and your tool list is sent once. Each server's calls keep their own session.
Identity
Baton names the person behind a call only when you tell it who that is. You pass one function, resolve_principal. It gets the call's headers, _meta, tool name, arguments and the verified token's claims, and returns a Principal or None. The SDK sends what the function returns and does nothing else to it: no hashing, no key, no guessing.
If your server runs OAuth, two ready-made hooks cover it. Pass one as it is:
from baton import install_baton, VendorConfig, principal_from_oauth_email
install_baton(mcp, VendorConfig(
dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
resolve_principal=principal_from_oauth_email, # or principal_from_oauth_sub
))
principal_from_oauth_email uses the token's email claim as the id and the part before @ as the name your dashboard shows. principal_from_oauth_sub uses the token's subject. Both return None when the claim is missing. A token exists only on HTTP with auth configured.
For anything else, such as a gateway header, an argument or a stdio login, write your own. It is a few lines:
from baton import Principal
def resolve(ctx):
employee = (ctx.headers or {}).get("x-forwarded-user")
if not employee:
return None
return Principal(principal_id=employee, display_name=employee.split("@")[0])
Principal field | Default | What it does |
|---|---|---|
| principal_id | required | The id, sent exactly as you return it. Your dashboard groups a person's sessions by it. It can name a person or a service account. For the company they belong to, use organization below. |
| display_name | None | What your dashboard shows for this person. Without it, the dashboard shows the id. |
| form | "raw" | What the id is. Leave it as "raw" for a real identity. Set "hashed" only when your function hashed the id itself. |
| user_data | None | Python only. Accepted, and not used today. Nothing in it is sent. |
| labels | () | Your names for the groups this caller is in, for the Console's settings to match. See Settings from the Console. |
Their company. To say which of your customers a call belongs to, give the Principal an organization. If you only know the company, for example from an org-wide API key, return an Organization on its own. A company returned as a Principal is counted as a person, so use Organization for it.
from baton import Organization, Principal
def resolve(ctx):
user = (ctx.headers or {}).get("x-forwarded-user")
org = (ctx.headers or {}).get("x-org-id")
company = Organization(organization_id=org) if org else None
if user:
return Principal(principal_id=user, organization=company)
return company
Organization field | Default | What it does |
|---|---|---|
| organization_id | required | The company's id, sent exactly as you return it. |
| display_name | None | A name for the company. It is a label, never a key. |
| form | "raw" | As for Principal. Set "hashed" only when your function hashed the id itself. |
| labels | () | As for Principal. Both lists are sent together. |
Your dashboard stores the organization with each event, but doesn't filter by it or show it yet. Two sessions that name different organizations are never joined, and a session that names two organizations is never joined to another. With the Library API, pass the same values to client.session(principal=...). A block that names only an organization, with no session_id, is never joined to another, so pass your own session_id there.
The id you return is stored by the collector as it is. Your function decides what is safe to send. If real identities must not leave your side, hash the id in the function and say so:
import hashlib, hmac, os
from baton import Principal
KEY = os.environ["MY_ID_HASH_KEY"].encode()
def resolve(ctx):
sub = (ctx.claims or {}).get("sub")
if not sub:
return None
digest = hmac.new(KEY, sub.encode(), hashlib.sha256).hexdigest()
return Principal(principal_id=digest, form="hashed")
A hook that raises, or returns nothing usable, costs that event its person and nothing else: the tool call and the event are unaffected. The two ready-made hooks are short and are the best examples to copy from: Python, TypeScript.
Settings from the Console
With settings="console", the SDK reads the capture settings saved on the Console's Capture page, so you can change them without a deploy. Each caller gets the settings of the first audience that matches it. An audience can match on the caller's labels, the app it runs in (such as claude-code), or a share of your callers. With several of these, all must match.
install_baton(mcp, VendorConfig(
dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
settings="console",
))
| Setting | What it changes | When it applies |
|---|---|---|
| results | Whether results and error messages are sent, as result_capture_mode does. | The next call |
| goal | Whether the user_goal Baton adds is required or optional. | The next tools/list |
| reports | Whether the caller sees the report tool. A caller with reports off can still file a report from an older tool list. | The next tools/list |
- It needs a DSN: it reads with the DSN's key. Without one, install raises.
- The settings are read in the background, every 60 seconds by default. A read never delays startup or a call. Until the first read succeeds, and while nothing is saved, the values in your config apply.
- The report tool is on by default here, so the Console decides who sees it. Set the report mode to off to keep it off for everyone.
- Your server instructions point to the report tool while any audience has reports on. A client reads them when it connects, so a change reaches new connections only.
- One
create_baton()reads the settings once for every server it wraps. - Once settings are read, each event says which ones it ran under, in
capture: the settings' version and the matched audience.
Labels come from your resolve_principal, as labels on the Principal or the Organization it returns: up to 20 per caller, each up to 64 characters. A label that is longer, blank or a repeat, or past the 20th, is dropped, not cut. They ride every event of that caller's requests in labels, not scrubbed, so send only names you are happy for Baton to see, never a raw id. A share of callers is picked by the principal's id, or the company's when there is no principal, so the same person always lands in the same group. A caller with neither is never in a share.
Sinks
| Sink | Use case |
|---|---|
| StdoutSink() | Events to stderr as JSON Lines. The default with a vendor_id and no DSN or sink=. |
| FileSink("./events.jsonl") | Capture to a local file. |
| HttpSink(url, api_key=…) | POSTs batches to {url}/v0/events/batch, or one event at a time to {url}/v0/events if the collector has no batch endpoint. Bounded buffer, retry, circuit breaker. A DSN builds this one for you. |
| MultiSink([…]) | Fan out to several sinks at once. |
Every sink but HttpSink is written off the tool call, from a queue of 1,000 events, so a slow or stuck sink never slows a call. When the queue is full, the oldest event is dropped and counted. A write that fails loses that event, and the next one is still written. Flush and close through the handle install_baton returns, with handle = install_baton(...) then handle.flush() and handle.aclose(). The sink's own flush() and aclose() skip what is still queued. If your own sink holds a connection made on your event loop, open it inside write, which runs on Baton's loop.
There is no S3 or OpenTelemetry sink in the SDKs. The proxy can write to S3.
from baton import install_baton, VendorConfig
from baton.sinks import StdoutSink, FileSink, MultiSink
# development: stderr and a file
install_baton(mcp, VendorConfig(
vendor_id="acme-kb",
vendor_display_name="Acme Knowledge Base",
sink=MultiSink([StdoutSink(), FileSink("./events.jsonl")]),
))
Turning capture off
Set BATON_DISABLED=1 in the environment of the process that runs the server, and the SDK installs nothing: no wrapped tools, no report tool, no change to the server instructions, no collector connection, no background thread. The server runs as it would without the install_baton line. The SDK reads the variable once at startup, never writes to stdout, and never stops the server from starting, even with a config it would otherwise refuse. Any value other than empty, 0, false, no or off turns it on.
The switch belongs to whoever runs the server.
- A server you distribute runs on your user's machine, so the switch is theirs. It goes in the
envblock for your server in their MCP client's config file, not in their shell: the client passes the server a fixed allowlist of environment variables, and an exportedBATON_DISABLEDis not on it. - A server you host runs on your machine, so the switch is yours. Your users cannot set it, and there is no per-user opt-out.
{
"mcpServers": {
"acme-knowledge-base": {
"command": "acme-kb-mcp",
"env": { "BATON_DISABLED": "1" }
}
}
}
Library API
For vendors whose customers reach the API via agent-generated code (Skills pattern). Here Baton lives in the Skill code rather than in a server, so it fits vendors who have no MCP server at all.
The following diagram illustrates where the SDK sits on the library path:
- Your API is untouched. Baton lives in the Skill that calls it, not behind it, so nothing ships on the API side.
- One
client.trace(...)per call, inside oneclient.session(...)per request, is the whole integration; the events it emits are the same envelope the MCP path emits. - Use this path when you ship a Skill rather than an MCP server.
Sync (Client)
from baton import Client, Principal
client = Client(dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...")
with client.session(
session_id=request.conversation_id, # optional: your own id for the conversation
principal=Principal(principal_id=user.id), # optional: who is calling
client_info={"name": "claude-code", "version": "2.1"}, # optional: which app is calling
headers=request.headers, # optional: only User-Agent and X-Anthropic-Client are kept
):
with client.trace(
tool_name="chat.completions.create",
intent="summarize the user's question",
expected_outcome="2-3 sentence answer",
) as trace:
response = vendor_client.chat.completions.create(...)
trace.observed(response)
client.annotate(what_happened="asked for a CSV export; no endpoint returns one", tool_name="none")
client.close() # or: with Client(dsn=...) as client:
Open one client.session(...) per request or conversation. Every trace() and annotate() inside it shares its session, principal and client. A call outside any block gets a session of its own, so it does not join the others. Pass client_info or the request's headers when your request says which app the agent runs in; with neither, your dashboard shows "app not reported".
Async (AsyncClient)
from baton import AsyncClient
async with AsyncClient(dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...") as client:
with client.session(session_id=request.conversation_id):
async with client.trace(tool_name="...", intent="...") as trace:
response = await vendor_client.chat.completions.create(...)
trace.observed(response)
Both take the same keyword arguments: dsn, or vendor_id, tenant_id and sink without one, plus scrubber and result_capture_mode. Both read BATON_DSN when no DSN is passed. On both, session() is a plain with block.
trace.annotate()
with client.trace(tool_name="search", intent="find docs for X") as trace:
try:
result = search_api.query(...)
trace.observed(result)
except ApiError as e:
trace.observed(error=e)
trace.annotate(what_happened="search returned 429 with no retry-after", tool_name="search", suggested_improvement="add retry-after on 429s")
A report says what went wrong in its own words. The collector assigns its group; there is no category to pick. Name the tool the report is about, or pass tool_name="none" when no tool exists for what was asked.
Agent reports on your own API
The MCP path gives agents a report tool. On your own API, offer the same tool with report_tool. It has the MCP report tool's description and default input schema, and a name made from vendor_display_name the same way, so an agent reads the same words. A display name that gives no usable tool name raises; pass name= then.
from baton import report_tool
tool = report_tool(vendor_display_name="Acme")
# Offer tool.name, tool.description and tool.input_schema to the agent.
# When the agent calls it:
kwargs = tool.annotate_kwargs(arguments)
if kwargs is None:
return {"ok": False, "error": tool.refusal}
client.annotate(**kwargs)
return {"ok": True}
annotate_kwargs returns None when the agent sent no what_happened, or a blank one. Send tool.refusal back and send nothing to Baton. Call annotate inside the same session(...) block as the calls it is about, or use trace.annotate(**kwargs) for one traced call. tool.instructions holds the text the MCP path adds to your server instructions.
Choosing paths
| Concern | MCP integration | Library API |
|---|---|---|
| Instrumentation lives | Vendor side (MCP server) | Agent side (agent-generated code) |
| Setup | 2 lines in your MCP server | Vendor publishes a Baton-aware Skill |
| Reliability | Deterministic. Every tool call | Soft. Depends on agent following Skill |
| Reports from the agent | An MCP tool, off by default (report_mode="on"), on by default with Console settings | The same tool on your own API (report_tool), then annotate(…) |
TypeScript
The same SDK for Node. @goodtiming/baton-sdk emits the same envelope as the Python package, so a workspace can run both and the Console never learns which one produced an event. Node 20+.
npm install @goodtiming/baton-sdk
Your MCP server is the argument, as in Python. Both major versions of the official TypeScript MCP SDK are supported and both are optional peer dependencies, so you install whichever one you already use, either @modelcontextprotocol/sdk ^1.30.0 or @modelcontextprotocol/server ^2.0.0, and nothing else.
import { McpServer } from "@modelcontextprotocol/server";
import { withBaton } from "@goodtiming/baton-sdk";
const server = new McpServer({ name: "acme-knowledge-base", version: "1.0.0" });
withBaton(server, {
dsn: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
});
Config fields are the Python names in camelCase (vendorId, tenantId, vendorDisplayName, sink, annotationToolName, intentParamMode, reportMode, resultCaptureMode, scrubber), plus settings and settingsRefreshMs, which is in milliseconds. A dsn sets vendorId, tenantId and sink, and vendorDisplayName when you leave it unset, as in Python. The sinks are the same four as in Python, as classes, such as new HttpSink(url, { apiKey }), and queue events the same way (see Sinks). Call handle.aclose() before process.exit(): at exit only a StdoutSink or FileSink gets what is still queued. Tools registered before or after withBaton are both captured, and so are tools added or removed later.
Identity works as in Python: pass resolvePrincipal, which returns { principalId, displayName?, form?, organization?, labels? }, an organization on its own as { organizationId, displayName?, form?, labels? }, or null, sync or async. principalFromOAuthEmail and principalFromOAuthSub ship ready-made and read the token's claims from authInfo.extra. See Identity.
import { withBaton, principalFromOAuthEmail } from "@goodtiming/baton-sdk";
withBaton(server, {
dsn: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
resolvePrincipal: principalFromOAuthEmail,
});
Settings from the Console work as in Python, with settings: "console" and settingsRefreshMs (60000 by default, at least 15000). It needs a DSN, and BATON_DSN counts. Labels go in labels on the Principal or Organization your resolvePrincipal returns, and in client.session({ principal }). See Settings from the Console.
A server built per request. Do not call withBaton per request, because each call builds a new sink. As in Python, call createBaton(config) once at startup and baton.wrap(server) for each new server. It takes the same config as withBaton. Call await baton.aclose() when your server stops.
import { createBaton } from "@goodtiming/baton-sdk";
const baton = createBaton(); // reads BATON_DSN, like withBaton
app.post("/mcp", async (req, res) => {
const server = buildServer();
baton.wrap(server);
// connect a transport and handle the request as before
});
Without MCP
The Library API is here too, as Client. The block and the call take callbacks instead of with: client.session(options, fn) and client.trace(options, fn). The option names are the Python names in camelCase. Put one trace() where every tool call passes through, such as a middleware, and every tool is covered.
import { Client } from "@goodtiming/baton-sdk";
const baton = new Client({ dsn: process.env.BATON_DSN });
app.use((req, res, next) =>
baton.session({ sessionId: req.get("x-conversation-id"), headers: req.headers }, () =>
baton.trace({ toolName: req.path, params: req.body }, () => next()),
),
);
A callback can be sync or async. Its return value is recorded as the result, and a throw is recorded and passed on unchanged. client.wrap(toolName, fn) traces a function on every call, for code with no single place to put trace().
The report tool for your own API is reportTool({ vendorDisplayName, name? }). Its annotateArgs(args) returns the options for annotate(), or null when the agent sent no what_happened; answer tool.refusal then.
What it captures
The same user_goal parameter, the same surface_snapshot, and the same events. intentParamMode defaults to "required", which lists user_goal in each tool's required list and never enforces it. There is no "off". The report tool is off by default here too, and on by default with Console settings. reportMode: "on" adds it.
One difference under resultCaptureMode: "off": the message of an error your handler throws is never sent. The TypeScript MCP SDK has no ToolError class to mark a message as safe to send. The Python SDK sends the message of a ToolError.
PII scrubbing is on by default here too, a rule-for-rule port of Python's ruleset. Pass identityScrub to opt out, or your own (value: unknown) => unknown. Read what it does and does not catch before relying on it.
What is not here yet
Stated so you find out now rather than later. None of it blocks the paths above.
- Only the high-level
McpServer. The low-levelServeris not wrapped. - Only the intent parameter needs a Zod schema. Every tool registered with a handler function is wrapped and captured either way, and a tool with no input schema gets no intent parameter. 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. - A 1.x task-based tool is not wrapped. It emits no events. It still lists
user_goal, and Baton removes it before your handler runs. - A refusal inside your own
validateToolInputoverride reads asinvalid_argument. A refusal from an override ofexecuteToolHandler, or from a wrapper on thetools/callhandler installed beforewithBaton, is captured as"refused". One installed afterwithBatonis not seen. - v2's
createMcpHandleris tested only for calls that pause for input. A server your own code builds per request is supported, withcreateBatonabove. resources/templates/listsends no events.
Wire compatibility
This is a tested property, not an intention. All three SDKs are checked against baton-spec, a neutral schema repo: Python and TypeScript events are validated against the shared JSON Schema, Go events are compared with its example events and scrub cases, and the TypeScript emitter is diffed field-by-field against captured Python output for the same scenario. Envelope and payload keys must match exactly; values match except for ids, timestamps, timings and the genuinely language-specific fields.
Go
The same SDK for servers built on the official Go MCP SDK. baton-go takes the same DSN and sends the same events as the Python and TypeScript packages. It is open source under Apache-2.0, with its source in the baton-go repo. Go 1.25+, and github.com/modelcontextprotocol/go-sdk v1.6.1 or later in v1.
go get github.com/good-timing/baton-go@v1.0.0
If your server is on an older go-sdk, go get moves it up to v1.6.1. A newer one stays where it is.
impl := &mcp.Implementation{Name: "acme-knowledge-base", Version: "1.0.0"}
server := mcp.NewServer(impl, nil)
handle, err := baton.Install(server, impl, nil, baton.Config{
DSN: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
})
if err != nil {
log.Fatal(err) // a bad DSN or config; nothing was installed
}
defer handle.Close(context.Background())
Pass Install the same impl and options you gave mcp.NewServer. The options may be nil in both places. Baton reads your server's name, version and instructions from them, and never calls your server to find them out. A nil impl or an empty impl.Name is an error. Tools added before and after Install are both captured.
Call Close when your server stops. Events are sent in the background, in batches, so one can reach the Console up to 5 seconds after it was recorded. Close(ctx) sends what is still buffered and stops shortly before ctx's deadline, or after about 3 seconds if it has none. It never returns an error. Events recorded after Close are dropped.
With no DSN, no BATON_DSN, and no Sink, VendorID or TenantID, Install logs one warning and installs nothing, and your server starts as usual. A config value that is not valid is still an error.
Configuration
Fields of baton.Config. With a DSN, every other field is optional. Each mode has its own type, with a named constant for each value, so a value of another mode is a compile error. A quoted value such as "off" also works; a string variable needs a conversion, such as baton.ReportMode(s).
| Field | Default | What it does |
|---|---|---|
| DSN | BATON_DSN | The value from /account. An explicit DSN wins over BATON_DSN. |
| Sink | from the DSN | Where events go without a DSN. See Sinks below. |
| VendorID | — | The server's id. Required without a DSN. Letters, digits, _ and -, up to 48 characters. |
| TenantID | VendorID | The account, for events written without a DSN. |
| VendorDisplayName | the server's name | The name the agent reads in the report tool's description and its instructions. |
| ResultCaptureMode | baton.ResultCaptureFull | baton.ResultCaptureOff stops sending what your tools return, and the error text. Requests are still sent. |
| IntentParamMode | baton.IntentParamRequired | Whether user_goal is listed as required. baton.IntentParamOptional leaves it off the list. Nothing enforces it. |
| ReportMode | baton.ReportOff | baton.ReportOn adds the tool the agent uses to report problems, named after your server. |
| AnnotationToolName | from the server's name | Pins the report tool's name, with baton.ReportOn. |
| Scrubber | baton.DefaultScrubber | Runs on every captured value, with the same rules as Python. baton.NoScrub turns scrubbing off, or pass your own func(any) any. |
| ResolvePrincipal | — | A function that says who is behind a call. Unset, no event names anyone. |
| Middleware | — | Your own receiving middleware, such as an auth check. See Refused calls below. |
| Settings | baton.SettingsLocal | baton.SettingsConsole reads capture settings from the Console, and needs a DSN. See Settings from the Console. |
| SettingsRefresh | 60 seconds | How often SettingsConsole reads, as a time.Duration. At least 15 seconds. |
The constants are ResultCaptureFull and ResultCaptureOff ("full", "off"), IntentParamRequired and IntentParamOptional ("required", "optional"), ReportOn and ReportOff ("on", "off"), and SettingsLocal and SettingsConsole ("local", "console").
Under baton.ResultCaptureOff, the error_type of an error your handler returned is still sent. It is the Go type name, such as *acme.NotFoundError. Its message is withheld, unless you return it as a *baton.PublicError, which marks it safe to send. The message of a failed listing, prompt or resource request is still sent, and Install warns once about this.
Servers built per request
A server built per request. Each Install starts its own sender, so do not call it per request. Make one Baton at startup with New, and Wrap each server:
b, err := baton.New(impl, opts, baton.Config{DSN: os.Getenv("BATON_DSN")})
if err != nil {
log.Fatal(err)
}
defer b.Close(context.Background())
handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {
s := mcp.NewServer(impl, opts)
// your AddTool lines
b.Wrap(s)
return s
}, &mcp.StreamableHTTPOptions{Stateless: true})
Build every server with the impl and opts you gave New. b.Close closes the shared sink. Wrap never fails a request: it returns an error only for a nil server, and skips a server it already wrapped. If you build the server once, call Install once and hand that server to the handler.
Sessions on stateless HTTP work as in Python.
Sinks
Without a collector, set Sink and VendorID instead of a DSN. Each event is one line of JSON.
handle, err := baton.Install(server, impl, opts, baton.Config{
Sink: baton.MultiSink(baton.StdoutSink(), baton.FileSink("events.jsonl")),
VendorID: "acme-kb",
})
| Sink | Use case |
|---|---|
| baton.StdoutSink() | Events to stderr, because stdout carries the stdio transport. The sink when you set VendorID and no Sink. |
| baton.FileSink(path) | Appends to a local file. The file is created on the first event. |
| baton.MultiSink(a, b) | Writes every event to each sink. |
| your own type | Anything with Write(ctx, []baton.Event) error and Close(ctx) error. |
There is no HttpSink to build: to send to a collector, give a DSN, which names its host. A DSN together with Sink, VendorID or TenantID is an error. A BATON_DSN in the environment is ignored then, with one warning. Baton calls a sink only from its own goroutine, never from a tool call, and holds up to 1,000 events in front of it, dropping the oldest when full.
Identity
Pass ResolvePrincipal. It works as in Identity. It gets a baton.Caller, which holds the verified token, the HTTP headers, _meta, the tool's name and its arguments, and returns a *baton.Principal or nil.
baton.Install(server, impl, opts, baton.Config{
DSN: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
ResolvePrincipal: baton.PrincipalFromOAuthEmail, // or baton.PrincipalFromOAuthSub
})
PrincipalFromOAuthEmail and PrincipalFromOAuthSub read the email or sub claim from c.Token.Extra. A token exists only on streamable HTTP behind go-sdk's auth.RequireBearerToken. On stdio and SSE, c.Token and c.Header are nil. For anything else, write your own:
func resolve(ctx context.Context, c baton.Caller) (*baton.Principal, error) {
p := &baton.Principal{ID: c.Header.Get("X-Forwarded-User")}
if org := c.Header.Get("X-Org-Id"); org != "" {
p.Organization = &baton.Organization{ID: org}
}
return p, nil
}
A Principal has ID, DisplayName, Hashed and Organization. An Organization has ID, DisplayName and Hashed. Both have Labels for Settings from the Console; a Principal with Labels and no ID sends the labels alone. If you only know the company, leave ID empty and set Organization. Set Hashed: true only when your function hashed the id itself. An id longer than 128 characters is cut to 128, and a blank one is not sent. If the hook returns an error, panics or takes longer than 5 seconds, that call is sent without a principal, and the call goes on.
Refused calls
A call your own middleware stops before the tool runs, such as an auth or credits check, is captured with failure_kind "refused" when you give that middleware to Baton instead of adding it yourself:
handle, err := baton.Install(server, impl, opts, baton.Config{
DSN: "https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...",
Middleware: []mcp.Middleware{auth},
})
Baton adds it inside its own middleware, so it sees every call, and ResolvePrincipal sees what your auth put in the ctx. That holds for a tools/list too, so labels from your auth shape the caller's tool list; Baton adds its tools to the list your middleware returns. A listing your middleware answers without calling next, such as from a cache, is matched without what your auth set. When Install or New adds nothing, it still adds your middleware, so your auth always runs. Do not add it again. Middleware you add yourself is not named: added before Install, a call it stops looks like your tool's own error; added after, a call it stops is not captured at all.
Turning capture off
BATON_DISABLED=1 works as in Turning capture off, for both Install and New.
What is not here yet
- No Library API. Only a go-sdk
*mcp.Serveris wrapped. The Library API will come later, as an addition. - The Console's setup agent has no Go recipe for a server built per request. Follow Servers built per request by hand.
Settings by product
The five ways to install Baton don't have the same settings. Check the column for the one you use.
| Python SDK | TypeScript SDK | Go SDK | Proxy | Gateway | |
|---|---|---|---|---|---|
| Where settings go | VendorConfig, snake_case | withBaton options, camelCase | baton.Config fields | Environment variables | Environment variables |
user_goal | intent_param_mode, required or optional | intentParamMode, required or optional | IntentParamMode, required or optional | BATON_INTENT_PARAM, required or optional | BATON_INTENT_PARAM, required or optional |
| Report tool, off by default | report_mode, named after your server. On by default with Console settings | reportMode, named after your server. On by default with Console settings | ReportMode, named after your server. On by default with Console settings | BATON_ANNOTATE, named baton_annotate | None |
| Settings from the Console | settings="console" | settings: "console" | Settings: baton.SettingsConsole | None | None |
| Turn off results | result_capture_mode | resultCaptureMode | ResultCaptureMode | None, results are always sent | None, results are always sent |
| Turn Baton off | BATON_DISABLED=1 | BATON_DISABLED=1 | BATON_DISABLED=1 | None, stop wrapping the server | None, remove it from the gateway config |
| Where events go | stderr, a file, HTTPS, or several | stderr, a file, HTTPS, or several | stderr, a file, HTTPS, or several | stderr, a file, HTTPS or S3 | The proxy's sinks |
| Who is calling | resolve_principal | resolvePrincipal | ResolvePrincipal | Not sent | From a gateway header |
| Their company | Organization, from resolve_principal | organization, from resolvePrincipal | Organization, from ResolvePrincipal | Not sent | BATON_EXTMCP_ORGANIZATION_ID_HEADER |
| Their groups | labels, from resolve_principal | labels, from resolvePrincipal | Labels, from ResolvePrincipal | Not sent | Not sent |
What it costs your agent
Measured with Claude Code on our own test servers, with Sonnet 5.5 unless stated. Your numbers depend on your tools and your model, so read these as the size of the effect, not a promise.
- Input. Each tool's schema grows by about 350 characters (the
user_goalproperty and its 344-character description), sent with the tool list. Input tokens cost about 0.02 ms each to process, 0.01 ms when cached, 100 to 200 times less than output. - Output. The agent writes the
user_goalvalue on every call. Writing time follows output tokens, at about 4.2–4.7 ms per token on Sonnet 5.5, 6.8 on Opus 5.5 and 3.6 on Haiku 5.5. - Reports (
report_mode="on"). The agent is told to call the report tool only when it has something to report, such as a tool call that went wrong or a request no tool covers. Each report it files adds a turn before its answer. The tool and its instructions add about 1,450 characters to what the agent reads. About 1,300 of them are the tool's description, in the tool list. The rest, about 150, go into your server instructions.
What leaves your server
Only what crosses the MCP call. The SDK never reads your logs, your database or anything else in your process. This table is the Python SDK. The differences are noted under TypeScript and Go.
| Sent | What |
|---|---|
| Always | The tool's name, its arguments (params), user_goal, how long the call took, and on failure the error_type. Your tool list and schemas, once per change. What the client declares about itself, such as its name and version. Who the caller is, only if you set resolve_principal. |
Only with result_capture_mode="full" (the default) | What the tool returned (result), the error text it returned (error_body), and the message of an exception it raised. |
With report_mode="on" | The reports the agent files, in its own words. |
| Never | Anything that did not cross the MCP call. |
result_capture_mode="off" turns off responses, not requests. Arguments are always sent, so the scrubber below is what protects them. Two things are still sent under "off": a ToolError's message, unless it was raised from another exception, and the message of a failed tool list, resource or prompt request.
The proxy has no result_capture_mode; it always sends results.
PII scrubbing
Scrubbing is on by default. baton.scrub.Scrubber walks every event payload before it reaches the sink and redacts email addresses, Bearer tokens of 16 or more characters, sk- keys, AKIA access keys, JWTs, North American phone numbers, and card numbers that pass a Luhn check. It also redacts the whole value of any field named email, phone, ssn, api_key, token, secret, password or user_name.
It matches patterns. It does not find every piece of personal data. {"name": "Jane Doe", "address": "12 Elm St"} passes through unchanged, and a card number written with spaces or hyphens is not caught. Decide what your tools put in their arguments and results with that in mind.
To turn it off:
from baton import install_baton, VendorConfig from baton.scrub import identity_scrub install_baton(mcp, VendorConfig(dsn="https://baton_pk_...@baton.goodtiming.ai/ten_.../srv-...", scrubber=identity_scrub))
Stability and versions
The Python, TypeScript and Go SDKs are at 1.0. What 1.0 promises:
- The events only grow. No event type, field or value is removed or changes meaning without a 2.0. New optional fields and new event types can appear, so a collector must ignore what it does not know.
- Each SDK follows semver. A change that breaks your code comes only in a new major version. Each SDK's README says what is public. In Go, a new major is a new module path, such as
github.com/good-timing/baton-go/v2. baton-proxystays at 0.x and sends 1.0 events.
A few parts are experimental. They may change in a minor release, so do not build on them yet:
| Experimental | What it is |
|---|---|
| capture.overlay | A member of the capture field on events. Reserved; no SDK sends it yet. |
| client_report | The event that counts what an SDK could not deliver. In Python and TypeScript, ClientReportEvent and ClientReportPayload. |
| trace_context | Reserved. Not sent. |
| EventSchema | TypeScript only. The zod schema may change with a zod major; the event types may not. |
The full rules are in SPEC §13, "Stability from 1.0". The 1.0 announcement covers what is supported and what comes next.
capture a whole fleet at once
Overview
For fleets of MCP servers. The other two paths instrument one server at a time: the SDK goes inside a server you own, the proxy wraps a server you do not. This one captures at the gateway itself, so every server behind it is covered at once, and neither your clients nor your backend servers change.
Baton runs as a processor beside your gateway, on the gateway's external-processor hook for MCP. Traffic still flows client to gateway to server. Baton sees the MCP messages as they pass and never becomes a hop in the path: it is not a subprocess wrap and not an HTTP bridge.
The following diagram illustrates where Baton sits relative to your gateway:
- Your gateway keeps the traffic. Client to gateway to server is unchanged; Baton is not inserted between any two of them.
- The hook hands Baton a copy. The external-processor call is what Baton sees. Configure that hook fail-open and a Baton outage costs you the event, not the call.
- Every server behind the gateway is covered at once, and none of them ships a change.
This is the path that reaches surfaces with no code to instrument. A client behind the gateway is captured without anyone shipping a change to it.
Quickstart
There is no public package yet. Each release builds private container images, and it is not on PyPI. The proxy and the SDK are published and you can start with either one today. The gateway processor ships with a runbook for your platform team instead, and we set it up with you. Talk to us and we will size it against your gateway.
Configuration
Two pieces: one hook in your gateway's own policy, pointed at the processor and set to see both the request and the response of each tool call along with its session id, and the same handful of environment variables the proxy reads.
| Variable | Purpose |
|---|---|
| BATON_VENDOR_ID | Labels the captured signal. |
| BATON_EVENT_SINK | Where events go: the Console over https, your own object store, a file, or stderr. Comma separate to fan out. |
| BATON_API_KEY | Bearer token for the Console sink, from your secret store. |
| BATON_CONSENT_TOKEN | Per install consent. The processor refuses to ship anywhere remote while this is still the placeholder. |
Nothing has to leave your walls. Point the sink at your own storage and the Console never sees an event.
Identity
This path resolves the caller from a request header, and which header is configuration rather than code. The value of that header is sent as the caller id exactly as your gateway gives it. If the real id must not leave your network, have the gateway put a pseudonym in the header.
To name the caller's company, set BATON_EXTMCP_ORGANIZATION_ID_HEADER to the header that carries it. It is unset by default, so nothing is sent. Its value is sent as your gateway gives it.
Your gateway must pass the header on every call. A call without it is captured with no caller, and nothing reports it. BATON_PRINCIPAL_ID_HMAC_KEY is no longer read; setting it only logs a warning.
What it captures
One parameter, user_goal, is added to each tool in the list the gateway returns. The agent writes the number of the user's message and what the call is for, in the same words the SDK and the proxy use. Baton reads it off each call and strips it before the request reaches your server, so your handlers are unchanged. The agent sees the parameter, and clients that show tool arguments show it to the user. With initialize routed to the processor, it also adds one sentence to your server instructions asking the agent to pass the message number to a subagent.
| MCP message | What Baton does |
|---|---|
| initialize | Adds the subagent sentence below your server instructions. |
| tools/list | Adds user_goal to each tool. |
| tools/call request | Reads the values off the request, strips them, emits tool_call_start. |
| tools/call response | Pairs the result with its call and emits tool_call_end or tool_call_error, with the duration. |
The events are the same wire format the other two paths emit, so one Console reads all three. A response carries no request id, so the gateway passes the session id to the processor on both halves of each call, and results pair within a session in the order calls were made. Pairing is exact while a session's calls complete in order. Calls running at the same time inside one session can pair with the wrong request, and a call with no session id gets no result event.
Scrubbing runs in the processor before any sink sees an event, with the same patterns as the SDK.
Trust & security
sample friction yourself
Overview
baton-proxy wraps an MCP server and captures friction events. From Claude's perspective it is the MCP server; the real server is either its child process or the endpoint it forwards to. Your server receives the arguments it would have received unwrapped: the proxy adds one parameter, user_goal, to each tool's advertised schema and strips it from every call before forwarding.
Two upstream forms. A stdio server is named after -- and run as a subprocess; a remote Streamable-HTTP server is named with --url, with BATON_UPSTREAM_AUTH_TOKEN sent upstream as a bearer token. They are mutually exclusive.
uvx baton-proxy -- python server.py # stdio, as a subprocess uvx baton-proxy --url "https://mcp.example.com/mcp" # remote, as a bridge
uvx (no install) or pipx · scan needs a server already configured in Claude (~/.claude.json).The following diagram illustrates how the proxy sits between Claude and your server:
- The proxy is the server, as far as Claude is concerned. Your real server runs as its child process and receives the arguments it would have received unwrapped.
- Green marks what Baton owns, here the proxy and the Console. Everything neutral is yours or your client's, and none of it changes.
- Three sinks, one event. The same envelope goes to stderr, a file, and an
https://collector; which ones are live is configuration.
Install
For a one-off scan, install nothing: uvx runs it on demand.
uvx baton-proxy scan --config <server-name>
To wrap a server permanently in Claude's config, put baton-proxy on your PATH so the config can invoke it directly:
pipx install baton-proxy
Plain pip install baton-proxy works if you manage your own Python env. Requires Python 3.11+. Currently 0.x, and it sends 1.0 events; see Stability and versions and the releases.
Quickstart
Replace your MCP server entry in Claude's config. The only change is wrapping your existing command:
// Before
{ "command": "npx", "args": ["@vendor/mcp-server"] }
// After. Events go to stderr + /tmp/baton-proxy.jsonl
{ "command": "baton-proxy", "args": ["--", "npx", "@vendor/mcp-server"] }
Restart Claude and drive a few tool calls. Then see what happened:
// In conversation, just ask Claude. It is told where the file is,
// and every line carries a session_id it can filter on:
"What went wrong in this session?"
// Or inspect raw:
cat /tmp/baton-proxy.jsonl | jq -c '{type: .event_type, payload}'
To ship events to a Console, add four env vars:
{
"command": "baton-proxy",
"args": ["--", "npx", "@vendor/mcp-server"],
"env": {
"BATON_EVENT_SINK": "https://console.example.com",
"BATON_TENANT_ID": "your-tenant",
"BATON_API_KEY": "bk_live_...",
"BATON_CONSENT_TOKEN": "customer-consented"
}
}
scan
Preview friction on a server you already have configured, with no permanent install and no change to your Claude config.
uvx baton-proxy scan --config my-server
scan reads the named entry from ~/.claude.json, reuses its credentials, drives a headless agent, and writes ./baton-report.md. Events are written to a temp file and deleted after the report, so nothing leaves your machine.
| Flag | Description |
|---|---|
| --config <name> | Entry name in ~/.claude.json (required). |
| --config-file <path> | Use a specific config file. |
| --timeout <seconds> | Bound the run (default: 300s). |
| --out <path> | Report output path (default: ./baton-report.md). |
Configuration
All knobs are environment variables. Every one has a default, so no config file is needed.
| Variable | Default | Purpose |
|---|---|---|
| BATON_EVENT_SINK | stderr:,file:///tmp/baton-proxy.jsonl | Where events go. Comma-separated for fan-out. https://… POSTs to {url}/v0/events, file:///path appends JSONL, stderr: writes to stderr. |
| BATON_TENANT_ID | local | Tenant identifier sent on every event. |
| BATON_CONSENT_TOKEN | local | Per-process consent token. Must be replaced before using an https:// sink. |
| BATON_API_KEY | unset | Bearer token. Required when sink is https://. |
| BATON_VENDOR_ID | local | Labels the install for the operator. A placeholder: a remote sink refuses to start while it is still local, because the Console buckets friction by vendor. |
| BATON_INTENT_PARAM | required | How user_goal is added. required lists it in the advertised required set; optional does not. That is an advertisement only: nothing validates it and no call fails for leaving it out. There is no off. |
| BATON_ANNOTATE | off | on adds baton_annotate, the tool the agent uses to report problems, and the instructions for it. See Injected tools. |
| BATON_PRINCIPAL_ID_HMAC_KEY | — | No longer read, since 0.6.13. The proxy does not hash the caller id. |
| BATON_UPSTREAM_AUTH_TOKEN | unset | Credential for the --url bridge, sent upstream as Authorization: Bearer. Ignored by the stdio form. |
| BATON_UPSTREAM_TIMEOUT | 60 | Read timeout in seconds for the --url bridge. |
| BATON_PROXY_LOG_FILE | unset | Path to tee proxy logs to. |
The three rungs
| Rung | Sink | Env additions |
|---|---|---|
| 1. Default | stderr + /tmp/baton-proxy.jsonl | none |
| 2. Custom local | Your path | BATON_EVENT_SINK=file:///your/path.jsonl |
| 3. Ship to Console | Hosted | BATON_EVENT_SINK + BATON_API_KEY + BATON_TENANT_ID + BATON_CONSENT_TOKEN + BATON_VENDOR_ID |
https:// sink is configured but BATON_API_KEY is unset, or BATON_CONSENT_TOKEN or BATON_VENDOR_ID is still "local".Remote servers
The proxy also fronts a remote HTTPS MCP server over the Streamable HTTP transport, instead of spawning a subprocess. It stays stdio-facing to Claude and forwards each message as an HTTP POST, streaming the JSON or SSE response back. Injection, emission and correlation are the same code as the subprocess path.
{
"command": "baton-proxy",
"args": ["--url", "https://mcp.vendor.example.com/mcp"],
"env": { "BATON_UPSTREAM_AUTH_TOKEN": "..." }
}
--url and the -- <command> form are mutually exclusive.
Sessions. The proxy gives each process one session id, so every call through one proxy run is one session, whether it spawns the server or fronts a remote one. Its events carry no caller id, because the proxy has no setting for who is calling. It still forwards what the client puts in a request's _meta, and some clients put their own id for the user there.
baton_annotate, when on, stays usable.Injected tools
Off by default. With BATON_ANNOTATE=on, the proxy adds baton_annotate to the upstream server's tool list during the MCP handshake. The upstream server never sees it. When the proxy writes events to a local file, the instructions it appends name that file's path, so Claude can read it and explain what went wrong. The try kit turns it on for you.
baton_annotate
Called by Claude (unprompted) when a call goes wrong or no tool fits the request. Claude says what happened in its own words; there is no category to pick. Emits an annotation event with what_happened, tool_name (or none when no tool exists), intent (from user_goal), and optionally suggested_improvement and context. Available in all sink modes.
What it captures
Per real tool call, three event types are emitted matching the Baton wire format:
| Event | Payload fields |
|---|---|
| tool_call_start | tool_name, params |
| tool_call_end | tool_name, result, duration_ms |
| tool_call_error | tool_name, error_type, error_body, duration_ms, and result — the full response body, on the shape below |
Each line in the events file is one JSON object, { event_type, payload }. A failure the server returned rather than raised — MCP files one as a successful 200 whose body sets isError — lands like this:
{"event_type":"tool_call_start","payload":{"tool_name":"run_sql","params":{"statement":"ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)"}}}
{"event_type":"tool_call_error","payload":{"tool_name":"run_sql","error_type":"tool_error","error_body":"foreign keys are not supported","result":{"content":[{"type":"text","text":"foreign keys are not supported"}],"isError":true},"duration_ms":412}}
{"event_type":"annotation","payload":{"what_happened":"asked run_sql to add a foreign key; it answered that foreign keys are not supported","intent":"add a foreign key so an order can't reference a missing customer","suggested_improvement":"list unsupported DDL in the tool description","tool_name":"run_sql"}}
error_type is the literal tool_error rather than an exception class, because there is no exception; result carries the whole response body, because the reason lives inside it and a flat error_body string would be all that survived. Proxy 0.6.11 and later; the Python SDK from 0.8.10 and the TypeScript SDK from 0.4.0 classify the same shape the same way. The gateway path also files it as tool_call_error, with result, as the other paths do.Intent parameters
This is how the proxy captures why a call was made, not just what happened. At tools/list it adds one string parameter, user_goal, to every upstream tool's advertised schema. The agent fills it in as it composes each call, and the proxy strips it at tools/call before forwarding.
| Parameter | Captured as |
|---|---|
user_goal | tool_call_start.payload.call_intent. Written as '<n>: <what this call is for>; success is <what its result should show>', where n is the number of the user's current message (3: list open invoices; success is a list with amounts) |
In the default mode, user_goal is advertised in each tool's required list. That is advertisement only: a call that leaves it out is served exactly as it would be unwrapped, and call_intent is simply null. A wrapped tool's schema lists ["customer", "user_goal"] as required where the unwrapped one listed ["customer"].
Before 0.6.19 the proxy added two more parameters, expected_result and overall_task. A client still holding a tool list from then may send them; they are stripped before forwarding too.
A parameter description reaches the model at the moment it composes the call, on every client. Some clients drop InitializeResult.instructions entirely, so instructions alone are not a reliable channel. A tool that already declares a parameter of that name is left alone: its value is forwarded untouched and never read as intent.
Trust & security
- Open source, Apache 2.0. github.com/good-timing/baton-proxy
- Fail-open. A Console outage never breaks the MCP pipe. Emission is enqueued on a background thread.
- Outbound-only. The proxy never accepts inbound connections.
- No external dependencies. Pure stdlib: no pydantic, no httpx.
- Credential isolation.
BATON_*vars are filtered from the upstream subprocess env. - Scrubbed on your machine. Same rules as the SDK, applied before any event leaves. PII scrubbing →
turn the signal into a roadmap
Overview
The proxy and the SDK capture friction one server at a time. The Baton Console is the hosted service that collects those events across every customer and every session and turns them into something you can act on. It does what a single local report can't: it shows the friction across your whole customer base, ranked, with the evidence behind every number one click away.
- Many customers, one view. Sessions arrive from every customer running your server and are grouped together, so what you read is demand across your base, not one transcript at a time.
- Every output is text you copy. Baton drafts the fix and hands it to you. It does not open tickets or reach back into a customer's agent. Nothing ships without you.
What you see
Four tabs, one filter bar across all of them. Every number is a link: click it and you land on the sessions behind it with the filter already applied.
The Overview tab
How agents experience your server, on one screen. Four stat tiles, picked from what your traffic has: sessions, tasks, identified users, the share of tool calls that returned an error, sessions containing a failure, and reports filed by agents.
Below them, four categories with a count each: recurring errors, token costs, high-friction sessions, and tools whose calls fail often. Then the three most recent sessions worth a person's attention. A server card lists your tools, the surface hash and when it was last seen, and warns you if your server sends no initialize instructions, because then every agent connects with zero guidance from you.
The Insights tab
Five panels. Each is a list of things you could go and fix.
High-friction sessions
Four counts: the last tool call failed, a tool failed and never succeeded again in that task, any call failed at all, and sessions you rated low. A session can sit in more than one.
Recurring errors
Errors that repeat across sessions, grouped by tool. Each row names where the fix belongs: the tool description, the error message, the implementation, or account config.
Token costs
What your surface costs every session before anyone calls anything. Tool definitions that are never called, mandated fetches, and responses large enough to push earlier results out of the agent's context.
Tool error rates
Every tool ranked by how often its calls come back as errors, with p50 and p95 latency and the error codes, plus the tools nothing has called.
The fifth is Filed feedback: what agents told you they needed and could not get, in their own words, through the report tool, which is off by default. That lane only fills when reports are on and the agent chooses to report, so it is usually the smallest of the five.
The Sessions tab
The session list, filtered and paged. Open one and you get its tasks, the calls inside each task, and two lanes of markers: what the agent filed, and what Baton detected. Click a marker and the call list narrows to exactly the calls it counted, so a number always shows its evidence.
Run Explain on a session and a model reads it and writes what the user was trying to do and how it went, including a satisfaction rating. You can flag a session to come back to, or exclude it from your numbers. Excluding one requires a written reason, so the next person to read the number can see why it moved.
The Live tab
Every event as it arrives, newest first, refreshed every couple of seconds. One row shape, no highlighting. This is the raw stream, for watching your own setup work while you drive an agent at it. Events appear within seconds of the call. Anything that interprets them lives on the other three tabs.
Access & security
The Console is hosted by us and auditable by you. Your data is single-tenant, and every event is logged and inspectable, so you can see exactly what each agent sent, when, and why. Scrubbing runs before anything leaves your machine, and is on by default. It redacts emails, North American phone numbers, common API keys and tokens, and card numbers written without spaces. It is pattern matching, not a guarantee. Free text inside a tool argument or result is sent as written, so decide what your tools hand back. Baton never reads your logs, your database or anything else in your process.
The Console is where you act on what the proxy and the SDK capture. Get started →