agentrail-python 0.3.0__tar.gz → 0.4.1__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 (51) hide show
  1. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/PKG-INFO +65 -5
  2. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/README.md +60 -1
  3. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/integration/README.md +6 -5
  4. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/pyproject.toml +13 -5
  5. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/__init__.py +2 -5
  6. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_cli.py +1 -1
  7. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_client.py +30 -22
  8. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_handoff.py +10 -6
  9. agentrail_python-0.4.1/src/agentrail_python/_init.py +38 -0
  10. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_options.py +1 -5
  11. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_outbound.py +39 -17
  12. agentrail_python-0.4.1/src/agentrail_python/_processors.py +218 -0
  13. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_runtime.py +44 -6
  14. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_version.py +1 -1
  15. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/asgi.py +6 -3
  16. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/httpx.py +19 -15
  17. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/mcp.py +32 -15
  18. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/requests.py +14 -9
  19. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/wsgi.py +5 -4
  20. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/README.md +9 -4
  21. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/sdk-contract.json +1 -1
  22. agentrail_python-0.4.1/tests/coexistence.py +523 -0
  23. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/support.py +28 -12
  24. agentrail_python-0.4.1/tests/test_coexistence.py +197 -0
  25. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_delivery.py +37 -13
  26. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_evidence.py +12 -13
  27. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_incoming.py +28 -4
  28. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_mcp.py +22 -1
  29. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_outbound.py +45 -11
  30. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_privacy.py +14 -24
  31. agentrail_python-0.4.1/tests/test_setup.py +80 -0
  32. agentrail_python-0.3.0/src/agentrail_python/_init.py +0 -64
  33. agentrail_python-0.3.0/src/agentrail_python/_processors.py +0 -262
  34. agentrail_python-0.3.0/tests/test_composition.py +0 -174
  35. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/.gitignore +0 -0
  36. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/LICENSE +0 -0
  37. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_performance.py +0 -0
  38. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_privacy.py +0 -0
  39. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_queue.py +0 -0
  40. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_suppression.py +0 -0
  41. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/_text.py +0 -0
  42. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/logging.py +0 -0
  43. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/src/agentrail_python/py.typed +0 -0
  44. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/interoperability/contract.json +0 -0
  45. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/interoperability/generate-performance.mjs +0 -0
  46. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/interoperability/javascript.json +0 -0
  47. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/interoperability/markers.json +0 -0
  48. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/testdata/interoperability/performance.json +0 -0
  49. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_cli.py +0 -0
  50. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_interoperability.py +0 -0
  51. {agentrail_python-0.3.0 → agentrail_python-0.4.1}/tests/test_mcp_request_facts.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentrail-python
3
- Version: 0.3.0
3
+ Version: 0.4.1
4
4
  Summary: Agentrail for Python backends: HTTP, identity, milestones, logs and MCP for agent journeys, over OpenTelemetry.
5
5
  Project-URL: Homepage, https://www.agentrail.co
6
6
  Project-URL: Documentation, https://www.agentrail.co/docs/guides/journeys-python
@@ -23,9 +23,10 @@ Classifier: Topic :: System :: Monitoring
23
23
  Classifier: Typing :: Typed
24
24
  Requires-Python: >=3.10
25
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
26
+ Requires-Dist: opentelemetry-api<2,>=1.39
27
+ Requires-Dist: opentelemetry-exporter-otlp-proto-common<2,>=1.39
28
+ Requires-Dist: opentelemetry-sdk<2,>=1.39
29
+ Requires-Dist: requests<3,>=2.26
29
30
  Provides-Extra: httpx
30
31
  Requires-Dist: httpx<1,>=0.28; extra == 'httpx'
31
32
  Provides-Extra: mcp
@@ -120,6 +121,42 @@ application = agentrail.wsgi(get_wsgi_application()) # Django (WSGI)
120
121
  app.wsgi_app = agentrail.wsgi(app.wsgi_app) # Flask, any WSGI app
