agentrail-python 0.3.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

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.
@@ -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
  ]
agentrail_python/_cli.py CHANGED
@@ -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
 
agentrail_python/_init.py CHANGED
@@ -1,35 +1,30 @@
1
1
  # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
- """Standalone startup: Agentrail owns the process's OpenTelemetry providers."""
2
+ """Startup: one Agentrail installation per process, beside whatever tracer the application runs."""
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
+ import atexit
6
7
  import threading
7
- from dataclasses import replace
8
-
9
- from opentelemetry import _logs as otel_logs
10
- from opentelemetry import propagate, trace
11
- from opentelemetry._logs._internal import ProxyLoggerProvider # pyright: ignore[reportPrivateImportUsage]
12
- from opentelemetry.sdk._logs import LoggerProvider
13
- from opentelemetry.sdk.trace import TracerProvider
14
- from opentelemetry.sdk.trace.sampling import ALWAYS_ON
15
8
 
16
9
  from ._client import Client
17
10
  from ._options import ConfigurationError, Options
18
- from ._processors import Processors
11
+ from ._processors import build
19
12
 
20
13
  _lock = threading.Lock()
21
14
  _installed: tuple[Options, Client] | None = None
22
15
 
23
16
 
24
17
  def init(options: Options) -> Client:
25
- """Install Agentrail's tracer provider, logger provider and propagator globally.
26
-
27
- Call once at startup, before the application serves requests. The
28
- providers drain when the interpreter exits; call ``shutdown`` yourself after
29
- your server stops accepting requests to bound it. Calling it
30
- again with the same options object returns the same client. If the process
31
- already has an OpenTelemetry provider, build it with ``create_processors``
32
- instead.
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.
33
28
  """
34
29
  global _installed
35
30
  with _lock:
@@ -37,28 +32,7 @@ def init(options: Options) -> Client:
37
32
  if _installed[0] is not options:
38
33
  raise ConfigurationError("Agentrail is already initialized. Reuse the original options and client.")
39
34
  return _installed[1]
40
- if not isinstance(trace.get_tracer_provider(), trace.ProxyTracerProvider):
41
- raise ConfigurationError(
42
- "A tracer provider is already installed. Wire create_processors into its construction instead."
43
- )
44
- if not isinstance(otel_logs.get_logger_provider(), ProxyLoggerProvider):
45
- raise ConfigurationError(
46
- "A logger provider is already installed. Use create_processors with the existing setup."
47
- )
48
- processors = Processors(options if options.propagator is not None else _with_base(options))
49
- provider = TracerProvider(sampler=processors.sampler(ALWAYS_ON))
50
- provider.add_span_processor(processors.span_processor)
51
- logger = LoggerProvider()
52
- logger.add_log_record_processor(processors.log_processor)
53
- client = processors.bind(provider)
54
- trace.set_tracer_provider(provider)
55
- otel_logs.set_logger_provider(logger)
56
- propagate.set_global_textmap(processors.propagator)
57
- client._on_shutdown.extend((provider.shutdown, logger.shutdown)) # pyright: ignore[reportPrivateUsage]
35
+ client = build(options)
36
+ atexit.register(client.shutdown)
58
37
  _installed = (options, client)
59
38
  return client
60
-
61
-
62
- def _with_base(options: Options) -> Options:
63
- """Unmanaged work keeps the process's existing propagator."""
64
- return replace(options, propagator=propagate.get_global_textmap())
@@ -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: