agentrail-python 0.1.0__tar.gz → 0.3.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 (52) hide show
  1. agentrail_python-0.3.0/PKG-INFO +209 -0
  2. agentrail_python-0.3.0/README.md +173 -0
  3. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/pyproject.toml +4 -0
  4. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/__init__.py +4 -0
  5. agentrail_python-0.3.0/src/agentrail_python/_cli.py +173 -0
  6. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_client.py +48 -7
  7. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_handoff.py +4 -0
  8. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_options.py +38 -1
  9. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_privacy.py +158 -8
  10. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_processors.py +4 -1
  11. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_queue.py +88 -18
  12. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_runtime.py +78 -2
  13. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_version.py +1 -1
  14. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/asgi.py +11 -1
  15. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/httpx.py +2 -2
  16. agentrail_python-0.3.0/src/agentrail_python/mcp.py +520 -0
  17. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/requests.py +2 -2
  18. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/wsgi.py +9 -1
  19. agentrail_python-0.3.0/testdata/README.md +32 -0
  20. agentrail_python-0.3.0/testdata/sdk-contract.json +5106 -0
  21. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/support.py +14 -3
  22. agentrail_python-0.3.0/tests/test_cli.py +130 -0
  23. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_delivery.py +84 -9
  24. agentrail_python-0.3.0/tests/test_mcp.py +719 -0
  25. agentrail_python-0.3.0/tests/test_mcp_request_facts.py +267 -0
  26. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_outbound.py +20 -0
  27. agentrail_python-0.1.0/PKG-INFO +0 -625
  28. agentrail_python-0.1.0/README.md +0 -590
  29. agentrail_python-0.1.0/src/agentrail_python/mcp.py +0 -125
  30. agentrail_python-0.1.0/testdata/README.md +0 -19
  31. agentrail_python-0.1.0/testdata/sdk-contract.json +0 -2751
  32. agentrail_python-0.1.0/tests/test_mcp.py +0 -107
  33. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/.gitignore +0 -0
  34. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/LICENSE +0 -0
  35. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/integration/README.md +0 -0
  36. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_init.py +0 -0
  37. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_outbound.py +0 -0
  38. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_performance.py +0 -0
  39. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_suppression.py +0 -0
  40. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/_text.py +0 -0
  41. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/logging.py +0 -0
  42. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/src/agentrail_python/py.typed +0 -0
  43. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/testdata/interoperability/contract.json +0 -0
  44. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/testdata/interoperability/generate-performance.mjs +0 -0
  45. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/testdata/interoperability/javascript.json +0 -0
  46. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/testdata/interoperability/markers.json +0 -0
  47. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/testdata/interoperability/performance.json +0 -0
  48. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_composition.py +0 -0
  49. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_evidence.py +0 -0
  50. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_incoming.py +0 -0
  51. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_interoperability.py +0 -0
  52. {agentrail_python-0.1.0 → agentrail_python-0.3.0}/tests/test_privacy.py +0 -0