121
122
  ```
122
123
 
124
+ ### Beside Sentry, Datadog or OpenTelemetry
125
+
126
+ The setup above is the same when your application already runs Sentry,
127
+ Datadog or OpenTelemetry, and there is nothing to change in theirs. They can
128
+ start before or after `init`, and their middleware can sit outside or inside
129
+ Agentrail's. Agentrail runs a tracer provider of its own and registers no
130
+ OpenTelemetry global: no tracer provider, logger provider, propagator or
131
+ context. Their spans never reach Agentrail, and Agentrail's never reach them.
132
+
133
+ Inside a request, your tracer's span stays current: your database and client
134
+ spans stay children of its server span, and its trace headers (`traceparent`,
135
+ `tracestate`, `baggage`, `sentry-trace`, `x-datadog-*`) go out on your calls as
136
+ it set them. Agentrail removes only its own headers,
137
+ `x-agentrail-trace-handoff` and `x-agentrail-cli`.
138
+
139
+ One limit: on a call to an origin in `outbound_origins`, Agentrail's signed
140
+ `traceparent` replaces your tracer's, and its `tracestate` is dropped with it.
141
+ A tracer that propagates by W3C `traceparent` alone, as OpenTelemetry does by
142
+ default, continues that hop under Agentrail's trace ID. Sentry and Datadog keep
143
+ their own trace there, since `sentry-trace`, `baggage` and `x-datadog-*` still
144
+ go out. OpenTelemetry's httpx instrumentation, installed with
145
+ `HTTPXClientInstrumentor().instrument()`, writes its `traceparent` beneath
146
+ Agentrail's transport, after Agentrail has signed: such a call reaches the
147
+ allowed origin with a `traceparent` the handoff does not name, and that service
148
+ records the caller as a link instead of continuing its trace.
149
+
150
+ Agentrail's capture and delivery take none of OpenTelemetry's `OTEL_*`
151
+ environment variables, which stay your exporters' and SDK's: your
152
+ `OTEL_EXPORTER_OTLP_*` headers, compression and certificates never reach
153
+ Agentrail's collector, and your attribute limits never cut its spans. The one
154
+ exception is `OTEL_SDK_DISABLED=true`, which also switches Agentrail off: it
155
+ records nothing and reports `entry_not_recording` to `on_error`.
156
+
157
+ With `DD_TRACE_OTEL_ENABLED` and `import ddtrace.auto`, import ddtrace before
158
+ `agentrail_python`, as Datadog asks anyway.
159
+
123
160
  ### MCP
124
161
 
125
162
  With the official `mcp` SDK, add the middleware first. Each JSON-RPC message
@@ -185,12 +222,35 @@ configure.
185
222
  Agentrail never fails your request: anything it could not capture or send goes
186
223
  to your `on_error` callback.
187
224
 
225
+ ## Upgrading from 0.3
226
+
227
+ 0.4 has one setup for everyone, and removes the one for an existing
228
+ OpenTelemetry provider:
229
+
230
+ - `create_processors` and `Processors` (its `bind`, `sampler`,
231
+ `span_processor`, `log_processor` and `propagator`) are gone: call `init`
232
+ instead, and leave your provider as it was.
233
+ - `Options.propagator` is gone: your propagator stays yours.
234
+ - `init` no longer refuses an existing tracer or logger provider, and sets
235
+ none.
236
+ - Your own spans inside a request, such as those of
237
+ `opentelemetry-instrumentation-*` packages, and logs written through an
238
+ OpenTelemetry logger provider no longer reach Agentrail. Send logs with
239
+ `agentrail.log` or `agentrail_python.logging.AgentrailHandler`.
240
+ - Calls made while answering a request keep your tracer's headers; only an
241
+ allowed origin's `traceparent` is replaced.
242
+ - Work in a thread you start yourself is part of the request only when the
243
+ thread runs in a copy of the request's context:
244
+ `contextvars.copy_context().run(...)` or `asyncio.to_thread` (Starlette's and
245
+ anyio's thread pools already do this). OpenTelemetry's threading
246
+ instrumentation no longer carries Agentrail's request.
247
+
188
248
  ## Documentation
189
249
 
190
250
  | | |
191
251
  | --- | --- |
192
252
  | [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 |
253
+ | [Python SDK reference](https://www.agentrail.co/docs/guides/journeys-python-reference) | Every option, running beside Sentry, Datadog or OpenTelemetry, delivery and error codes, framework notes |
194
254
  | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) | Skip calls between your own services |
195
255
  | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) | Report workflow attempts and plugin calls on milestones |
196
256
  | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) | What is sent, what is hashed, and what never leaves your process |
@@ -84,6 +84,42 @@ application = agentrail.wsgi(get_wsgi_application()) # Django (WSGI)
84
84
  app.wsgi_app = agentrail.wsgi(app.wsgi_app) # Flask, any WSGI app
85
85
  ```
