Metadata-Version: 2.4
Name: baton-sdk
Version: 0.2.1
Summary: Baton — structured signal capture SDK that wraps a vendor's MCP server. Thin event emitter; Console worker assembles, interprets, dispatches.
Author: Good Timing
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for describing the origin of the Work and
              reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Support. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or support.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Good Timing
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/good-timing/baton
Project-URL: Repository, https://github.com/good-timing/baton
Project-URL: Documentation, https://github.com/good-timing/baton/tree/main/docs
Project-URL: Issues, https://github.com/good-timing/baton/issues
Keywords: mcp,agents,support,signals,observability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.14
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0
Requires-Dist: httpx>=0.25
Provides-Extra: mcp
Requires-Dist: mcp>=1.20; extra == "mcp"
Provides-Extra: fastmcp
Requires-Dist: fastmcp>=2.10; extra == "fastmcp"
Provides-Extra: all
Requires-Dist: baton-sdk[mcp]; extra == "all"
Requires-Dist: baton-sdk[fastmcp]; extra == "all"
Provides-Extra: dev
Requires-Dist: baton-sdk[all]; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-httpserver>=1.0; extra == "dev"
Dynamic: license-file

# Baton SDK

*Structured signal capture for agent-mediated tool use. Thin event capture surface with pluggable sinks (stdout / file / HTTP / fan-out); a worker on the other side of the sink assembles signals, applies policy, and dispatches.*

**Pre-1.0 (`0.2.0`)** — public API not yet stable; breaking changes flagged in [SPEC §13](docs/SPEC.md). Vendor integration via `install_baton(mcp, ...)` against either the official Anthropic `mcp` SDK (`baton.integrations.mcp`) or the standalone `fastmcp` library (`baton.integrations.fastmcp`); library API path (`baton.Client` / `AsyncClient`) for Skill-instrumented code. Thin SDK + fat collector worker per [CHARTER ADR-4](docs/CHARTER.md). MCP tool-call events captured across Claude Code, Cursor, and Claude Desktop; the proactive + reactive annotation flow works on Claude Code and Cursor (per-runtime support matrix in [SPEC §5.1.3](docs/SPEC.md)). See [`docs/SPEC.md`](docs/SPEC.md) for the wire protocol.

![Baton in action — events streaming to stderr](docs/demo.gif)

*30 seconds, zero config — `python examples/01_stdout/demo.py` emits structured signals you can pipe through `jq`. See [`examples/`](examples/) for the four-rung sink ladder.*

---

## What Baton is

MCP is Anthropic's [Model Context Protocol](https://modelcontextprotocol.io) — the standard way agents (Claude Code, Cursor, ChatGPT, etc.) discover and call vendor tools. MCP standardizes the transport and tool-discovery layer; it doesn't capture *why* a call happened or whether it actually helped the user. Baton instruments agent–tool interactions on the vendor side — either by wrapping a vendor's MCP server (middleware) or by direct library-API calls in vendor code — and captures the four things only an agent-using-a-tool has in one context — **intent**, **tool calls**, **observed outcomes**, **expected outcomes** — plus friction signals (eight types per [SPEC §3.1](docs/SPEC.md)). It hands these as events to a sink of your choice; an `HttpSink` pointed at a collector (your own or a hosted Console) is the production path — the collector interprets, applies policy, and routes structured signals to the vendor's agent layer (which triages, deflects, or escalates to human support).

> **PII scrubbing in 0.1.x is a no-op identity function** (`src/baton/scrub.py`). Vendors handling sensitive end-user data should wire their own scrubber via `VendorConfig(scrubber=...)` until the default scrubber lands; events otherwise ship with whatever params/results/error bodies cross the MCP transport.

## Shape of the protocol — agent-to-agent, not agent-to-human

```
   customer  ↔  customer agent  ↔  Baton  ↔  vendor agent  ↔  vendor support
     ↑          (Claude / Cursor /    (this project)    (vendor's AI         (humans, last
   human         ChatGPT / Codex)                       assistant)            resort)
```

Baton is the **protocol layer connecting two agent layers**, with humans on both ends. The vendor's agent (triage / deflection / structured-action routing) is the FIRST consumer of Baton signals; humans are the fallback when the agent can't resolve. This is the shape of modern agent-to-agent support — not agent-to-human handoff.

## Implementation — two integration paths

### MCP middleware path

