agentrail-python 0.1.0__tar.gz → 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.
Files changed (48) hide show
  1. agentrail_python-0.2.0/PKG-INFO +202 -0
  2. agentrail_python-0.2.0/README.md +167 -0
  3. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/pyproject.toml +2 -0
  4. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/__init__.py +4 -0
  5. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_client.py +46 -7
  6. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_options.py +38 -1
  7. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_privacy.py +153 -8
  8. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_processors.py +4 -1
  9. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_queue.py +88 -18
  10. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_runtime.py +76 -2
  11. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_version.py +1 -1
  12. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/asgi.py +11 -1
  13. agentrail_python-0.2.0/src/agentrail_python/mcp.py +520 -0
  14. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/wsgi.py +9 -1
  15. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/README.md +13 -2
  16. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/sdk-contract.json +1733 -84
  17. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/support.py +14 -3
  18. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_delivery.py +84 -9
  19. agentrail_python-0.2.0/tests/test_mcp.py +719 -0
  20. agentrail_python-0.2.0/tests/test_mcp_request_facts.py +267 -0
  21. agentrail_python-0.1.0/PKG-INFO +0 -625
  22. agentrail_python-0.1.0/README.md +0 -590
  23. agentrail_python-0.1.0/src/agentrail_python/mcp.py +0 -125
  24. agentrail_python-0.1.0/tests/test_mcp.py +0 -107
  25. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/.gitignore +0 -0
  26. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/LICENSE +0 -0
  27. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/integration/README.md +0 -0
  28. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_handoff.py +0 -0
  29. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_init.py +0 -0
  30. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_outbound.py +0 -0
  31. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_performance.py +0 -0
  32. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_suppression.py +0 -0
  33. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/_text.py +0 -0
  34. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/httpx.py +0 -0
  35. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/logging.py +0 -0
  36. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/py.typed +0 -0
  37. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/src/agentrail_python/requests.py +0 -0
  38. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/interoperability/contract.json +0 -0
  39. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/interoperability/generate-performance.mjs +0 -0
  40. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/interoperability/javascript.json +0 -0
  41. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/interoperability/markers.json +0 -0
  42. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/testdata/interoperability/performance.json +0 -0
  43. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_composition.py +0 -0
  44. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_evidence.py +0 -0
  45. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_incoming.py +0 -0
  46. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_interoperability.py +0 -0
  47. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_outbound.py +0 -0
  48. {agentrail_python-0.1.0 → agentrail_python-0.2.0}/tests/test_privacy.py +0 -0
@@ -0,0 +1,202 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentrail-python
3
+ Version: 0.2.0
4
+ Summary: Agentrail for Python backends: HTTP, identity, milestones, logs and MCP for agent journeys, over OpenTelemetry.
5
+ Project-URL: Homepage, https://www.agentrail.co
6
+ Project-URL: Documentation, https://www.agentrail.co/docs/guides/journeys-python
7
+ Project-URL: Repository, https://github.com/agentrail-co/agentrail-python
8
+ Project-URL: Issues, https://github.com/agentrail-co/agentrail-python/issues
9
+ Author: Agentrail
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agentrail,agents,asgi,mcp,observability,opentelemetry,wsgi
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
+ Requires-Dist: opentelemetry-api<1.46,>=1.45.1
26
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http<1.46,>=1.45.1
27
+ Requires-Dist: opentelemetry-sdk<1.46,>=1.45.1
28
+ Provides-Extra: httpx
29
+ Requires-Dist: httpx<1,>=0.28; extra == 'httpx'
30
+ Provides-Extra: mcp
31
+ Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
32
+ Provides-Extra: requests
33
+ Requires-Dist: requests<3,>=2.32; extra == 'requests'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # Agentrail for Python
37
+
38
+ [![CI](https://github.com/agentrail-co/agentrail-python/actions/workflows/ci.yml/badge.svg)](https://github.com/agentrail-co/agentrail-python/actions/workflows/ci.yml)
39
+ [![PyPI](https://img.shields.io/pypi/v/agentrail-python)](https://pypi.org/project/agentrail-python/)
40
+ [![Python](https://img.shields.io/pypi/pyversions/agentrail-python)](https://pypi.org/project/agentrail-python/)
41
+ [![Licence](https://img.shields.io/pypi/l/agentrail-python)](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE)
42
+
43
+ `agentrail-python` adds your Python servers to the journeys
44
+ [Agentrail](https://www.agentrail.co) follows: the requests they answer, the
45
+ calls they make, the identity your application verified, the milestones you
46
+ name, your logs and your MCP traffic. Bodies and raw identities never leave
47
+ your process; MCP arguments and results leave it only when you turn on
48
+ `capture_payloads`.
49
+
50
+ Works with FastAPI, Starlette, Django, Flask and any ASGI or WSGI application.
51
+ Requires **Python 3.10 or later**.
52
+
53
+ ## Install
54
+
55
+ ```sh
56
+ pip install agentrail-python
57
+ ```
58
+
59
+ Add `[httpx]`, `[requests]` or `[mcp]` for those integrations, for example
60
+ `pip install "agentrail-python[httpx,mcp]"`.
61
+
62
+ In Agentrail, open **Journeys**, select **Set up** and choose **Your servers**.
63
+ Agentrail shows the source's **Secret** and the workspace's **Hash key** once,
64
+ with your collector address. Keep both on your servers, never in a page, for
65
+ example as `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY`.
66
+
67
+ ## Quick start
68
+
69
+ ```python
70
+ import os
71
+ from contextlib import asynccontextmanager
72
+
73
+ from fastapi import Depends, FastAPI
74
+
75
+ import agentrail_python as ar
76
+ from agentrail_python.asgi import AgentrailASGIMiddleware
77
+ from my_app.auth import current_user # your own authentication
78
+
79
+ # Once, when the process starts.
80
+ agentrail = ar.init(
81
+ ar.Options(
82
+ collector=ar.CollectorOptions(
83
+ endpoint="https://<collector>/ingest/otlp",
84
+ secret=os.environ["AGENTRAIL_SECRET"],
85
+ ),
86
+ hash_key=os.environ["AGENTRAIL_HASH_KEY"],
87
+ service_name="orders-api",
88
+ )
89
+ )
90
+
91
+
92
+ @asynccontextmanager
93
+ async def lifespan(app: FastAPI):
94
+ yield
95
+ agentrail.shutdown() # sends what is still queued
96
+
97
+
98
+ app = FastAPI(lifespan=lifespan)
99
+ app.add_middleware(AgentrailASGIMiddleware, client=agentrail) # records each request
100
+
101
+
102
+ @app.post("/orders/{order_id}/confirm")
103
+ async def confirm(order_id: str, user=Depends(current_user)):
104
+ # Only after your application has authenticated the caller. Ids are hashed.
105
+ agentrail.identify(ar.VerifiedIdentity(kind="user", id=user.id))
106
+
107
+ # A business step, with a stable name.
108
+ with agentrail.start_milestone(
109
+ "checkout.confirm", ar.MilestoneContext(surface="custom", kind="checkout.confirm")
110
+ ):
111
+ ...
112
+ ```
113
+
114
+ Other frameworks wrap the application once:
115
+
116
+ ```python
117
+ application = agentrail.asgi(get_asgi_application()) # Django (ASGI), Starlette, any ASGI app
118
+ application = agentrail.wsgi(get_wsgi_application()) # Django (WSGI)
119
+ app.wsgi_app = agentrail.wsgi(app.wsgi_app) # Flask, any WSGI app
120
+ ```
121
+
122
+ ### MCP
123
+
124
+ With the official `mcp` SDK, add the middleware first. Each JSON-RPC message
125
+ your server receives becomes a step: its method, outcome and JSON-RPC error
126
+ code, message sizes, the calling client and, on stateful streamable HTTP, a
127
+ keyed hash of the session ID (the opening `initialize` included). Wrapped
128
+ tools, resources and prompts are child spans of that step. Step names carry
129
+ the tool, the prompt and the requested resource URI (without its userinfo,
130
+ query or fragment), with payload capture off too.
131
+
132
+ A wrapped tool that raises is a failed call: `MCPServer` answers the exception
133
+ with an `isError` result of its own, and the step keeps `isError` but carries
134
+ the exception's type. A result your tool returns with `isError` is a failed
135
+ result (`tool_error`).
136
+
137
+ ```python
138
+ from mcp.server.mcpserver import MCPServer
139
+ from agentrail_python.mcp import mcp_capture
140
+
141
+ capture = mcp_capture(agentrail)
142
+ server = MCPServer("orders", middleware=[capture.middleware]) # first in the list
143
+ server.tool(name="checkout")(capture.tool("checkout", checkout))
144
+
145
+ # Streamable HTTP: wrap the app so each MCP step sits under its HTTP request.
146
+ app = agentrail.asgi(server.streamable_http_app())
147
+ ```
148
+
149
+ Behind `agentrail.asgi` (or `agentrail.wsgi`), a step whose message came by
150
+ HTTP also carries that request's method, URL (its query cut to Agentrail's
151
+ markers), user agent, header names (never a value), `Accept` and
152
+ `Accept-Encoding` (each only when the request sent one), and the message's
153
+ JSON-RPC id. ASGI gives the names in the order they arrived; WSGI keeps no
154
+ order, so they are sent lower-cased and sorted. A message over stdio, or from
155
+ an in-memory client, carries none; a wrapped function that is the step carries
156
+ them when it receives the `Context`.
157
+
158
+ Arguments and results are off by default. To send them, pass a redact hook; it
159
+ gets copies of `method`, `name`, `request` and `response` and returns what to
160
+ send, or `None` to send nothing:
161
+
162
+ ```python
163
+ def redact(payload: ar.McpPayload):
164
+ request = dict(payload["request"] or {})
165
+ request.pop("arguments", None)
166
+ return {"request": request, "response": payload["response"]}
167
+
168
+
169
+ capture = mcp_capture(agentrail, capture_payloads=ar.CapturePayloads(redact=redact))
170
+ ```
171
+
172
+ When a span's two payloads together pass 14 MiB, they are cut to fit on a
173
+ character boundary, the longer first (both, when each passes half), and each
174
+ cut side is flagged. A multi-round-trip `requestState` is never sent. A request the MCP SDK refuses before its
175
+ middleware runs (a malformed body, a wrong header, an unknown session) is no
176
+ MCP step; behind `agentrail.asgi` it is still recorded as its HTTP request.
177
+
178
+ Agentrail never fails your request: anything it could not capture or send goes
179
+ to your `on_error` callback.
180
+
181
+ ## Documentation
182
+
183
+ | | |
184
+ | --- | --- |
185
+ | [Install the Python SDK](https://www.agentrail.co/docs/guides/journeys-python) | Setup for each framework, outgoing calls, identity, milestones, logs, MCP and location |
186
+ | [Python SDK reference](https://www.agentrail.co/docs/guides/journeys-python-reference) | Every option, an existing OpenTelemetry setup, delivery and error codes, framework notes |
187
+ | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) | Skip calls between your own services |
188
+ | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) | Report workflow attempts and plugin calls on milestones |
189
+ | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) | What is sent, what is hashed, and what never leaves your process |
190
+
191
+ The same SDK is available for [Node](https://github.com/agentrail-co/agentrail-js/tree/main/packages/node)
192
+ (`agentrail-node`) and [Go](https://github.com/agentrail-co/agentrail-go) (`agentrail-go`).
193
+
194
+ ## Contributing
195
+
196
+ Issues and pull requests are welcome. See
197
+ [CONTRIBUTING.md](https://github.com/agentrail-co/agentrail-python/blob/main/CONTRIBUTING.md)
198
+ for development and releasing.
199
+
200
+ ## Licence
201
+
202
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE).
@@ -0,0 +1,167 @@
1
+ # Agentrail for Python
2
+
3
+ [![CI](https://github.com/agentrail-co/agentrail-python/actions/workflows/ci.yml/badge.svg)](https://github.com/agentrail-co/agentrail-python/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/agentrail-python)](https://pypi.org/project/agentrail-python/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/agentrail-python)](https://pypi.org/project/agentrail-python/)
6
+ [![Licence](https://img.shields.io/pypi/l/agentrail-python)](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE)
7
+
8
+ `agentrail-python` adds your Python servers to the journeys
9
+ [Agentrail](https://www.agentrail.co) follows: the requests they answer, the
10
+ calls they make, the identity your application verified, the milestones you
11
+ name, your logs and your MCP traffic. Bodies and raw identities never leave
12
+ your process; MCP arguments and results leave it only when you turn on
13
+ `capture_payloads`.
14
+
15
+ Works with FastAPI, Starlette, Django, Flask and any ASGI or WSGI application.
16
+ Requires **Python 3.10 or later**.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ pip install agentrail-python
22
+ ```
23
+
24
+ Add `[httpx]`, `[requests]` or `[mcp]` for those integrations, for example
25
+ `pip install "agentrail-python[httpx,mcp]"`.
26
+
27
+ In Agentrail, open **Journeys**, select **Set up** and choose **Your servers**.
28
+ Agentrail shows the source's **Secret** and the workspace's **Hash key** once,
29
+ with your collector address. Keep both on your servers, never in a page, for
30
+ example as `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY`.
31
+
32
+ ## Quick start
33
+
34
+ ```python
35
+ import os
36
+ from contextlib import asynccontextmanager
37
+
38
+ from fastapi import Depends, FastAPI
39
+
40
+ import agentrail_python as ar
41
+ from agentrail_python.asgi import AgentrailASGIMiddleware
42
+ from my_app.auth import current_user # your own authentication
43
+
44
+ # Once, when the process starts.
45
+ agentrail = ar.init(
46
+ ar.Options(
47
+ collector=ar.CollectorOptions(
48
+ endpoint="https://<collector>/ingest/otlp",
49
+ secret=os.environ["AGENTRAIL_SECRET"],
50
+ ),
51
+ hash_key=os.environ["AGENTRAIL_HASH_KEY"],
52
+ service_name="orders-api",
53
+ )
54
+ )
55
+
56
+
57
+ @asynccontextmanager
58
+ async def lifespan(app: FastAPI):
59
+ yield
60
+ agentrail.shutdown() # sends what is still queued
61
+
62
+
63
+ app = FastAPI(lifespan=lifespan)
64
+ app.add_middleware(AgentrailASGIMiddleware, client=agentrail) # records each request
65
+
66
+
67
+ @app.post("/orders/{order_id}/confirm")
68
+ async def confirm(order_id: str, user=Depends(current_user)):
69
+ # Only after your application has authenticated the caller. Ids are hashed.
70
+ agentrail.identify(ar.VerifiedIdentity(kind="user", id=user.id))
71
+
72
+ # A business step, with a stable name.
73
+ with agentrail.start_milestone(
74
+ "checkout.confirm", ar.MilestoneContext(surface="custom", kind="checkout.confirm")
75
+ ):
76
+ ...
77
+ ```
78
+
79
+ Other frameworks wrap the application once:
80
+
81
+ ```python
82
+ application = agentrail.asgi(get_asgi_application()) # Django (ASGI), Starlette, any ASGI app
83
+ application = agentrail.wsgi(get_wsgi_application()) # Django (WSGI)
84
+ app.wsgi_app = agentrail.wsgi(app.wsgi_app) # Flask, any WSGI app
85
+ ```
86
+
87
+ ### MCP
88
+
89
+ With the official `mcp` SDK, add the middleware first. Each JSON-RPC message
90
+ your server receives becomes a step: its method, outcome and JSON-RPC error
91
+ code, message sizes, the calling client and, on stateful streamable HTTP, a
92
+ keyed hash of the session ID (the opening `initialize` included). Wrapped
93
+ tools, resources and prompts are child spans of that step. Step names carry
94
+ the tool, the prompt and the requested resource URI (without its userinfo,
95
+ query or fragment), with payload capture off too.
96
+
97
+ A wrapped tool that raises is a failed call: `MCPServer` answers the exception
98
+ with an `isError` result of its own, and the step keeps `isError` but carries
99
+ the exception's type. A result your tool returns with `isError` is a failed
100
+ result (`tool_error`).
101
+
102
+ ```python
103
+ from mcp.server.mcpserver import MCPServer
104
+ from agentrail_python.mcp import mcp_capture
105
+
106
+ capture = mcp_capture(agentrail)
107
+ server = MCPServer("orders", middleware=[capture.middleware]) # first in the list
108
+ server.tool(name="checkout")(capture.tool("checkout", checkout))
109
+
110
+ # Streamable HTTP: wrap the app so each MCP step sits under its HTTP request.
111
+ app = agentrail.asgi(server.streamable_http_app())
112
+ ```
113
+
114
+ Behind `agentrail.asgi` (or `agentrail.wsgi`), a step whose message came by
115
+ HTTP also carries that request's method, URL (its query cut to Agentrail's
116
+ markers), user agent, header names (never a value), `Accept` and
117
+ `Accept-Encoding` (each only when the request sent one), and the message's
118
+ JSON-RPC id. ASGI gives the names in the order they arrived; WSGI keeps no
119
+ order, so they are sent lower-cased and sorted. A message over stdio, or from
120
+ an in-memory client, carries none; a wrapped function that is the step carries
121
+ them when it receives the `Context`.
122
+
123
+ Arguments and results are off by default. To send them, pass a redact hook; it
124
+ gets copies of `method`, `name`, `request` and `response` and returns what to
125
+ send, or `None` to send nothing:
126
+
127
+ ```python
128
+ def redact(payload: ar.McpPayload):
129
+ request = dict(payload["request"] or {})
130
+ request.pop("arguments", None)
131
+ return {"request": request, "response": payload["response"]}
132
+
133
+
134
+ capture = mcp_capture(agentrail, capture_payloads=ar.CapturePayloads(redact=redact))
135
+ ```
136
+
137
+ When a span's two payloads together pass 14 MiB, they are cut to fit on a
138
+ character boundary, the longer first (both, when each passes half), and each
139
+ cut side is flagged. A multi-round-trip `requestState` is never sent. A request the MCP SDK refuses before its
140
+ middleware runs (a malformed body, a wrong header, an unknown session) is no
141
+ MCP step; behind `agentrail.asgi` it is still recorded as its HTTP request.
142
+
143
+ Agentrail never fails your request: anything it could not capture or send goes
144
+ to your `on_error` callback.
145
+
146
+ ## Documentation
147
+
148
+ | | |
149
+ | --- | --- |
150
+ | [Install the Python SDK](https://www.agentrail.co/docs/guides/journeys-python) | Setup for each framework, outgoing calls, identity, milestones, logs, MCP and location |
151
+ | [Python SDK reference](https://www.agentrail.co/docs/guides/journeys-python-reference) | Every option, an existing OpenTelemetry setup, delivery and error codes, framework notes |
152
+ | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) | Skip calls between your own services |
153
+ | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) | Report workflow attempts and plugin calls on milestones |
154
+ | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) | What is sent, what is hashed, and what never leaves your process |
155
+
156
+ The same SDK is available for [Node](https://github.com/agentrail-co/agentrail-js/tree/main/packages/node)
157
+ (`agentrail-node`) and [Go](https://github.com/agentrail-co/agentrail-go) (`agentrail-go`).
158
+
159
+ ## Contributing
160
+
161
+ Issues and pull requests are welcome. See
162
+ [CONTRIBUTING.md](https://github.com/agentrail-co/agentrail-python/blob/main/CONTRIBUTING.md)
163
+ for development and releasing.
164
+
165
+ ## Licence
166
+
167
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE).
@@ -55,6 +55,8 @@ dev = [
55
55
  "flask>=3.1",
56
56
  "mcp>=2.3",
57
57
  "uvicorn>=0.38",
58
+ "a2wsgi>=1.10",
59
+ "trustme>=1.2",
58
60
  ]
59
61
 
60
62
  [tool.hatch.version]
@@ -11,6 +11,7 @@ from ._options import (
11
11
  AuthorizedOperation,
12
12
  CaptureCode,
13
13
  CaptureError,
14
+ CapturePayloads,
14
15
  CollectorOptions,
15
16
  ConfigurationError,
16
17
  IncomingRequest,
@@ -18,6 +19,7 @@ from ._options import (
18
19
  LocationSource,
19
20
  LogsOptions,
20
21
  McpContext,
22
+ McpPayload,
21
23
  MilestoneContext,
22
24
  Options,
23
25
  PerformanceContext,
@@ -38,6 +40,7 @@ __all__ = [
38
40
  "AuthorizedOperation",
39
41
  "CaptureCode",
40
42
  "CaptureError",
43
+ "CapturePayloads",
41
44
  "Client",
42
45
  "CollectorOptions",
43
46
  "ConfigurationError",
@@ -47,6 +50,7 @@ __all__ = [
47
50
  "LocationSource",
48
51
  "LogsOptions",
49
52
  "McpContext",
53
+ "McpPayload",
50
54
  "MilestoneContext",
51
55
  "MilestoneScope",
52
56
  "Options",
@@ -17,20 +17,22 @@ from opentelemetry import context as otel_context
17
17
  from opentelemetry import trace
18
18
  from opentelemetry.trace import Link, NonRecordingSpan, Span, SpanContext, SpanKind, StatusCode, TraceFlags
19
19
 
20
- from ._handoff import HANDOFF_HEADER, Refused, parse_traceparent, verify
20
+ from ._handoff import HANDOFF_HEADER, Refused, keyed_hash, parse_traceparent, verify
21
21
  from ._options import (
22
22
  LOCATION_SOURCES,
23
23
  PRINCIPAL_KINDS,
24
24
  SURFACES,
25
+ CaptureCode,
25
26
  ConfigurationError,
26
27
  IncomingRequest,
27
28
  MilestoneContext,
29
+ Signal,
28
30
  VerifiedIdentity,
29
31
  )
30
32
  from ._performance import performance_attributes
31
33
  from ._privacy import StructuredLog, clean_context, copy_log
32
34
  from ._queue import ExportQueue, QueueStats
33
- from ._runtime import Attributes, Mark, RequestState, Runtime
35
+ from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime
34
36
  from ._suppression import suppressed
35
37
  from ._text import bounded, valid_text
36
38
  from ._version import VERSION
@@ -62,16 +64,28 @@ class MilestoneScope:
62
64
  The block's exception is recorded and re-raised unchanged.
63
65
  """
64
66
 
65
- def __init__(self, client: Client, name: str, details: MilestoneContext) -> None:
67
+ def __init__(
68
+ self,
69
+ client: Client,
70
+ name: str,
71
+ details: MilestoneContext,
72
+ *,
73
+ step: bool = True,
74
+ mcp: McpEvidence | None = None,
75
+ ) -> None:
66
76
  client._validate_milestone(name, details) # pyright: ignore[reportPrivateUsage]
67
77
  self._client = client
68
78
  self._name = name
69
79
  self._details = details
80
+ self._step = step
81
+ self._mcp = mcp
70
82
  self._span: Span | None = None
71
83
  self._token: object | None = None
72
84
 
73
85
  def __enter__(self) -> MilestoneScope:
74
- span, ctx = self._client._start(self._name, self._details) # pyright: ignore[reportPrivateUsage]
86
+ span, ctx = self._client._start( # pyright: ignore[reportPrivateUsage]
87
+ self._name, self._details, step=self._step, mcp=self._mcp
88
+ )
75
89
  self._span = span
76
90
  self._token = otel_context.attach(ctx)
77
91
  return self
@@ -200,7 +214,13 @@ class Client:
200
214
  raise ConfigurationError("Milestone name and kind must contain 1-256 characters, with a known surface.")
201
215
 
202
216
  def _start(
203
- self, name: str, details: MilestoneContext, identity: Attributes | None = None
217
+ self,
218
+ name: str,
219
+ details: MilestoneContext,
220
+ identity: Attributes | None = None,
221
+ *,
222
+ step: bool = True,
223
+ mcp: McpEvidence | None = None,
204
224
  ) -> tuple[Span, otel_context.Context]:
205
225
  performance = None
206
226
  if details.performance is not None:
@@ -210,16 +230,24 @@ class Client:
210
230
  self._runtime.report("invalid_performance", "context")
211
231
  base = otel_context.get_current()
212
232
  state = self._runtime.state(base)
233
+ continued: list[Link] = []
234
+ if state is not None and state.entry is not None:
235
+ current = trace.get_current_span(base).get_span_context()
236
+ if current.is_valid and (current.is_remote or current.trace_id != state.entry.trace_id):
237
+ # A trace continued from unsigned input inside the request (the MCP
238
+ # SDK continues a client's _meta traceparent) is a link, never the parent.
239
+ continued.append(Link(clean_context(current)))
240
+ base = trace.set_span_in_context(NonRecordingSpan(state.entry), base)
213
241
  if state is None:
214
242
  external = trace.get_current_span(base).get_span_context()
215
243
  links = [Link(clean_context(external))] if external.is_valid else []
216
244
  state = RequestState(links=links)
217
245
  # Its own managed scope: an unrelated caller's trace is a link, never the parent.
218
246
  base = otel_context.set_value(self._runtime.state_key, state, otel_context.Context())
219
- mark = Mark(name=name, details=details, performance=performance, identity=identity)
247
+ mark = Mark(name=name, details=details, performance=performance, identity=identity, step=step, mcp=mcp)
220
248
  marked = otel_context.set_value(self._runtime.mark_key, mark, base)
221
249
  parented = trace.get_current_span(base).get_span_context().is_valid
222
- span = self._tracer.start_span(name, context=marked, links=[] if parented else state.links)
250
+ span = self._tracer.start_span(name, context=marked, links=continued + ([] if parented else state.links))
223
251
  if not span.is_recording():
224
252
  self._runtime.report("entry_not_recording", "traces")
225
253
  return span, trace.set_span_in_context(span, base)
@@ -278,6 +306,16 @@ class Client:
278
306
 
279
307
  return AgentrailWSGIMiddleware(app, client=self)
280
308
 
309
+ def _keyed_hash(self, value: str) -> str:
310
+ """The keyed hash principal IDs use: 32 lowercase hex under the workspace key."""
311
+ return keyed_hash(self._runtime.options.input.hash_key, value)
312
+
313
+ def _payload_room(self) -> bool:
314
+ return self._spans.payload_room()
315
+
316
+ def _report(self, code: CaptureCode, signal: Signal) -> None:
317
+ self._runtime.report(code, signal)
318
+
281
319
  def _managed(self) -> bool:
282
320
  return not self._closed and not suppressed() and self._runtime.state() is not None
283
321
 
@@ -318,6 +356,7 @@ class Client:
318
356
  span = self._tracer.start_span(
319
357
  f"HTTP {request.method}", context=ctx, kind=SpanKind.SERVER, attributes=attributes
320
358
  )
359
+ state.entry = span.get_span_context()
321
360
  if not span.is_recording():
322
361
  self._runtime.report("entry_not_recording", "traces")
323
362
  return span, trace.set_span_in_context(span, ctx)
@@ -8,7 +8,7 @@ import sys
8
8
  import uuid
9
9
  from collections.abc import Callable, Mapping, Sequence
10
10
  from dataclasses import dataclass, field
11
- from typing import TYPE_CHECKING, Literal
11
+ from typing import TYPE_CHECKING, Any, Literal, TypedDict
12
12
  from urllib.parse import SplitResult, urlsplit
13
13
 
14
14
  from ._text import valid_text, well_formed
@@ -36,6 +36,8 @@ CaptureCode = Literal[
36
36
  "ignore_failed",
37
37
  "identity_outside_request",
38
38
  "invalid_performance",
39
+ "payload_redact_failed",
40
+ "payload_budget",
39
41
  ]
40
42
  Signal = Literal["traces", "logs", "context"]
41
43
 
@@ -143,6 +145,41 @@ class McpContext:
143
145
  client: str | None = None
144
146
  client_version: str | None = None
145
147
  protocol: str | None = None
148
+ # The tool, resource or prompt's registered name, never a value from its arguments.
149
+ name: str | None = None
150
+
151
+
152
+ class McpPayload(TypedDict):
153
+ """What a redact hook sees of one MCP message: copies, never the live objects.
154
+
155
+ ``name`` is the tool, the resource URI (without userinfo, query or
156
+ fragment) or the prompt, else ``None``. ``request`` is the message's
157
+ params; ``response`` is the result or the JSON-RPC error the server
158
+ answers with (``code``, ``message``, ``data``), and ``None`` only for a
159
+ notification or a request ended without an answer (a cancellation). A
160
+ multi-round-trip ``requestState`` is removed from both.
161
+ """
162
+
163
+ method: str
164
+ name: str | None
165
+ request: Any
166
+ response: Any
167
+
168
+
169
+ @dataclass(frozen=True, kw_only=True)
170
+ class CapturePayloads:
171
+ """Opt in to sending MCP request and response content.
172
+
173
+ ``redact`` runs in the request, after the handler returns and before the
174
+ answer is written, on JSON copies.
175
+ Return the mapping to send (its ``request`` and ``response`` are encoded
176
+ as JSON text; a missing or ``None`` side is not sent), or ``None`` to send
177
+ neither. A hook that raises sends nothing for that message and is
178
+ reported as ``payload_redact_failed``, as is one whose result is not JSON;
179
+ the MCP call is unaffected.
180
+ """
181
+
182
+ redact: Callable[[McpPayload], Mapping[str, Any] | None]
146
183
 
147
184
 
148
185
  @dataclass(frozen=True, kw_only=True)