86
86
 
87
+ ### Beside Sentry, Datadog or OpenTelemetry
88
+
89
+ The setup above is the same when your application already runs Sentry,
90
+ Datadog or OpenTelemetry, and there is nothing to change in theirs. They can
91
+ start before or after `init`, and their middleware can sit outside or inside
92
+ Agentrail's. Agentrail runs a tracer provider of its own and registers no
93
+ OpenTelemetry global: no tracer provider, logger provider, propagator or
94
+ context. Their spans never reach Agentrail, and Agentrail's never reach them.
95
+
96
+ Inside a request, your tracer's span stays current: your database and client
97
+ spans stay children of its server span, and its trace headers (`traceparent`,
98
+ `tracestate`, `baggage`, `sentry-trace`, `x-datadog-*`) go out on your calls as
99
+ it set them. Agentrail removes only its own headers,
100
+ `x-agentrail-trace-handoff` and `x-agentrail-cli`.
101
+
102
+ One limit: on a call to an origin in `outbound_origins`, Agentrail's signed
103
+ `traceparent` replaces your tracer's, and its `tracestate` is dropped with it.
104
+ A tracer that propagates by W3C `traceparent` alone, as OpenTelemetry does by
105
+ default, continues that hop under Agentrail's trace ID. Sentry and Datadog keep
106
+ their own trace there, since `sentry-trace`, `baggage` and `x-datadog-*` still
107
+ go out. OpenTelemetry's httpx instrumentation, installed with
108
+ `HTTPXClientInstrumentor().instrument()`, writes its `traceparent` beneath
109
+ Agentrail's transport, after Agentrail has signed: such a call reaches the
110
+ allowed origin with a `traceparent` the handoff does not name, and that service
111
+ records the caller as a link instead of continuing its trace.
112
+
113
+ Agentrail's capture and delivery take none of OpenTelemetry's `OTEL_*`
114
+ environment variables, which stay your exporters' and SDK's: your
115
+ `OTEL_EXPORTER_OTLP_*` headers, compression and certificates never reach
116
+ Agentrail's collector, and your attribute limits never cut its spans. The one
117
+ exception is `OTEL_SDK_DISABLED=true`, which also switches Agentrail off: it
118
+ records nothing and reports `entry_not_recording` to `on_error`.
119
+
120
+ With `DD_TRACE_OTEL_ENABLED` and `import ddtrace.auto`, import ddtrace before
121
+ `agentrail_python`, as Datadog asks anyway.
122
+
87
123
  ### MCP
88
124
 
89
125
  With the official `mcp` SDK, add the middleware first. Each JSON-RPC message
@@ -149,12 +185,35 @@ configure.
149
185
  Agentrail never fails your request: anything it could not capture or send goes
150
186
  to your `on_error` callback.
151
187
 