```
Customer agent (Claude / Cursor / ChatGPT / …)
            │ MCP transport
            ▼
   ┌────────────────────────────┐
   │  Vendor MCP server         │
   │  ┌──────────────────────┐  │      Sink
   │  │ baton-sdk            │  │  (stdout / file / http / multi)
   │  │  • middleware        │  │ ─────────────────▶ Collector
   │  │  • annotation tool   │  │                    (your own, or a hosted
   │  │  • capture surface   │  │                     Console — Baton is
   │  │  • PII scrub         │  │                     collector-agnostic)
   │  └──────────────────────┘  │                          │
   │  ┌──────────────────────┐  │                          ▼
   │  │ vendor tools         │  │                    Vendor agent layer
   │  └──────────────────────┘  │                    (triage / deflection /
   └────────────────────────────┘                     routing)
                                                            │
                                                            ▼
                                                     Human support
                                                     (last resort)
```

### Library API path (Skills pattern)

```
Customer agent runtime (Claude Code / Cursor — following a vendor-published Skill)
   ┌──────────────────────────────────────────┐
   │  agent-generated code (vendor's Skill)   │
   │  ┌────────────────────────┐              │      Sink
   │  │ baton.Client           │              │  (stdout / file / http / multi)
   │  │  • client.trace(...)   │              │ ─────────────────▶ Collector
   │  │  • client.annotate     │              │                    (same as MCP path)
   │  │  • PII scrub           │              │                          │
   │  └────────────────────────┘              │                          ▼
   │  ┌────────────────────────┐              │                    Vendor agent layer
   │  │ vendor SDK / HTTP call │ ───► Vendor  │                          │
   │  └────────────────────────┘     API      │                          ▼
   └──────────────────────────────────────────┘                    Human support
```

Everything downstream of the sink is identical across both paths — same wire envelope, same collector, same vendor-agent / human-support routing. The SDK has no state, no policy, no routing logic; everything beyond capture lives on the other side of the sink. See [docs/SPEC.md §11](docs/SPEC.md) for the capture/interpretation/egress separation.

## Install

```sh
pip install baton-sdk              # core only — library API for Skill-instrumented code
pip install baton-sdk[mcp]         # +MCP integration for the official `mcp` SDK (Anthropic's)
pip install baton-sdk[fastmcp]     # +MCP integration for the standalone `fastmcp` library
pip install baton-sdk[all]         # everything
```

Core SDK ships always. Protocol-specific surfaces live under `baton.integrations.*` and require opt-in extras — the same pattern Sentry / Datadog / OpenTelemetry use.

## Minimal MCP integration

Two parallel adapters covering the two production Python MCP libraries. The vendor-facing API (`install_baton`, `VendorConfig`, `BatonHandle`) is identical across both — only the import path differs.

### Which one do I need?

| You import FastMCP via… | Use the adapter at… | Install extra |
|---|---|---|
| `from mcp.server.fastmcp import FastMCP` (Anthropic's official `mcp` SDK — the dominant library) | `baton.integrations.mcp` | `baton-sdk[mcp]` |
| `from fastmcp import FastMCP` (standalone `fastmcp` library, v2.x by jlowin) | `baton.integrations.fastmcp` | `baton-sdk[fastmcp]` |

### Official `mcp` SDK path

```python
import os
from mcp.server.fastmcp import FastMCP
from baton.integrations.mcp import install_baton, VendorConfig
from baton.sinks import HttpSink   # or StdoutSink / FileSink / MultiSink

mcp = FastMCP("your-vendor-mcp")
install_baton(mcp, VendorConfig(
    vendor_id="your-vendor",
    vendor_display_name="Your Vendor",
    consent_token=os.environ["BATON_CONSENT_TOKEN"],
    sink=HttpSink(
        url=os.environ["BATON_INGEST_URL"],
        api_key=os.environ["BATON_API_KEY"],
    ),
))

@mcp.tool()
async def your_tool(...): ...
```

### Standalone `fastmcp` path

```python
import os
from fastmcp import FastMCP
from baton.integrations.fastmcp import install_baton, VendorConfig
from baton.sinks import HttpSink

mcp = FastMCP("your-vendor-mcp")
install_baton(mcp, VendorConfig(
    vendor_id="your-vendor",
    vendor_display_name="Your Vendor",
    consent_token=os.environ["BATON_CONSENT_TOKEN"],
    sink=HttpSink(
        url=os.environ["BATON_INGEST_URL"],
        api_key=os.environ["BATON_API_KEY"],
    ),
))

@mcp.tool()
async def your_tool(...): ...
```

That's the integration. `install_baton` registers a vendor-namespaced annotation tool (`<vendor_id>_annotate`), sets the MCP server `instructions` motivating proactive + reactive annotation, captures events at the MCP transport boundary, and hands those events to your sink. The SDK is whitelabeled — no Baton-branded strings reach the calling agent or end user.

Under the hood the two adapters use different hook mechanisms — the official `mcp` SDK's FastMCP has no middleware system, so its adapter wraps each registered tool handler in place; the standalone `fastmcp` library uses its native middleware chain. The choice doesn't surface to vendors; both emit identical events through the same sink layer.

## Sinks — where events go

The SDK is sink-agnostic. The capture surface is the same regardless of destination:

| Sink | Use case |
|---|---|
| `StdoutSink()` | Zero config, no backend. Events to stderr as JSON Lines. Default if `sink=` is omitted. |
| `FileSink("./events.jsonl")` | Capture to a file for later analysis. |
| `HttpSink(url=..., api_key=...)` | POST to any HTTP collector — your own, a hosted Console, anyone's. Bounded buffer + retry + circuit breaker. |
| `MultiSink([...])` | Fan out (e.g., stdout + http during dev). |

Four runnable examples laddered by complexity in [`examples/`](examples/) — `01_stdout` → `02_local_file` → `03_local_https` → `04_hosted_console`. The SDK is identical across all four; only the sink changes.

## Library API — for non-MCP integrations

For vendors whose customers reach the API via agent-generated code (Skills pattern) rather than MCP tool calls, the library API (`baton.Client` / `baton.AsyncClient`) is the equivalent capture surface. Same event envelope, same sink layer, same wire contract — different emission boundary:

```python
from baton import Client, SignalType
from baton.sinks import HttpSink

client = Client(
    vendor_id="your-vendor",
    consent_token=os.environ["BATON_CONSENT_TOKEN"],
    sink=HttpSink(url=..., api_key=...),
)

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)
```

Worked end-to-end at [`examples/skill_demo/`](examples/skill_demo/); full surface (sync + async parity, `client.annotate(...)`, `trace.annotate(...)`, exception path) covered in `src/baton/client.py` docstrings and validated by [`examples/library_api_smoke_test/`](examples/library_api_smoke_test/).

### Choosing between MCP integration and Library API

| Concern | MCP integration (`install_baton`) | Library API (`Client`) |
|---|---|---|
| Where instrumentation lives | Vendor side (in MCP server runtime) | Agent side (in agent-generated code) |
| Setup | Vendor's MCP server adds 5 lines | Vendor publishes a Skill teaching agents the pattern |
| Reliability | Deterministic — wrap/middleware runs on every tool call | Soft — depends on agent following the Skill |
| Annotation surface | MCP tool (`<vendor>_annotate`) with MUST/REQUIRED framing | Python function calls (`trace.annotate(...)`) |
| Vendor API call captured? | Yes (vendor controls MCP server) | Yes (agent calls vendor API from inside trace context) |
| Where partner invests | Wire SDK into their MCP server | Author + maintain a Baton-aware Skill |
| Best fit | Vendors with MCP servers as their primary surface | Vendors using Skills as their primary distribution |

Both paths emit identical events through the same sink — downstream of the sink, correlation + policy + dispatch are unchanged.

## Development

```sh
make install          # uv / pip install -e ".[dev]" in .venv
make test             # pytest -q
make ci               # lint + typecheck + test (CI gate)
make format           # ruff format
```

See `Makefile` for the full target list.

## What's in this repo

```
baton/
├── src/baton/         # SDK package (Python)
│   ├── client.py                    # library API (Client, AsyncClient, Trace)
│   ├── sinks.py                     # Sink ABC + StdoutSink / FileSink / HttpSink / MultiSink
│   ├── events.py / scrub.py / _state.py  # core substrate
│   └── integrations/
│       ├── mcp/      # Official `mcp` SDK adapter (install_baton, VendorConfig, tool-handler wrapping)
│       └── fastmcp/  # Standalone `fastmcp` library adapter (install_baton, VendorConfig, middleware)
├── docs/
│   ├── SPEC.md                     # the wire protocol — the hero artifact
│   └── CHARTER.md                  # load-bearing project decisions
├── examples/          # runnable examples (skill_demo, library_api_smoke_test)
├── tests/             # test suite
├── pyproject.toml
├── Makefile
├── AGENTS.md          # per-repo guidance for AI coding agents (agents.md convention)
├── CHANGELOG.md       # user-facing release notes (SPEC §13 has wire-format changes)
├── CONTRIBUTING.md    # dev setup + PR conventions
├── CODE_OF_CONDUCT.md
├── SECURITY.md        # disclosure policy
├── LICENSE            # Apache 2.0
└── README.md          # this file
```

The Console (ingest + worker + Channels + UI) lives in a separate sibling repo.

## Status

Pre-1.0 (`0.1.0`). Wire format and public API are not yet stable; breaking changes will be flagged in [docs/SPEC.md §13](docs/SPEC.md) and the top-level [CHANGELOG.md](CHANGELOG.md).

For design-partner conversations: reach out via [Good Timing](https://goodtiming.ai).