@@ -0,0 +1,209 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentrail-python
3
+ Version: 0.3.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: http-sf<2,>=1.5.0
26
+ Requires-Dist: opentelemetry-api<1.46,>=1.45.1
27
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http<1.46,>=1.45.1
28
+ Requires-Dist: opentelemetry-sdk<1.46,>=1.45.1
29
+ Provides-Extra: httpx
30
+ Requires-Dist: httpx<1,>=0.28; extra == 'httpx'
31
+ Provides-Extra: mcp
32
+ Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
33
+ Provides-Extra: requests
34
+ Requires-Dist: requests<3,>=2.32; extra == 'requests'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Agentrail for Python
38
+
39
+ [![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)
40
+ [![PyPI](https://img.shields.io/pypi/v/agentrail-python)](https://pypi.org/project/agentrail-python/)
41
+ [![Python](https://img.shields.io/pypi/pyversions/agentrail-python)](https://pypi.org/project/agentrail-python/)
42
+ [![Licence](https://img.shields.io/pypi/l/agentrail-python)](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE)
43
+
44
+ `agentrail-python` adds your Python servers to the journeys
45
+ [Agentrail](https://www.agentrail.co) follows: the requests they answer, the
46
+ calls they make, the identity your application verified, the milestones you
47
+ name, your logs and your MCP traffic. Bodies and raw identities never leave
48
+ your process; MCP arguments and results leave it only when you turn on
49
+ `capture_payloads`.
50
+
51
+ Works with FastAPI, Starlette, Django, Flask and any ASGI or WSGI application.
52
+ Requires **Python 3.10 or later**.
53
+
54
+ ## Install
55
+
56
+ ```sh
57
+ pip install agentrail-python
58
+ ```
59
+
60
+ Add `[httpx]`, `[requests]` or `[mcp]` for those integrations, for example
61
+ `pip install "agentrail-python[httpx,mcp]"`.
62
+
63
+ In Agentrail, open **Journeys**, select **Set up** and choose **Your servers**.
64
+ Agentrail shows the source's **Secret** and the workspace's **Hash key** once,
65
+ with your collector address. Keep both on your servers, never in a page, for
66
+ example as `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY`.
67
+
68
+ ## Quick start
69
+
70
+ ```python
71
+ import os
72
+ from contextlib import asynccontextmanager
73
+
74
+ from fastapi import Depends, FastAPI
75
+
76
+ import agentrail_python as ar
77
+ from agentrail_python.asgi import AgentrailASGIMiddleware
78
+ from my_app.auth import current_user # your own authentication
79
+
80
+ # Once, when the process starts.
81
+ agentrail = ar.init(
82
+ ar.Options(
83
+ collector=ar.CollectorOptions(
84
+ endpoint="https://<collector>/ingest/otlp",
85
+ secret=os.environ["AGENTRAIL_SECRET"],
86
+ ),
87
+ hash_key=os.environ["AGENTRAIL_HASH_KEY"],
88
+ service_name="orders-api",
89
+ )
90
+ )
91
+
92
+
93
+ @asynccontextmanager
94
+ async def lifespan(app: FastAPI):
95
+ yield
96
+ agentrail.shutdown() # sends what is still queued
97
+
98
+
99
+ app = FastAPI(lifespan=lifespan)
100
+ app.add_middleware(AgentrailASGIMiddleware, client=agentrail) # records each request
101
+
102
+
103
+ @app.post("/orders/{order_id}/confirm")
104
+ async def confirm(order_id: str, user=Depends(current_user)):
105
+ # Only after your application has authenticated the caller. Ids are hashed.
106
+ agentrail.identify(ar.VerifiedIdentity(kind="user", id=user.id))
107
+
108
+ # A business step, with a stable name.
109
+ with agentrail.start_milestone(
110
+ "checkout.confirm", ar.MilestoneContext(surface="custom", kind="checkout.confirm")
111
+ ):
112
+ ...
113
+ ```
114
+
115
+ Other frameworks wrap the application once:
116
+
117
+ ```python
118
+ application = agentrail.asgi(get_asgi_application()) # Django (ASGI), Starlette, any ASGI app
119
+ application = agentrail.wsgi(get_wsgi_application()) # Django (WSGI)
120
+ app.wsgi_app = agentrail.wsgi(app.wsgi_app) # Flask, any WSGI app
121
+ ```
122
+
123
+ ### MCP
124
+
125
+ With the official `mcp` SDK, add the middleware first. Each JSON-RPC message
126
+ your server receives becomes a step: its method, outcome and JSON-RPC error
127
+ code, message sizes, the calling client and, on stateful streamable HTTP, a
128
+ keyed hash of the session ID (the opening `initialize` included). Wrapped
129
+ tools, resources and prompts are child spans of that step. Step names carry
130
+ the tool, the prompt and the requested resource URI (without its userinfo,
131
+ query or fragment), with payload capture off too.
132
+
133
+ A wrapped tool that raises is a failed call: `MCPServer` answers the exception
134
+ with an `isError` result of its own, and the step keeps `isError` but carries
135
+ the exception's type. A result your tool returns with `isError` is a failed
136
+ result (`tool_error`).
137
+
138
+ ```python
139
+ from mcp.server.mcpserver import MCPServer
140
+ from agentrail_python.mcp import mcp_capture
141
+
142
+ capture = mcp_capture(agentrail)
143
+ server = MCPServer("orders", middleware=[capture.middleware]) # first in the list
144
+ server.tool(name="checkout")(capture.tool("checkout", checkout))
145
+
146
+ # Streamable HTTP: wrap the app so each MCP step sits under its HTTP request.
147
+ app = agentrail.asgi(server.streamable_http_app())
148
+ ```
149
+
150
+ Behind `agentrail.asgi` (or `agentrail.wsgi`), a step whose message came by
151
+ HTTP also carries that request's method, URL (its query cut to Agentrail's
152
+ markers), user agent, header names (never a value), `Accept` and
153
+ `Accept-Encoding` (each only when the request sent one), and the message's
154
+ JSON-RPC id. ASGI gives the names in the order they arrived; WSGI keeps no
155
+ order, so they are sent lower-cased and sorted. A message over stdio, or from
156
+ an in-memory client, carries none; a wrapped function that is the step carries
157
+ them when it receives the `Context`.
158
+
159
+ Arguments and results are off by default. To send them, pass a redact hook; it
160
+ gets copies of `method`, `name`, `request` and `response` and returns what to
161
+ send, or `None` to send nothing:
162
+
163
+ ```python
164
+ def redact(payload: ar.McpPayload):
165
+ request = dict(payload["request"] or {})
166
+ request.pop("arguments", None)
167
+ return {"request": request, "response": payload["response"]}
168
+
169
+
170
+ capture = mcp_capture(agentrail, capture_payloads=ar.CapturePayloads(redact=redact))
171
+ ```
172
+
173
+ When a span's two payloads together pass 14 MiB, they are cut to fit on a
174
+ character boundary, the longer first (both, when each passes half), and each
175
+ cut side is flagged. A multi-round-trip `requestState` is never sent. A request the MCP SDK refuses before its
176
+ middleware runs (a malformed body, a wrong header, an unknown session) is no
177
+ MCP step; behind `agentrail.asgi` it is still recorded as its HTTP request.
178
+
179
+ When a customer's CLI uses [`agentrail-cli-sdk`](https://www.npmjs.com/package/agentrail-cli-sdk),
180
+ its requests say which command an agent ran, in which run and session. The
181
+ ASGI and WSGI middleware record that on the request's span, the session only as
182
+ a keyed hash, so the agent's CLI runs join its journey. There is nothing to
183
+ configure.
184
+
185
+ Agentrail never fails your request: anything it could not capture or send goes
186
+ to your `on_error` callback.
187
+
188
+ ## Documentation
189
+
190
+ | | |
191
+ | --- | --- |
192
+ | [Install the Python SDK](https://www.agentrail.co/docs/guides/journeys-python) | Setup for each framework, outgoing calls, identity, milestones, logs, MCP and location |
193
+ | [Python SDK reference](https://www.agentrail.co/docs/guides/journeys-python-reference) | Every option, an existing OpenTelemetry setup, delivery and error codes, framework notes |
194
+ | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) | Skip calls between your own services |
195
+ | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) | Report workflow attempts and plugin calls on milestones |
196
+ | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) | What is sent, what is hashed, and what never leaves your process |
197
+
198
+ The same SDK is available for [Node](https://github.com/agentrail-co/agentrail-js/tree/main/packages/node)
199
+ (`agentrail-node`) and [Go](https://github.com/agentrail-co/agentrail-go) (`agentrail-go`).
200
+
201
+ ## Contributing
202
+
203
+ Issues and pull requests are welcome. See
204
+ [CONTRIBUTING.md](https://github.com/agentrail-co/agentrail-python/blob/main/CONTRIBUTING.md)
205
+ for development and releasing.
206
+
207
+ ## Licence
208
+
209
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE).
@@ -0,0 +1,173 @@
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
+ When a customer's CLI uses [`agentrail-cli-sdk`](https://www.npmjs.com/package/agentrail-cli-sdk),
144
+ its requests say which command an agent ran, in which run and session. The
145
+ ASGI and WSGI middleware record that on the request's span, the session only as
146
+ a keyed hash, so the agent's CLI runs join its journey. There is nothing to
147
+ configure.
148
+
149
+ Agentrail never fails your request: anything it could not capture or send goes
150
+ to your `on_error` callback.
151
+
152
+ ## Documentation
153
+
154
+ | | |
155
+ | --- | --- |
156
+ | [Install the Python SDK](https://www.agentrail.co/docs/guides/journeys-python) | Setup for each framework, outgoing calls, identity, milestones, logs, MCP and location |
157
+ | [Python SDK reference](https://www.agentrail.co/docs/guides/journeys-python-reference) | Every option, an existing OpenTelemetry setup, delivery and error codes, framework notes |
158
+ | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) | Skip calls between your own services |
159
+ | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) | Report workflow attempts and plugin calls on milestones |
160
+ | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) | What is sent, what is hashed, and what never leaves your process |
161
+
162
+ The same SDK is available for [Node](https://github.com/agentrail-co/agentrail-js/tree/main/packages/node)
163
+ (`agentrail-node`) and [Go](https://github.com/agentrail-co/agentrail-go) (`agentrail-go`).
164
+
165
+ ## Contributing
166
+
167
+ Issues and pull requests are welcome. See
168
+ [CONTRIBUTING.md](https://github.com/agentrail-co/agentrail-python/blob/main/CONTRIBUTING.md)
169
+ for development and releasing.
170
+
171
+ ## Licence
172
+
173
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-python/blob/main/LICENSE).
@@ -30,6 +30,8 @@ dependencies = [
30
30
  "opentelemetry-api>=1.45.1,<1.46",
31
31
  "opentelemetry-sdk>=1.45.1,<1.46",
32
32
  "opentelemetry-exporter-otlp-proto-http>=1.45.1,<1.46",
33
+ # RFC 9651 Structured Fields, for the x-agentrail-cli header a customer's CLI sends.
34
+ "http-sf>=1.5.0,<2",
33
35
  ]
34
36
 
35
37
  [project.optional-dependencies]
@@ -55,6 +57,8 @@ dev = [
55
57
  "flask>=3.1",
56
58
  "mcp>=2.3",
57
59
  "uvicorn>=0.38",
60
+ "a2wsgi>=1.10",
61
+ "trustme>=1.2",
58
62
  ]
59
63
 
60
64
  [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",
@@ -0,0 +1,173 @@
1
+ # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
+ """The header a customer's CLI sends its own API, as a server reads it.
3
+
4
+ ``agentrail-cli-sdk`` writes ``x-agentrail-cli``, an RFC 9651 Dictionary naming
5
+ the command an agent ran, the run, the session and the agent. This reads it as
6
+ agentrail-core's ``readCliHeader`` and agentrail-go do (the contract's
7
+ ``cliHeader``), and turns it into the span attributes the collector reads
8
+ (``otlp.cliAttributes``), the session only as its keyed hash.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass
16
+
17
+ import http_sf
18
+
19
+ from ._runtime import Attributes
20
+
21
+ CLI_HEADER = "x-agentrail-cli" # also in ``_handoff.STRIPPED_HEADERS``
22
+
23
+ _TEXT = re.compile(r"[\x20-\x7e]{1,64}")
24
+ _COMMAND = re.compile(r"[\x20-\x7e]{1,128}")
25
+ _RUN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
26
+ _SESSION = re.compile(r"[0-9a-f]{32}")
27
+ _AGENT = re.compile(r"[a-z0-9._-]{1,64}")
28
+ _VARIABLE = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}")
29
+ _SESSION_SOURCES = ("agent", "ci", "local", "run")
30
+ _MODES = ("agent", "ci", "interactive", "non-interactive")
31
+ # The largest Integer RFC 9651 holds, and the most evidence a header names.
32
+ _MAX_INTEGER = 999_999_999_999_999
33
+ _MAX_EVIDENCE = 8
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class CliHeader:
38
+ sdk_version: str
39
+ cli: str
40
+ run: str
41
+ sequence: int
42
+ session: str
43
+ session_from: str
44
+ mode: str
45
+ cli_version: str | None = None
46
+ agent: str | None = None
47
+ agent_version: str | None = None
48
+ evidence: tuple[str, ...] | None = None
49
+ command: str | None = None
50
+
51
+
52
+ class _Unread(Exception):
53
+ """A header no CLI SDK writes: it reads as nothing."""
54
+
55
+
56
+ def _item(members: Mapping[str, object], key: str) -> object:
57
+ member = members.get(key)
58
+ if not isinstance(member, tuple) or len(member) != 2: # pyright: ignore[reportUnknownArgumentType]
59
+ raise _Unread(key)
60
+ return member[0] # pyright: ignore[reportUnknownVariableType]
61
+
62
+
63
+ def _string(members: Mapping[str, object], key: str, pattern: re.Pattern[str]) -> str:
64
+ value = _item(members, key)
65
+ # A Token or a Display String is no String, though each holds text.
66
+ if type(value) is not str or pattern.fullmatch(value) is None:
67
+ raise _Unread(key)
68
+ return value
69
+
70
+
71
+ def _optional(members: Mapping[str, object], key: str, pattern: re.Pattern[str]) -> str | None:
72
+ return _string(members, key, pattern) if key in members else None
73
+
74
+
75
+ def _token(members: Mapping[str, object], key: str, allowed: tuple[str, ...]) -> str:
76
+ value = _item(members, key)
77
+ if not isinstance(value, http_sf.Token) or str(value) not in allowed:
78
+ raise _Unread(key)
79
+ return str(value)
80
+
81
+
82
+ def _integer(members: Mapping[str, object], key: str, low: int, high: int) -> int:
83
+ value = _item(members, key)
84
+ # bool is an int in Python; a Boolean is no Integer.
85
+ if type(value) is not int or not low <= value <= high:
86
+ raise _Unread(key)
87
+ return value
88
+
89
+
90
+ def _evidence(members: Mapping[str, object]) -> tuple[str, ...] | None:
91
+ if "ev" not in members:
92
+ return None
93
+ items = _item(members, "ev")
94
+ if not isinstance(items, list):
95
+ raise _Unread("ev")
96
+ entries: list[object] = items # pyright: ignore[reportUnknownVariableType]
97
+ if not 1 <= len(entries) <= _MAX_EVIDENCE:
98
+ raise _Unread("ev")
99
+ names: list[str] = []
100
+ for entry in entries:
101
+ if not isinstance(entry, tuple):
102
+ raise _Unread("ev")
103
+ parts: tuple[object, ...] = entry # pyright: ignore[reportUnknownVariableType]
104
+ name = parts[0]
105
+ if type(name) is not str or _VARIABLE.fullmatch(name) is None:
106
+ raise _Unread("ev")
107
+ names.append(name)
108
+ return tuple(names)
109
+
110
+
111
+ def read_cli_header(value: str | None) -> CliHeader | None:
112
+ """What the header says, or None for none, or one that is not a CLI header of
113
+ any version: not a Dictionary, a member missing, one outside the contract's
114
+ rules, or one given twice, as two header lines a server joined are. Any ``v``
115
+ from 1 is read, and members this version does not know are ignored."""
116
+ if value is None:
117
+ return None
118
+ repeated: list[str] = []
119
+ try:
120
+ members = http_sf.parse(
121
+ value.encode("latin-1"),
122
+ tltype="dictionary",
123
+ on_duplicate_key=lambda key, _context: repeated.append(key),
124
+ )
125
+ except (http_sf.StructuredFieldError, UnicodeEncodeError):
126
+ return None
127
+ if repeated or not isinstance(members, dict):
128
+ return None
129
+ fields: Mapping[str, object] = members
130
+ try:
131
+ _integer(fields, "v", 1, _MAX_INTEGER)
132
+ return CliHeader(
133
+ sdk_version=_string(fields, "sdk", _TEXT),
134
+ cli=_string(fields, "cli", _TEXT),
135
+ run=_string(fields, "run", _RUN),
136
+ sequence=_integer(fields, "seq", 1, _MAX_INTEGER),
137
+ session=_string(fields, "ses", _SESSION),
138
+ session_from=_token(fields, "sesfrom", _SESSION_SOURCES),
139
+ mode=_token(fields, "mode", _MODES),
140
+ cli_version=_optional(fields, "cliv", _TEXT),
141
+ agent=_optional(fields, "agent", _AGENT),
142
+ agent_version=_optional(fields, "agentv", _TEXT),
143
+ evidence=_evidence(fields),
144
+ command=_optional(fields, "cmd", _COMMAND),
145
+ )
146
+ except _Unread:
147
+ return None
148
+
149
+
150
+ def cli_attributes(value: str | None, keyed_hash: Callable[[str], str]) -> Attributes:
151
+ """The request's CLI facts as span attributes; empty for a header that does not read."""
152
+ header = read_cli_header(value)
153
+ if header is None:
154
+ return {}
155
+ attributes: Attributes = {
156
+ "agentrail.cli.name": header.cli,
157
+ "agentrail.cli.run_id": header.run,
158
+ "agentrail.cli.sequence": header.sequence,
159
+ "agentrail.cli.mode": header.mode,
160
+ "agentrail.cli.session.id_hash": keyed_hash(header.session),
161
+ "agentrail.cli.session.source": header.session_from,
162
+ "agentrail.cli.sdk.version": header.sdk_version,
163
+ }
164
+ for key, optional in (
165
+ ("agentrail.cli.version", header.cli_version),
166
+ ("agentrail.cli.command", header.command),
167
+ ("agentrail.cli.agent.name", header.agent),
168
+ ("agentrail.cli.agent.version", header.agent_version),
169
+ ("agentrail.cli.agent.evidence", None if header.evidence is None else ",".join(header.evidence)),
170
+ ):
171
+ if optional is not None:
172
+ attributes[key] = optional
173
+ return attributes