188
+ ## Upgrading from 0.3
189
+
190
+ 0.4 has one setup for everyone, and removes the one for an existing
191
+ OpenTelemetry provider:
192
+
193
+ - `create_processors` and `Processors` (its `bind`, `sampler`,
194
+ `span_processor`, `log_processor` and `propagator`) are gone: call `init`
195
+ instead, and leave your provider as it was.
196
+ - `Options.propagator` is gone: your propagator stays yours.
197
+ - `init` no longer refuses an existing tracer or logger provider, and sets
198
+ none.
199
+ - Your own spans inside a request, such as those of
200
+ `opentelemetry-instrumentation-*` packages, and logs written through an
201
+ OpenTelemetry logger provider no longer reach Agentrail. Send logs with
202
+ `agentrail.log` or `agentrail_python.logging.AgentrailHandler`.
203
+ - Calls made while answering a request keep your tracer's headers; only an
204
+ allowed origin's `traceparent` is replaced.
205
+ - Work in a thread you start yourself is part of the request only when the
206
+ thread runs in a copy of the request's context:
207
+ `contextvars.copy_context().run(...)` or `asyncio.to_thread` (Starlette's and
208
+ anyio's thread pools already do this). OpenTelemetry's threading
209
+ instrumentation no longer carries Agentrail's request.
210
+
152
211
  ## Documentation
153
212
 
154
213
  | | |
155
214
  | --- | --- |
156
215
  | [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 |
216
+ | [Python SDK reference](https://www.agentrail.co/docs/guides/journeys-python-reference) | Every option, running beside Sentry, Datadog or OpenTelemetry, delivery and error codes, framework notes |
158
217
  | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) | Skip calls between your own services |
159
218
  | [Plugin workflow tracking](https://www.agentrail.co/docs/guides/plugin-performance) | Report workflow attempts and plugin calls on milestones |
160
219
  | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) | What is sent, what is hashed, and what never leaves your process |
@@ -9,10 +9,11 @@ ARGUS_DIR=/absolute/path/to/argus ./integration/run.sh
9
9
 
10
10
  `capture.py` uses the public package: a Starlette app behind the ASGI
11
11
  middleware identifies a synthetic user, opens a custom milestone, writes two
12
- correlated logs and makes an outgoing `httpx` call beneath a supporting
13
- OpenTelemetry span, with a synthetic location hook. A local collector keeps the
14
- exact OTLP protobuf bytes. There are no provider calls, real identities or
15
- production credentials; the collector token and hash key are synthetic.
12
+ correlated logs and makes an outgoing `httpx` call to an allowed origin, the
13
+ milestone's supporting span, with a synthetic location hook. A local collector
14
+ keeps the exact OTLP protobuf bytes. There are no provider calls, real
15
+ identities or production credentials; the collector token and hash key are
16
+ synthetic.
16
17
 
17
18
  The runner copies `argus-receiver.integration.test.ts` into a uniquely named
18
19
  temporary Argus API test, then runs `pnpm --filter @argus/api test:file`.
@@ -21,7 +22,7 @@ database. The test creates a backend (`node`) journey source through the public
21
22
  API, sends the captured bytes logs first and trace batches reversed, then
22
23
  repeats every delivery unchanged. Fresh reads check that:
23
24
 
24
- - four spans and two logs are stored once, through the retries;
25
+ - three spans and two logs are stored once, through the retries;
25
26
  - the resource keeps `agentrail-python`, its service identity and hash key ID;
26
27
  - the HTTP entry and the milestone are both entries, with supporting spans
27
28
  beneath the milestone;
@@ -25,11 +25,15 @@ classifiers = [
25
25
  "Topic :: System :: Monitoring",
26
26
  "Typing :: Typed",
27
27
  ]
28
- # The tested OpenTelemetry family. Its API, SDK and exporter versions move together.
28
+ # The OpenTelemetry family from the oldest release the suite passes on (CI's
29
+ # lowest-opentelemetry job) to the next major. Its API, SDK and OTLP encoder
30
+ # versions move together.
29
31
  dependencies = [
30
- "opentelemetry-api>=1.45.1,<1.46",
31
- "opentelemetry-sdk>=1.45.1,<1.46",
32
- "opentelemetry-exporter-otlp-proto-http>=1.45.1,<1.46",
32
+ "opentelemetry-api>=1.39,<2",
33
+ "opentelemetry-sdk>=1.39,<2",
34
+ "opentelemetry-exporter-otlp-proto-common>=1.39,<2",
35
+ # Delivery to the collector; 2.26 is the oldest the suite passes on.
36
+ "requests>=2.26,<3",
33
37
  # RFC 9651 Structured Fields, for the x-agentrail-cli header a customer's CLI sends.
34
38
  "http-sf>=1.5.0,<2",
35
39
  ]
@@ -59,6 +63,10 @@ dev = [
59
63
  "uvicorn>=0.38",
60
64
  "a2wsgi>=1.10",
61
65
  "trustme>=1.2",
66
+ # The tracers a customer already runs, for the tests that run beside them.
67
+ "sentry-sdk>=2.40",
68
+ "ddtrace>=4.16",
69
+ "opentelemetry-instrumentation-asgi>=0.60b0",
62
70
  ]
63
71
 
64
72
  [tool.hatch.version]
@@ -72,7 +80,7 @@ include = ["src", "tests", "testdata", "README.md", "LICENSE", "pyproject.toml"]
72
80
 
73
81
  [tool.uv]
74
82
  # Resolve only releases at least two weeks old when the lock was written.
75
- exclude-newer = "2026-10-28T00:00:00Z"
83
+ exclude-newer = "2026-11-11T00:00:00Z"
76
84
 
77
85
  [tool.ruff]
78
86
  line-length = 120
@@ -1,8 +1,8 @@
1
1
  # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
2
  """Agentrail for Python: backend journey evidence over OpenTelemetry.
3
3
 
4
- Standalone: ``agentrail = init(Options(...))``. With an existing OpenTelemetry
5
- setup: ``create_processors(Options(...))``, then ``bind`` your provider.
4
+ ``agentrail = init(Options(...))``, the same with or without Sentry, Datadog or
5
+ an OpenTelemetry setup of your own: Agentrail registers no OpenTelemetry global.
6
6
  """
7
7
 
8
8
  from ._client import Client, Diagnostics, MilestoneScope
@@ -30,7 +30,6 @@ from ._options import (
30
30
  VerifiedIdentity,
31
31
  )
32
32
  from ._privacy import StructuredLog
33
- from ._processors import Processors, create_processors
34
33
  from ._queue import QueueStats
35
34
  from ._version import VERSION
36
35
 
@@ -57,12 +56,10 @@ __all__ = [
57
56
  "PerformanceContext",
58
57
  "PluginInvocation",
59
58
  "PrincipalKind",
60
- "Processors",
61
59
  "QueueOptions",
62
60
  "QueueStats",
63
61
  "StructuredLog",
64
62
  "Surface",
65
63
  "VerifiedIdentity",
66
- "create_processors",
67
64
  "init",
68
65
  ]
@@ -18,7 +18,7 @@ import http_sf
18
18
 
19
19
  from ._runtime import Attributes
20
20
 
21
- CLI_HEADER = "x-agentrail-cli" # also in ``_handoff.STRIPPED_HEADERS``
21
+ CLI_HEADER = "x-agentrail-cli" # also in ``_handoff.AGENTRAIL_HEADERS``
22
22
 
23
23
  _TEXT = re.compile(r"[\x20-\x7e]{1,64}")
24
24
  _COMMAND = re.compile(r"[\x20-\x7e]{1,128}")
@@ -9,6 +9,7 @@ import re
9
9
  import threading
10
10
  import time
11
11
  from collections.abc import Callable
12
+ from contextvars import Token
12
13
  from dataclasses import dataclass
13
14
  from types import TracebackType
14
15
  from typing import TYPE_CHECKING, Any, TypeVar, cast
@@ -33,7 +34,7 @@ from ._options import (
33
34
  from ._performance import performance_attributes
34
35
  from ._privacy import StructuredLog, clean_context, copy_log
35
36
  from ._queue import ExportQueue, QueueStats
36
- from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime
37
+ from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime, attach, current, current_span, detach
37
38
  from ._suppression import suppressed
38
39
  from ._text import bounded, valid_text
39
40
  from ._version import VERSION
@@ -62,7 +63,8 @@ def _error_type(error: BaseException) -> str:
62
63
  class MilestoneScope:
63
64
  """A milestone around a block: ``with`` or ``async with``.
64
65
 
65
- The block's exception is recorded and re-raised unchanged.
66
+ The block's exception is recorded and re-raised unchanged. The
67
+ application's own current span stays current inside it.
66
68
  """
67
69
 
68
70
  def __init__(
@@ -73,6 +75,7 @@ class MilestoneScope:
73
75
  *,
74
76
  step: bool = True,
75
77
  mcp: McpEvidence | None = None,
78
+ link: SpanContext | None = None,
76
79
  ) -> None:
77
80
  client._validate_milestone(name, details) # pyright: ignore[reportPrivateUsage]
78
81
  self._client = client
@@ -80,15 +83,16 @@ class MilestoneScope:
80
83
  self._details = details
81
84
  self._step = step
82
85
  self._mcp = mcp
86
+ self._link = link
83
87
  self._span: Span | None = None
84
- self._token: object | None = None
88
+ self._token: Token[otel_context.Context] | None = None
85
89
 
86
90
  def __enter__(self) -> MilestoneScope:
87
91
  span, ctx = self._client._start( # pyright: ignore[reportPrivateUsage]
88
- self._name, self._details, step=self._step, mcp=self._mcp
92
+ self._name, self._details, step=self._step, mcp=self._mcp, link=self._link
89
93
  )
90
94
  self._span = span
91
- self._token = otel_context.attach(ctx)
95
+ self._token = attach(ctx)
92
96
  return self
93
97
 
94
98
  def __exit__(
@@ -107,7 +111,7 @@ class MilestoneScope:
107
111
  span.set_attribute("error.type", _error_type(exc))
108
112
  span.end()
109
113
  finally:
110
- otel_context.detach(cast(Any, token))
114
+ detach(token)
111
115
 
112
116
  async def __aenter__(self) -> MilestoneScope:
113
117
  return self.__enter__()
@@ -122,9 +126,10 @@ class MilestoneScope:
122
126
 
123
127
 
124
128
  class Client:
125
- """Records backend evidence with a bound tracer provider.
129
+ """Records backend evidence with Agentrail's own tracer provider.
126
130
 
127
- Get one from ``init`` or from ``create_processors(...).bind(provider)``.
131
+ Get one from ``init``. It registers no OpenTelemetry global and never
132
+ changes the application's current span.
128
133
  """
129
134
 
130
135
  def __init__(
@@ -222,33 +227,36 @@ class Client:
222
227
  *,
223
228
  step: bool = True,
224
229
  mcp: McpEvidence | None = None,
230
+ link: SpanContext | None = None,
225
231
  ) -> tuple[Span, otel_context.Context]:
232
+ """A milestone span parented on Agentrail's current span, and the context to make it current in."""
226
233
  performance = None
227
234
  if details.performance is not None:
228
235
  try:
229
236
  performance = performance_attributes(details.performance, self._runtime.options.input.hash_key)
230
237
  except ConfigurationError:
231
238
  self._runtime.report("invalid_performance", "context")
232
- base = otel_context.get_current()
239
+ base = current()
233
240
  state = self._runtime.state(base)
234
- continued: list[Link] = []
235
- if state is not None and state.entry is not None:
236
- current = trace.get_current_span(base).get_span_context()
237
- if current.is_valid and (current.is_remote or current.trace_id != state.entry.trace_id):
238
- # A trace continued from unsigned input inside the request (the MCP
239
- # SDK continues a client's _meta traceparent) is a link, never the parent.
240
- continued.append(Link(clean_context(current)))
241
- base = trace.set_span_in_context(NonRecordingSpan(state.entry), base)
242
241
  if state is None:
243
- external = trace.get_current_span(base).get_span_context()
244
- links = [Link(clean_context(external))] if external.is_valid else []
242
+ # Its own managed scope: the application's span it runs in (its trace,
243
+ # an unrelated caller's) is a link, never the parent. When the message
244
+ # names a trace, a span on that trace is the library that continued it
245
+ # (the MCP SDK continues _meta in OpenTelemetry's context): one link.
246
+ external = trace.get_current_span().get_span_context()
247
+ continued = link is not None and external.trace_id == link.trace_id
248
+ links = [Link(clean_context(external))] if external.is_valid and not continued else []
245
249
  state = RequestState(links=links)
246
- # Its own managed scope: an unrelated caller's trace is a link, never the parent.
247
250
  base = otel_context.set_value(self._runtime.state_key, state, otel_context.Context())
248
251
  mark = Mark(name=name, details=details, performance=performance, identity=identity, step=step, mcp=mcp)
249
252
  marked = otel_context.set_value(self._runtime.mark_key, mark, base)
250
253
  parented = trace.get_current_span(base).get_span_context().is_valid
251
- span = self._tracer.start_span(name, context=marked, links=continued + ([] if parented else state.links))
254
+ links = [] if parented else list(state.links)
255
+ if link is not None:
256
+ # A trace the message itself names (an MCP client's _meta traceparent)
257
+ # is a link, never the parent.
258
+ links.append(Link(clean_context(link)))
259
+ span = self._tracer.start_span(name, context=marked, links=links)
252
260
  if not span.is_recording():
253
261
  self._runtime.report("entry_not_recording", "traces")
254
262
  return span, trace.set_span_in_context(span, base)
@@ -264,7 +272,7 @@ class Client:
264
272
  return
265
273
  span = None
266
274
  if state is not None:
267
- context = trace.get_current_span().get_span_context()
275
+ context = current_span().get_span_context()
268
276
  span = context if context.is_valid else None
269
277
  now = time.time_ns()
270
278
  self._logs.add(copy_log(entry, now, now, span, self._runtime))
@@ -17,12 +17,16 @@ from dataclasses import dataclass
17
17
  from ._text import js_json, well_formed
18
18
 
19
19
  HANDOFF_HEADER = "x-agentrail-trace-handoff"
20
- # Headers a managed request never forwards as received.
21
- OWNED_HEADERS = ("traceparent", "tracestate", "baggage", "sentry-trace", HANDOFF_HEADER)
22
- # What a managed request never sends on as the server received it: the owned
23
- # trace headers, and a CLI's x-agentrail-cli, which names its run and session
24
- # to this server alone.
25
- STRIPPED_HEADERS = (*OWNED_HEADERS, "x-agentrail-cli")
20
+ # Agentrail's own headers, which a managed call never sends on as the server
21
+ # received them: a handoff binds one request, and a CLI's x-agentrail-cli names
22
+ # its run and session to this server alone. Every other header is the
23
+ # application's, its tracers' included, and is left alone.
24
+ AGENTRAIL_HEADERS = (HANDOFF_HEADER, "x-agentrail-cli")
25
+ # What a call to an allowed origin loses with the application's traceparent,
26
+ # which the signed one replaces: the vendor state that belonged to it.
27
+ SIGNED_REPLACES = ("traceparent", "tracestate")
28
+ # What a managed call to the collector itself never carries.
29
+ COLLECTOR_STRIPPED = ("traceparent", "tracestate", "baggage", "sentry-trace", *AGENTRAIL_HEADERS)
26
30
  MAX_AGE_MS = 60_000
27
31
  _MAX_SAFE_INTEGER = 9_007_199_254_740_991
28
32
 
@@ -0,0 +1,38 @@
1
+ # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
+ """Startup: one Agentrail installation per process, beside whatever tracer the application runs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import atexit
7
+ import threading
8
+
9
+ from ._client import Client
10
+ from ._options import ConfigurationError, Options
11
+ from ._processors import build
12
+
13
+ _lock = threading.Lock()
14
+ _installed: tuple[Options, Client] | None = None
15
+
16
+
17
+ def init(options: Options) -> Client:
18
+ """Start Agentrail with its own tracer provider and export queues.
19
+
20
+ Registers no OpenTelemetry global (tracer provider, logger provider,
21
+ propagator or context): Sentry, Datadog or the application's own
22
+ OpenTelemetry setup can start before or after it, unchanged. Call once at
23
+ startup, before the application serves requests. What is still queued is
24
+ sent when the interpreter exits; call ``shutdown`` yourself after your
25
+ server stops accepting requests to bound it. Calling it again with the same
26
+ options object returns the same client; other options are refused, since a
27
+ second installation would record every request twice.
28
+ """
29
+ global _installed
30
+ with _lock:
31
+ if _installed is not None:
32
+ if _installed[0] is not options:
33
+ raise ConfigurationError("Agentrail is already initialized. Reuse the original options and client.")
34
+ return _installed[1]
35
+ client = build(options)
36
+ atexit.register(client.shutdown)
37
+ _installed = (options, client)
38
+ return client
@@ -8,14 +8,11 @@ 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, Any, Literal, TypedDict
11
+ from typing import Any, Literal, TypedDict
12
12
  from urllib.parse import SplitResult, urlsplit
13
13
 
14
14
  from ._text import valid_text, well_formed
15
15
 
16
- if TYPE_CHECKING:
17
- from opentelemetry.propagators.textmap import TextMapPropagator
18
-
19
16
  PrincipalKind = Literal["user", "agent_registration", "agent_instance", "oauth_client", "api_key"]
20
17
  PRINCIPAL_KINDS: frozenset[str] = frozenset(("user", "agent_registration", "agent_instance", "oauth_client", "api_key"))
21
18
  Surface = Literal["http", "mcp", "auth", "custom", "a2a", "genai", "payment", "edge", "firewall", "browser"]
@@ -126,7 +123,6 @@ class Options:
126
123
  incoming_location: Callable[[IncomingRequest], IPLocation | None] | None = None
127
124
  logs: LogsOptions = field(default_factory=LogsOptions)
128
125
  queue: QueueOptions = field(default_factory=QueueOptions)
129
- propagator: TextMapPropagator | None = None
130
126
  on_error: Callable[[CaptureError], None] | None = None
131
127
 
132
128
 
@@ -9,7 +9,16 @@ from typing import TYPE_CHECKING
9
9
 
10
10
  from opentelemetry.trace import Span, SpanKind, StatusCode
11
11
 
12
- from ._handoff import HANDOFF_HEADER, HandoffInputError, format_traceparent, sign
12
+ from ._handoff import (
13
+ AGENTRAIL_HEADERS,
14
+ COLLECTOR_STRIPPED,
15
+ HANDOFF_HEADER,
16
+ SIGNED_REPLACES,
17
+ HandoffInputError,
18
+ format_traceparent,
19
+ sign,
20
+ )
21
+ from ._runtime import current
13
22
 
14
23
  if TYPE_CHECKING:
15
24
  from ._client import Client
@@ -27,16 +36,26 @@ def origin(scheme: str, host: str, port: int | None) -> str:
27
36
 
28
37
  @dataclass
29
38
  class Outgoing:
30
- """``span`` is None when the call is not part of a managed operation."""
39
+ """``span`` is None when the call is not part of a managed operation.
40
+
41
+ The call is sent without the headers in ``remove``, then with ``headers``.
42
+ Neither changes the application's own request object: an HTTP client builds
43
+ a redirect from that, and the next destination is admitted on its own.
44
+ """
31
45
 
32
46
  span: Span | None
47
+ remove: tuple[str, ...] = ()
33
48
  headers: dict[str, str] = field(default_factory=lambda: {})
34
- strip: bool = False
49
+
50
+ @property
51
+ def changes(self) -> bool:
52
+ return bool(self.remove or self.headers)
35
53
 
36
54
 
37
55
  def begin(client: Client, method: str, destination: str, path: str, target: str, url: str) -> Outgoing:
38
- """Owned headers are always stripped from managed calls; only exact allowed
39
- origins receive a newly signed handoff."""
56
+ """A managed call keeps the application's headers, its tracers' included,
57
+ without Agentrail's own. Only an exact allowed origin receives a newly signed
58
+ handoff, whose traceparent replaces the application's."""
40
59
  runtime = client._runtime # pyright: ignore[reportPrivateUsage]
41
60
  if not client._managed(): # pyright: ignore[reportPrivateUsage]
42
61
  return Outgoing(None)
@@ -45,24 +64,27 @@ def begin(client: Client, method: str, destination: str, path: str, target: str,
45
64
  f"{options.endpoint_path}/v1/traces",
46
65
  f"{options.endpoint_path}/v1/logs",
47
66
  ):
48
- return Outgoing(None, strip=True)
67
+ return Outgoing(None, remove=COLLECTOR_STRIPPED)
49
68
  tracer = client._tracer # pyright: ignore[reportPrivateUsage]
50
69
  span = tracer.start_span(
51
70
  f"HTTP {method}",
71
+ context=current(),
52
72
  kind=SpanKind.CLIENT,
53
73
  attributes={"http.request.method": method, "url.full": url},
54
74
  )
55
- outgoing = Outgoing(span, strip=True)
56
- if destination in options.origins:
57
- context = span.get_span_context()
58
- parent = format_traceparent(context.trace_id, context.span_id, context.trace_flags)
59
- try:
60
- token = sign(options.input.hash_key, parent, method, target, time.time_ns() // 1_000_000)
61
- except HandoffInputError:
62
- runtime.report("handoff_refused", "context")
63
- else:
64
- outgoing.headers = {"traceparent": parent, HANDOFF_HEADER: token}
65
- return outgoing
75
+ if destination not in options.origins:
76
+ return Outgoing(span, remove=AGENTRAIL_HEADERS)
77
+ context = span.get_span_context()
78
+ parent = format_traceparent(context.trace_id, context.span_id, context.trace_flags)
79
+ try:
80
+ token = sign(options.input.hash_key, parent, method, target, time.time_ns() // 1_000_000)
81
+ except HandoffInputError:
82
+ # Nothing signed, nothing replaced: the call goes as to any other origin.
83
+ runtime.report("handoff_refused", "context")
84
+ return Outgoing(span, remove=AGENTRAIL_HEADERS)
85
+ return Outgoing(
86
+ span, remove=(*AGENTRAIL_HEADERS, *SIGNED_REPLACES), headers={"traceparent": parent, HANDOFF_HEADER: token}
87
+ )
66
88
 
67
89
 
68
90
  def finish(span: Span, status: int | None, error: BaseException | None) -> None: