Skip to main content

sancho-observer

Analytics and observability for MCP servers written in Python. The SDK records one event per MCP request (which tool, which agent, how long, did it fail) and sends them in batches to a Sancho collector.

  • Works with servers built on the official mcp package: MCPServer and the low-level Server (mcp 2.x), FastMCP and the low-level Server (mcp 1.x).
  • stdio and streamable HTTP transports.
  • No runtime dependencies beyond the standard library. Python 3.10+.
  • Never raises into your server, never writes to stdout, never blocks a request on the network, and does nothing at all without SANCHO_TOKEN.

Install

pip install sancho-observer

Use

from mcp.server.mcpserver import MCPServer  # mcp 1.x: from mcp.server.fastmcp import FastMCP
import sancho_observer

mcp = MCPServer("issue-tracker", version="1.4.0")
sancho_observer.instrument(mcp)


@mcp.tool()
def search_issues(query: str) -> str: ...


mcp.run()  # stdio, or mcp.run("streamable-http")

Then set two environment variables where the server runs:

export SANCHO_TOKEN=sancho_...                  # ingest token of this MCP server
export SANCHO_ENDPOINT=https://collector.example.com   # your collector's base URL

instrument() works the same with a low-level Server. Call it once, before the server starts serving. It returns the SDK Client; you rarely need it, but client.flush() and client.shutdown() are there for short-lived processes (events are also flushed at exit).

Options

Everything can be set in code; explicit values win over environment variables.

sancho_observer.instrument(
    mcp,
    token="sancho_...",
    endpoint="https://collector.example.com",
    capture_payloads=True,
    attributes={"env": "production", "region": "eu-west-1"},
)
Environment variable Option Default Meaning
SANCHO_TOKEN token – Ingest token. Without it the SDK is a complete no-op: no network, no threads.
SANCHO_ENDPOINT endpoint – Collector base URL. Required; there is no built-in default.
SANCHO_SERVER_NAME server_name the server's own name Name shown in Sancho.
SANCHO_SERVER_VERSION server_version the server's own version Version shown in Sancho.
SANCHO_CAPTURE_PAYLOADS capture_payloads off Also record tool arguments and results (redacted, truncated). "remote": the agent companion settings decide.
SANCHO_SURVEYS surveys on Allow agent surveys when they are switched on in Sancho (see Agent companion).
SANCHO_REMOTE_CONFIG remote_config on Fetch the agent companion settings from the collector.
SANCHO_DEBUG debug off Diagnostic logs on stderr.
SANCHO_IDENTITY_SALT identity_salt – Secret key for hashing user/account ids (see User and account context).
identify – fn(IdentifyContext) -> Identity | None: the user/account behind a request.
hash_identities True False sends user/account ids unhashed (code only, no env variable).
attributes {} Low-cardinality labels sent with every batch.
redact – fn(kind, value) -> value, applied to captured payloads after the built-in redaction.
transport detected Force "stdio", "streamable-http", "sse" or "other".

Batching knobs (flush_interval, batch_size, max_queue_size, request_timeout, max_attempts) are available on sancho_observer.Options and as keyword arguments.

User and account context

MCP carries no user identity, so Sancho never sends one on its own: only what your resolver returns or what you pass to set_identity is sent (auth info and headers are handed to the resolver, never sent). To see which of your users and customer accounts use a tool, attach a user id, an account id (tenant, workspace, organization) and a few low-cardinality traits yourself, either with a resolver called once per request or from inside a handler.

import sancho_observer
from sancho_observer import Identity, IdentifyContext


def identify(ctx: IdentifyContext) -> Identity | None:
    # ctx: method, target, params, headers, session_id, auth_info (the mcp AccessToken when
    # the server uses the mcp package's OAuth support), request_context, http_request.
    if ctx.auth_info is None:
        return None
    claims = ctx.auth_info.claims or {}
    return Identity(user_id=ctx.auth_info.subject, account_id=claims.get("org_id"), traits={"plan": "pro"})


sancho_observer.instrument(mcp, identify=identify)


@mcp.tool()
def search_issues(query: str, workspace: str) -> str:
    # Attach (or override) identity for the request being handled.
    sancho_observer.set_identity(account_id=workspace, traits={"plan": plan_of(workspace)})
    ...
  • set_identity(user_id=..., account_id=..., traits=...) overrides the resolver field by field (traits are merged, the setter wins; None leaves a field unchanged). It works in sync and async tool, prompt and resource handlers on mcp 1.x and 2.x. Outside a request, or when the SDK is disabled, it does nothing.
  • The resolver runs once per observed request, and never without SANCHO_TOKEN. If it raises, the event is sent without its identity (logged on stderr with SANCHO_DEBUG).
  • Pseudonymous by default. user_id and account_id are trimmed and hashed in the process, before the event is queued: the first 32 hex characters of HMAC-SHA256 with identity_salt / SANCHO_IDENTITY_SALT as the key, or of plain SHA-256 without a salt. Set a salt: an unsalted hash of an email address can be reversed by guessing. Keep the salt secret and stable (changing it re-keys every user); use the same salt in all Sancho SDKs to get the same hashes. sancho_observer.hash_identity(id, salt) computes the same value, e.g. to look a user up.
  • hash_identities=False sends ids as given (trimmed, at most 128 bytes). Only do this for ids that are already opaque.
  • Traits are sent as-is, never hashed: keep them low-cardinality (plan, region, tier) and never put personal data in them. At most 8 traits; keys up to 64 bytes, values up to 128 bytes; numbers and booleans become strings; empty keys or values and other types are dropped.

