sancho-observer 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ .mypy_cache/
2
+ .ruff_cache/
3
+ .pytest_cache/
@@ -0,0 +1,49 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `sancho-observer` Python package are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package
5
+ uses [Semantic Versioning](https://semver.org/). Releases are tagged `sdk/python/vX.Y.Z`.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.0] - 2026-12-04
10
+
11
+ ### Added
12
+
13
+ - Events carry the HTTP `User-Agent` of each request (`userAgent`), so the collector can identify the client of requests that do not carry clientInfo (stateless HTTP, ADR 0011).
14
+ - User and account context (ADR 0012): an `identify` option (`fn(IdentifyContext) -> Identity | None`,
15
+ called once per request with its method, target, params, headers, session id and the mcp
16
+ `AccessToken` when present) and `set_identity(user_id=, account_id=, traits=)` for use inside
17
+ handlers fill the new `userId`, `accountId` and `traits` event fields. Ids are hashed by
18
+ default (first 32 hex chars of HMAC-SHA256 with `identity_salt` / `SANCHO_IDENTITY_SALT`, or
19
+ SHA-256 without a salt; opt out with `hash_identities=False`); traits are limited to 8 entries.
20
+ `hash_identity(id, salt)` exposes the same hash. Nothing is captured unless you provide it.
21
+ - Events carry the client's capability keys (`clientCapabilities`, `clientCapabilitiesKnown`),
22
+ from the request's `_meta` (2026-07-28) or the session's `initialize` (ADR 0015). New
23
+ `capability_keys()` helper.
24
+ - Outcome feedback (ADR 0015): `sancho_observer.feedback()` / `Client.feedback()` report a
25
+ positive or negative rating for a request, by event id or JSON-RPC request id, sent in
26
+ batches through the collector's `ExportFeedback` RPC (dropped when the collector does not
27
+ implement it). `sancho_observer.current_event_id()` returns the event id of the request
28
+ being handled; the event id is now assigned when a request begins.
29
+
30
+ ## [0.1.0] - 2026-12-01
31
+
32
+ ### Added
33
+
34
+ - `instrument(server)` for servers built with the official `mcp` package: the low-level
35
+ `Server` and `MCPServer` (mcp 2.x), and the low-level `Server` and `FastMCP` (mcp 1.x),
36
+ over stdio and streamable HTTP.
37
+ - One event per request with method, target, status (`OK`, `TOOL_ERROR`,
38
+ `PROTOCOL_ERROR` + error code, `INPUT_REQUIRED`, `CANCELLED`), duration, client identity
39
+ (2026-07-28 `_meta` or the 2025-11-25 `initialize` handshake), protocol version,
40
+ transport, W3C trace context, session key, JSON-RPC id and message sizes.
41
+ - Catalog snapshots (tools, prompts, resources, resource templates) with a stable hash,
42
+ sent at start-up and whenever the catalog changes.
43
+ - Opt-in payload capture (`SANCHO_CAPTURE_PAYLOADS`), redacted and truncated to 64 KiB.
44
+ - Low-level `Client` with `record()`, `record_catalog()`, `flush()` and `shutdown()`:
45
+ batching (every 2 s or 100 events, at most 1000 per request), bounded queue that drops
46
+ the oldest events, retries with exponential backoff that reuse the same event ids and
47
+ honour `backoffMs` / `Retry-After`, stop on `unauthenticated`, drop on
48
+ `invalid_argument`, best-effort flush at exit.
49
+ - No-op without `SANCHO_TOKEN`; no runtime dependencies beyond the standard library.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,290 @@
1
+ Metadata-Version: 2.5
2
+ Name: sancho-observer
3
+ Version: 0.2.0
4
+ Summary: Sancho SDK for Python: analytics and observability for MCP servers
5
+ Project-URL: Homepage, https://github.com/nomukaiki/sancho-observer
6
+ Project-URL: Source, https://github.com/nomukaiki/sancho-observer/tree/main/sdk/python
7
+ Project-URL: Changelog, https://github.com/nomukaiki/sancho-observer/blob/main/sdk/python/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/nomukaiki/sancho-observer/issues
9
+ Author: Sancho contributors
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,analytics,mcp,model-context-protocol,observability
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: System :: Monitoring
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Provides-Extra: mcp
26
+ Requires-Dist: mcp>=1.10; extra == 'mcp'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # sancho-observer
30
+
31
+ Analytics and observability for [MCP](https://modelcontextprotocol.io) servers written in
32
+ Python. The SDK records one event per MCP request (which tool, which agent, how long, did it
33
+ fail) and sends them in batches to a Sancho collector.
34
+
35
+ - Works with servers built on the official [`mcp`](https://pypi.org/project/mcp/) package:
36
+ `MCPServer` and the low-level `Server` (mcp 2.x), `FastMCP` and the low-level `Server`
37
+ (mcp 1.x).
38
+ - stdio and streamable HTTP transports.
39
+ - No runtime dependencies beyond the standard library. Python 3.10+.
40
+ - Never raises into your server, never writes to stdout, never blocks a request on the
41
+ network, and does nothing at all without `SANCHO_TOKEN`.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install sancho-observer
47
+ ```
48
+
49
+ ## Use
50
+
51
+ ```python
52
+ from mcp.server.mcpserver import MCPServer # mcp 1.x: from mcp.server.fastmcp import FastMCP
53
+ import sancho_observer
54
+
55
+ mcp = MCPServer("issue-tracker", version="1.4.0")
56
+ sancho_observer.instrument(mcp)
57
+
58
+
59
+ @mcp.tool()
60
+ def search_issues(query: str) -> str: ...
61
+
62
+
63
+ mcp.run() # stdio, or mcp.run("streamable-http")
64
+ ```
65
+
66
+ Then set two environment variables where the server runs:
67
+
68
+ ```bash
69
+ export SANCHO_TOKEN=sancho_... # ingest token of this MCP server
70
+ export SANCHO_ENDPOINT=https://collector.example.com # your collector's base URL
71
+ ```
72
+
73
+ `instrument()` works the same with a low-level `Server`. Call it once, before the server
74
+ starts serving. It returns the SDK `Client`; you rarely need it, but `client.flush()` and
75
+ `client.shutdown()` are there for short-lived processes (events are also flushed at exit).
76
+
77
+ ### Options
78
+
79
+ Everything can be set in code; explicit values win over environment variables.
80
+
81
+ ```python
82
+ sancho_observer.instrument(
83
+ mcp,
84
+ token="sancho_...",
85
+ endpoint="https://collector.example.com",
86
+ capture_payloads=True,
87
+ attributes={"env": "production", "region": "eu-west-1"},
88
+ )
89
+ ```
90
+
91
+ | Environment variable | Option | Default | Meaning |
92
+ |---|---|---|---|
93
+ | `SANCHO_TOKEN` | `token` | – | Ingest token. Without it the SDK is a complete no-op: no network, no threads. |
94
+ | `SANCHO_ENDPOINT` | `endpoint` | – | Collector base URL. Required; there is no built-in default. |
95
+ | `SANCHO_SERVER_NAME` | `server_name` | the server's own name | Name shown in Sancho. |
96
+ | `SANCHO_SERVER_VERSION` | `server_version` | the server's own version | Version shown in Sancho. |
97
+ | `SANCHO_CAPTURE_PAYLOADS` | `capture_payloads` | off | Also record tool arguments and results (redacted, truncated). |
98
+ | `SANCHO_DEBUG` | `debug` | off | Diagnostic logs on stderr. |
99
+ | `SANCHO_IDENTITY_SALT` | `identity_salt` | – | Secret key for hashing user/account ids (see [User and account context](#user-and-account-context)). |
100
+ | | `identify` | – | `fn(IdentifyContext) -> Identity \| None`: the user/account behind a request. |
101
+ | | `hash_identities` | `True` | `False` sends user/account ids unhashed (code only, no env variable). |
102
+ | | `attributes` | `{}` | Low-cardinality labels sent with every batch. |
103
+ | | `redact` | – | `fn(kind, value) -> value`, applied to captured payloads after the built-in redaction. |
104
+ | | `transport` | detected | Force `"stdio"`, `"streamable-http"`, `"sse"` or `"other"`. |
105
+
106
+ Batching knobs (`flush_interval`, `batch_size`, `max_queue_size`, `request_timeout`,
107
+ `max_attempts`) are available on `sancho_observer.Options` and as keyword arguments.
108
+
109
+ ### User and account context
110
+
111
+ MCP carries no user identity, so Sancho never sends one on its own: only what your resolver
112
+ returns or what you pass to `set_identity` is sent (auth info and headers are handed to the
113
+ resolver, never sent). To see which of *your*
114
+ users and customer accounts use a tool, attach a user id, an account id (tenant, workspace,
115
+ organization) and a few low-cardinality traits yourself, either with a resolver called once
116
+ per request or from inside a handler.
117
+
118
+ ```python
119
+ import sancho_observer
120
+ from sancho_observer import Identity, IdentifyContext
121
+
122
+
123
+ def identify(ctx: IdentifyContext) -> Identity | None:
124
+ # ctx: method, target, params, headers, session_id, auth_info (the mcp AccessToken when
125
+ # the server uses the mcp package's OAuth support), request_context, http_request.
126
+ if ctx.auth_info is None:
127
+ return None
128
+ claims = ctx.auth_info.claims or {}
129
+ return Identity(user_id=ctx.auth_info.subject, account_id=claims.get("org_id"), traits={"plan": "pro"})
130
+
131
+
132
+ sancho_observer.instrument(mcp, identify=identify)
133
+
134
+
135
+ @mcp.tool()
136
+ def search_issues(query: str, workspace: str) -> str:
137
+ # Attach (or override) identity for the request being handled.
138
+ sancho_observer.set_identity(account_id=workspace, traits={"plan": plan_of(workspace)})
139
+ ...
140
+ ```
141
+
142
+ - `set_identity(user_id=..., account_id=..., traits=...)` overrides the resolver field by field
143
+ (`traits` are merged, the setter wins; `None` leaves a field unchanged). It works in sync and
144
+ async tool, prompt and resource handlers on mcp 1.x and 2.x. Outside a request, or when the SDK
145
+ is disabled, it does nothing.
146
+ - The resolver runs once per observed request, and never without `SANCHO_TOKEN`. If it raises,
147
+ the event is sent without its identity (logged on stderr with `SANCHO_DEBUG`).
148
+ - **Pseudonymous by default.** `user_id` and `account_id` are trimmed and hashed in the process,
149
+ before the event is queued: the first 32 hex characters of HMAC-SHA256 with `identity_salt` /
150
+ `SANCHO_IDENTITY_SALT` as the key, or of plain SHA-256 without a salt. **Set a salt**: an
151
+ unsalted hash of an email address can be reversed by guessing. Keep the salt secret and stable
152
+ (changing it re-keys every user); use the same salt in all Sancho SDKs to get the same hashes.
153
+ `sancho_observer.hash_identity(id, salt)` computes the same value, e.g. to look a user up.
154
+ - `hash_identities=False` sends ids as given (trimmed, at most 128 bytes). Only do this for ids
155
+ that are already opaque.
156
+ - Traits are sent as-is, never hashed: keep them low-cardinality (`plan`, `region`, `tier`) and
157
+ never put personal data in them. At most 8 traits; keys up to 64 bytes, values up to 128
158
+ bytes; numbers and booleans become strings; empty keys or values and other types are dropped.
159
+
160
+ ### Low-level client
161
+
162
+ For custom integrations, send events yourself (JSON form of `McpEvent`, camelCase keys):
163
+
164
+ ```python
165
+ from sancho_observer import Client
166
+
167
+ client = Client() # reads SANCHO_TOKEN / SANCHO_ENDPOINT
168
+ client.record(
169
+ {"method": "tools/call", "target": "search_issues", "status": "CALL_STATUS_OK", "durationUs": 1530}
170
+ )
171
+ client.flush()
172
+ client.shutdown()
173
+ ```
174
+
175
+ `eventId` and `startTimeUnixNano` are filled in when missing.
176
+
177
+ ### Client capabilities
178
+
179
+ Every event records which optional features the client declared (elicitation, sampling,
180
+ roots, tasks, the MCP Apps UI extension, ...), automatically: from
181
+ `_meta["io.modelcontextprotocol/clientCapabilities"]` on each request (MCP 2026-07-28), else
182
+ from the session's `initialize` handshake. Only the keys are sent, one level deep (for example
183
+ `elicitation`, `elicitation.form`, `extensions.io.modelcontextprotocol/ui`), never their values;
184
+ `sancho_observer.capability_keys(caps)` shows what a capabilities object becomes.
185
+
186
+ ### Feedback
187
+
188
+ Latency and errors tell you whether a tool worked; feedback tells you whether its result was
189
+ useful. Report a rating for a call with `sancho_observer.feedback()`:
190
+
191
+ ```python
192
+ sancho_observer.feedback(
193
+ event_id=event_id, # or request_id=<JSON-RPC id> (optionally with session_key=...)
194
+ rating="negative", # "positive" or "negative"
195
+ reason="wrong project", # optional, max 1 KiB
196
+ attributes={"source": "thumbs"}, # optional, low-cardinality labels (max 32)
197
+ )
198
+ ```
199
+
200
+ While a request is being handled, `sancho_observer.current_event_id()` returns the id of the
201
+ event Sancho records for it (None outside an instrumented request). With an MCP App
202
+ (the `io.modelcontextprotocol/ui` extension), return it in the tool
203
+ result's `_meta` so the UI can send it back to a rating tool:
204
+
205
+ ```python
206
+ from mcp.types import CallToolResult, TextContent
207
+
208
+
209
+ @mcp.tool()
210
+ def search_issues(query: str) -> CallToolResult:
211
+ return CallToolResult(
212
+ content=[TextContent(type="text", text="...")],
213
+ _meta={"sancho/eventId": sancho_observer.current_event_id()},
214
+ )
215
+
216
+
217
+ @mcp.tool()
218
+ def rate_result(event_id: str, helpful: bool) -> str:
219
+ """Called by the UI's thumbs up / down buttons."""
220
+ sancho_observer.feedback(event_id=event_id, rating="positive" if helpful else "negative")
221
+ return "Thanks!"
222
+ ```
223
+
224
+ When the event is known to this process (the last 10,000), the feedback is linked to it and
225
+ its target (tool name) and session key are filled in; a `request_id` that matches no event, or
226
+ more than one, is sent unlinked. `feedback()` never raises and returns the feedback id, or
227
+ None when it was dropped (no `SANCHO_TOKEN`, invalid rating, ...). `Client.feedback()` takes the
228
+ same arguments. Feedback is batched and retried like events, through the collector's
229
+ `ExportFeedback` RPC; a collector too old to know it makes the SDK drop the feedback, events are
230
+ unaffected. **Do not put personal data in `reason`.**
231
+
232
+ ## Self-hosting
233
+
234
+ Run your own Sancho (see the repository's deployment docs) and point `SANCHO_ENDPOINT` at
235
+ your collector, for example `http://localhost:8081` for the repository's `docker compose` setup. The
236
+ package is the same for hosted and self-hosted collectors.
237
+
238
+ ## What is captured
239
+
240
+ Per request (one event once the response is sent):
241
+
242
+ - JSON-RPC method and target (tool name, prompt name or resource URI), JSON-RPC request id.
243
+ - Status: `OK`, `TOOL_ERROR` (`isError: true`), `PROTOCOL_ERROR` with the JSON-RPC error code,
244
+ `INPUT_REQUIRED`, `CANCELLED`; a short error message (max 1 KiB).
245
+ - Start time, duration, request and response size in bytes.
246
+ - Client name/version/title from `_meta["io.modelcontextprotocol/clientInfo"]`
247
+ (MCP 2026-07-28) or from the `initialize` handshake (2025-11-25), and the protocol version.
248
+ - The client's capability keys (see [Client capabilities](#client-capabilities)).
249
+ - Transport, W3C trace context (`_meta.traceparent` when the client sent one, otherwise new
250
+ ids), and a session key (`Mcp-Session-Id` on HTTP; on stdio, where one process serves one
251
+ client, the process instance id).
252
+
253
+ When you provide them (see [User and account context](#user-and-account-context)): a hashed user
254
+ id, a hashed account id and up to 8 traits.
255
+
256
+ Per process: SDK name/version, server name/version, a random instance id, your `attributes`,
257
+ and a snapshot of the tool/prompt/resource catalog (names, descriptions, schemas) whenever it
258
+ changes.
259
+
260
+ **Not captured unless you opt in:** tool arguments and results. With
261
+ `SANCHO_CAPTURE_PAYLOADS=true` they are recorded as JSON, with values under keys that look
262
+ sensitive (containing `password`, `secret`, `credential`, `apikey`, `cookie`, ..., or ending in
263
+ `token`, `auth`, `authorization`, `sessionid`, `signature`, ...) replaced
264
+ by `[REDACTED]`, then passed to your `redact` hook, then truncated to 64 KiB each.
265
+
266
+ ## How it behaves
267
+
268
+ - Events go into a bounded in-memory queue (10 000 by default; the oldest are dropped when it
269
+ is full). A daemon thread sends them every 2 seconds or as soon as 100 are queued, at most
270
+ 1000 per request, as Connect JSON over HTTPS.
271
+ - Transient failures (`unavailable`, `resource_exhausted`, network errors) are retried with
272
+ exponential backoff, reusing the same event ids so the collector can deduplicate; the
273
+ server's `backoffMs` / `Retry-After` hints are honoured.
274
+ - An `unauthenticated` response (bad or revoked token) stops sending for the rest of the
275
+ process and logs one line to stderr. `invalid_argument` drops that batch.
276
+ - At interpreter exit the queue is flushed for up to ~2 seconds; the thread never keeps the
277
+ process alive.
278
+
279
+ ## Development
280
+
281
+ ```bash
282
+ cd sdk/python
283
+ uv sync
284
+ uv run pytest
285
+ uv run ruff check . && uv run ruff format --check . && uv run mypy
286
+ ```
287
+
288
+ ## License
289
+
290
+ Apache-2.0