Low-level client

For custom integrations, send events yourself (JSON form of McpEvent, camelCase keys):

from sancho_observer import Client

client = Client()  # reads SANCHO_TOKEN / SANCHO_ENDPOINT
client.record(
    {"method": "tools/call", "target": "search_issues", "status": "CALL_STATUS_OK", "durationUs": 1530}
)
client.flush()
client.shutdown()

eventId and startTimeUnixNano are filled in when missing.

Client capabilities

Every event records which optional features the client declared (elicitation, sampling, roots, tasks, the MCP Apps UI extension, ...), automatically: from _meta["io.modelcontextprotocol/clientCapabilities"] on each request (MCP 2026-07-28), else from the session's initialize handshake. Only the keys are sent, one level deep (for example elicitation, elicitation.form, extensions.io.modelcontextprotocol/ui), never their values; sancho_observer.capability_keys(caps) shows what a capabilities object becomes.

Feedback

Latency and errors tell you whether a tool worked; feedback tells you whether its result was useful. Report a rating for a call with sancho_observer.feedback():

sancho_observer.feedback(
    event_id=event_id,  # or request_id=<JSON-RPC id> (optionally with session_key=...)
    rating="negative",  # "positive" or "negative"
    reason="wrong project",  # optional, max 1 KiB
    attributes={"source": "thumbs"},  # optional, low-cardinality labels (max 32)
)

While a request is being handled, sancho_observer.current_event_id() returns the id of the event Sancho records for it (None outside an instrumented request). With an MCP App (the io.modelcontextprotocol/ui extension), return it in the tool result's _meta so the UI can send it back to a rating tool:

from mcp.types import CallToolResult, TextContent


@mcp.tool()
def search_issues(query: str) -> CallToolResult:
    return CallToolResult(
        content=[TextContent(type="text", text="...")],
        _meta={"sancho/eventId": sancho_observer.current_event_id()},
    )


@mcp.tool()
def rate_result(event_id: str, helpful: bool) -> str:
    """Called by the UI's thumbs up / down buttons."""
    sancho_observer.feedback(event_id=event_id, rating="positive" if helpful else "negative")
    return "Thanks!"

When the event is known to this process (the last 10,000), the feedback is linked to it and its target (tool name) and session key are filled in; a request_id that matches no event, or more than one, is sent unlinked. feedback() never raises and returns the feedback id, or None when it was dropped (no SANCHO_TOKEN, invalid rating, ...). Client.feedback() takes the same arguments. Feedback is batched and retried like events, through the collector's ExportFeedback RPC; a collector too old to know it makes the SDK drop the feedback, events are unaffected. Do not put personal data in reason.

Built-in feedback

The SDK can offer a ready-made rating tool instead (ADR 0017). Switch it on in Sancho (the server's Agent companion page, "Result rating"), with no code change, or in code as the default:

from sancho_observer import AgentFeedback

sancho_observer.instrument(mcp, agent_feedback=AgentFeedback(agent=True))  # or SANCHO_AGENT_FEEDBACK=on

With agent=True:

  • every successful tool result gets its event id in _meta["io.sancho/eventId"] (sancho_observer.RESULT_ID_META) and a last text line Result ID: <id> (result_id_in_text=False leaves the line out);
  • a tool rate_result (tool_name= to rename it) takes result_id, rating (positive/negative), an optional reason (≤ 300 characters) and from_view; it answers Thanks, recorded., or Not recorded. when that result was already rated;
  • one paragraph is added after your server's own instructions, asking the model to rate the results it answered from (instructions="…" replaces it, instructions=False drops it).

AgentFeedback(tool=True) offers the tool only to your MCP App view (_meta.ui.visibility: ["app"]): no result line and no instructions. The view calls rate_result with the id from _meta and from_view: true.

Ratings show up in Sancho's feedback with attributes.source agent or view. The settings in Sancho win over the code option (Off turns it off); turning surveys off in code keeps it off. If your server already has a tool with that name, the SDK adds nothing. Some MCP directories review server instructions that ask the model to call a tool; use the app-only mode or no instructions there.

Agent companion

Inside your MCP server this SDK is the Sancho agent companion: it rides along with the server, records how agents use it and, when you ask it to, asks the agents how it went (ADR 0016). You configure it per server on the server's Agent companion page in Sancho (or with the Sancho MCP tool update_companion_config); the SDK fetches the settings at start-up and polls for changes, so no release is needed.

What the settings control:

  • Collection: payload capture (off, arguments only, arguments and results), user and account ids, client capabilities, catalog snapshots, and recording only calls (tools/call, prompts/get, resources/read).

  • Agent surveys, all off until you switch them on:

    • a feedback tool, report_tool_feedback, that agents can call to say whether a tool helped, what they used instead, whether the data was too much or too little, and what was missing;
    • campaigns that append a short, sampled question to tool results (at most 20 % of calls, 3 asks per session by default) and a debrief after a task-finishing tool.

    The SDK answers the feedback tool itself: your handlers never see those calls and they are not counted as usage. Each answer carries the server version and a hash of the tool definition the agent saw, so feedback on 1.3 is never mixed with feedback on 1.4. Set SANCHO_SERVER_VERSION to your release version or git SHA.

Your code stays the ceiling:

  • Payload capture is off unless the code allows it: with capture_payloads="remote" (or SANCHO_CAPTURE_PAYLOADS=remote) the settings decide; with capture_payloads=True they can only turn it down.
  • surveys=False (or SANCHO_SURVEYS=off) never offers the feedback tool or asks agents, whatever the settings say.
  • remote_config=False (or SANCHO_REMOTE_CONFIG=off) stops fetching settings; only local options apply.

The SDK reports the settings revision it applied, and anything your code blocked, so the settings page shows each running instance.

Self-hosting

Run your own Sancho (see the repository's deployment docs) and point SANCHO_ENDPOINT at your collector, for example http://localhost:8081 for the repository's docker compose setup. The package is the same for hosted and self-hosted collectors.

What is captured

Per request (one event once the response is sent):

  • JSON-RPC method and target (tool name, prompt name or resource URI), JSON-RPC request id.
  • Status: OK, TOOL_ERROR (isError: true), PROTOCOL_ERROR with the JSON-RPC error code, INPUT_REQUIRED, CANCELLED; a short error message (max 1 KiB).
  • Start time, duration, request and response size in bytes.
  • Client name/version/title from _meta["io.modelcontextprotocol/clientInfo"] (MCP 2026-07-28) or from the initialize handshake (2025-11-25), and the protocol version.
  • The client's capability keys (see Client capabilities).
  • Transport, W3C trace context (_meta.traceparent when the client sent one, otherwise new ids), and a session key (Mcp-Session-Id on HTTP; on stdio, where one process serves one client, the process instance id).

When you provide them (see User and account context): a hashed user id, a hashed account id and up to 8 traits.

Per process: SDK name/version, server name/version, a random instance id, your attributes, and a snapshot of the tool/prompt/resource catalog (names, descriptions, schemas) whenever it changes.

Not captured unless you opt in: tool arguments and results. With SANCHO_CAPTURE_PAYLOADS=true they are recorded as JSON, with values under keys that look sensitive (containing password, secret, credential, apikey, cookie, ..., or ending in token, auth, authorization, sessionid, signature, ...) replaced by [REDACTED], then passed to your redact hook, then truncated to 64 KiB each.

How it behaves

  • Events go into a bounded in-memory queue (10 000 by default; the oldest are dropped when it is full). A daemon thread sends them every 2 seconds or as soon as 100 are queued, at most 1000 per request, as Connect JSON over HTTPS.
  • Transient failures (unavailable, resource_exhausted, network errors) are retried with exponential backoff, reusing the same event ids so the collector can deduplicate; the server's backoffMs / Retry-After hints are honoured.
  • An unauthenticated response (bad or revoked token) stops sending for the rest of the process and logs one line to stderr. invalid_argument drops that batch.
  • At interpreter exit the queue is flushed for up to ~2 seconds; the thread never keeps the process alive.

Development

cd sdk/python
uv sync
uv run pytest
uv run ruff check . && uv run ruff format --check . && uv run mypy

License

Apache-2.0

Metadata

Release files for sancho-observer 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sancho-observer 0.3.1
File Size Uploaded Provenance Actions
sancho_observer-0.3.1.tar.gz 69.8 kB With provenance Details for sancho_observer-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sancho-observer 0.3.1
File Interpreter ABI Platform Actions
sancho_observer-0.3.1-py3-none-any.whl Python 3 none any Details for sancho_observer-0.3.1-py3-none-any.whl

Total release size: 121.2 kB

Release files / sancho_observer-0.3.1.tar.gz

Download URL sancho_observer-0.3.1.tar.gz
Size 69.8 kB
Tags Source
SHA-256 checksum
How to use checksums
b7a714d72c515cd2b617dd669ac89fca5257c98491b40c568275b16f9d883f37
BLAKE2b-256 checksum
How to use checksums
e9353e4aa75a593a3d2b1228033b2dfa9c489842080c9d2b947957e89737406c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / sancho_observer-0.3.1-py3-none-any.whl

Download URL sancho_observer-0.3.1-py3-none-any.whl
Size 51.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ec9698ff5a91f9b57a7ffd36ebc6b6fe757b2b148310e588100159ea3b63f8da
BLAKE2b-256 checksum
How to use checksums
a38856593543a257e195a94b4f160be1ade00341d2449eb7022af49c99c83032
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for sancho-observer 0.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for sancho_observer-0.3.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page