agentrail-python 0.1.0__py3-none-any.whl → 0.3.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.
- agentrail_python/__init__.py +4 -0
- agentrail_python/_cli.py +173 -0
- agentrail_python/_client.py +48 -7
- agentrail_python/_handoff.py +4 -0
- agentrail_python/_options.py +38 -1
- agentrail_python/_privacy.py +158 -8
- agentrail_python/_processors.py +4 -1
- agentrail_python/_queue.py +88 -18
- agentrail_python/_runtime.py +78 -2
- agentrail_python/_version.py +1 -1
- agentrail_python/asgi.py +11 -1
- agentrail_python/httpx.py +2 -2
- agentrail_python/mcp.py +438 -43
- agentrail_python/requests.py +2 -2
- agentrail_python/wsgi.py +9 -1
- agentrail_python-0.3.0.dist-info/METADATA +209 -0
- agentrail_python-0.3.0.dist-info/RECORD +26 -0
- agentrail_python-0.1.0.dist-info/METADATA +0 -625
- agentrail_python-0.1.0.dist-info/RECORD +0 -25
- {agentrail_python-0.1.0.dist-info → agentrail_python-0.3.0.dist-info}/WHEEL +0 -0
- {agentrail_python-0.1.0.dist-info → agentrail_python-0.3.0.dist-info}/licenses/LICENSE +0 -0
agentrail_python/__init__.py
CHANGED
|
@@ -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",
|
agentrail_python/_cli.py
ADDED
|
@@ -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
|
agentrail_python/_client.py
CHANGED
|
@@ -17,20 +17,23 @@ 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 .
|
|
20
|
+
from ._cli import CLI_HEADER, cli_attributes
|
|
21
|
+
from ._handoff import HANDOFF_HEADER, Refused, keyed_hash, parse_traceparent, verify
|
|
21
22
|
from ._options import (
|
|
22
23
|
LOCATION_SOURCES,
|
|
23
24
|
PRINCIPAL_KINDS,
|
|
24
25
|
SURFACES,
|
|
26
|
+
CaptureCode,
|
|
25
27
|
ConfigurationError,
|
|
26
28
|
IncomingRequest,
|
|
27
29
|
MilestoneContext,
|
|
30
|
+
Signal,
|
|
28
31
|
VerifiedIdentity,
|
|
29
32
|
)
|
|
30
33
|
from ._performance import performance_attributes
|
|
31
34
|
from ._privacy import StructuredLog, clean_context, copy_log
|
|
32
35
|
from ._queue import ExportQueue, QueueStats
|
|
33
|
-
from ._runtime import Attributes, Mark, RequestState, Runtime
|
|
36
|
+
from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime
|
|
34
37
|
from ._suppression import suppressed
|
|
35
38
|
from ._text import bounded, valid_text
|
|
36
39
|
from ._version import VERSION
|
|
@@ -62,16 +65,28 @@ class MilestoneScope:
|
|
|
62
65
|
The block's exception is recorded and re-raised unchanged.
|
|
63
66
|
"""
|
|
64
67
|
|
|
65
|
-
def __init__(
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
client: Client,
|
|
71
|
+
name: str,
|
|
72
|
+
details: MilestoneContext,
|
|
73
|
+
*,
|
|
74
|
+
step: bool = True,
|
|
75
|
+
mcp: McpEvidence | None = None,
|
|
76
|
+
) -> None:
|
|
66
77
|
client._validate_milestone(name, details) # pyright: ignore[reportPrivateUsage]
|
|
67
78
|
self._client = client
|
|
68
79
|
self._name = name
|
|
69
80
|
self._details = details
|
|
81
|
+
self._step = step
|
|
82
|
+
self._mcp = mcp
|
|
70
83
|
self._span: Span | None = None
|
|
71
84
|
self._token: object | None = None
|
|
72
85
|
|
|
73
86
|
def __enter__(self) -> MilestoneScope:
|
|
74
|
-
span, ctx = self._client._start(
|
|
87
|
+
span, ctx = self._client._start( # pyright: ignore[reportPrivateUsage]
|
|
88
|
+
self._name, self._details, step=self._step, mcp=self._mcp
|
|
89
|
+
)
|
|
75
90
|
self._span = span
|
|
76
91
|
self._token = otel_context.attach(ctx)
|
|
77
92
|
return self
|
|
@@ -200,7 +215,13 @@ class Client:
|
|
|
200
215
|
raise ConfigurationError("Milestone name and kind must contain 1-256 characters, with a known surface.")
|
|
201
216
|
|
|
202
217
|
def _start(
|
|
203
|
-
self,
|
|
218
|
+
self,
|
|
219
|
+
name: str,
|
|
220
|
+
details: MilestoneContext,
|
|
221
|
+
identity: Attributes | None = None,
|
|
222
|
+
*,
|
|
223
|
+
step: bool = True,
|
|
224
|
+
mcp: McpEvidence | None = None,
|
|
204
225
|
) -> tuple[Span, otel_context.Context]:
|
|
205
226
|
performance = None
|
|
206
227
|
if details.performance is not None:
|
|
@@ -210,16 +231,24 @@ class Client:
|
|
|
210
231
|
self._runtime.report("invalid_performance", "context")
|
|
211
232
|
base = otel_context.get_current()
|
|
212
233
|
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)
|
|
213
242
|
if state is None:
|
|
214
243
|
external = trace.get_current_span(base).get_span_context()
|
|
215
244
|
links = [Link(clean_context(external))] if external.is_valid else []
|
|
216
245
|
state = RequestState(links=links)
|
|
217
246
|
# Its own managed scope: an unrelated caller's trace is a link, never the parent.
|
|
218
247
|
base = otel_context.set_value(self._runtime.state_key, state, otel_context.Context())
|
|
219
|
-
mark = Mark(name=name, details=details, performance=performance, identity=identity)
|
|
248
|
+
mark = Mark(name=name, details=details, performance=performance, identity=identity, step=step, mcp=mcp)
|
|
220
249
|
marked = otel_context.set_value(self._runtime.mark_key, mark, base)
|
|
221
250
|
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)
|
|
251
|
+
span = self._tracer.start_span(name, context=marked, links=continued + ([] if parented else state.links))
|
|
223
252
|
if not span.is_recording():
|
|
224
253
|
self._runtime.report("entry_not_recording", "traces")
|
|
225
254
|
return span, trace.set_span_in_context(span, base)
|
|
@@ -278,6 +307,16 @@ class Client:
|
|
|
278
307
|
|
|
279
308
|
return AgentrailWSGIMiddleware(app, client=self)
|
|
280
309
|
|
|
310
|
+
def _keyed_hash(self, value: str) -> str:
|
|
311
|
+
"""The keyed hash principal IDs use: 32 lowercase hex under the workspace key."""
|
|
312
|
+
return keyed_hash(self._runtime.options.input.hash_key, value)
|
|
313
|
+
|
|
314
|
+
def _payload_room(self) -> bool:
|
|
315
|
+
return self._spans.payload_room()
|
|
316
|
+
|
|
317
|
+
def _report(self, code: CaptureCode, signal: Signal) -> None:
|
|
318
|
+
self._runtime.report(code, signal)
|
|
319
|
+
|
|
281
320
|
def _managed(self) -> bool:
|
|
282
321
|
return not self._closed and not suppressed() and self._runtime.state() is not None
|
|
283
322
|
|
|
@@ -307,6 +346,7 @@ class Client:
|
|
|
307
346
|
remote_context = SpanContext(remote.trace_id, remote.span_id, True, TraceFlags(remote.flags & 1))
|
|
308
347
|
ctx = trace.set_span_in_context(NonRecordingSpan(remote_context), ctx)
|
|
309
348
|
state.location = self._location(request)
|
|
349
|
+
state.cli = cli_attributes(request.headers.get(CLI_HEADER), self._keyed_hash)
|
|
310
350
|
ctx = otel_context.set_value(self._runtime.state_key, state, ctx)
|
|
311
351
|
attributes: Attributes = {
|
|
312
352
|
"http.request.method": request.method,
|
|
@@ -318,6 +358,7 @@ class Client:
|
|
|
318
358
|
span = self._tracer.start_span(
|
|
319
359
|
f"HTTP {request.method}", context=ctx, kind=SpanKind.SERVER, attributes=attributes
|
|
320
360
|
)
|
|
361
|
+
state.entry = span.get_span_context()
|
|
321
362
|
if not span.is_recording():
|
|
322
363
|
self._runtime.report("entry_not_recording", "traces")
|
|
323
364
|
return span, trace.set_span_in_context(span, ctx)
|
agentrail_python/_handoff.py
CHANGED
|
@@ -19,6 +19,10 @@ from ._text import js_json, well_formed
|
|
|
19
19
|
HANDOFF_HEADER = "x-agentrail-trace-handoff"
|
|
20
20
|
# Headers a managed request never forwards as received.
|
|
21
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")
|
|
22
26
|
MAX_AGE_MS = 60_000
|
|
23
27
|
_MAX_SAFE_INTEGER = 9_007_199_254_740_991
|
|
24
28
|
|
agentrail_python/_options.py
CHANGED
|
@@ -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)
|
agentrail_python/_privacy.py
CHANGED
|
@@ -8,6 +8,7 @@ holds these copies.
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
10
|
import math
|
|
11
|
+
import re
|
|
11
12
|
import uuid
|
|
12
13
|
from collections.abc import Mapping
|
|
13
14
|
from dataclasses import dataclass, field
|
|
@@ -30,10 +31,18 @@ from opentelemetry.trace import (
|
|
|
30
31
|
from opentelemetry.util.types import AttributeValue
|
|
31
32
|
|
|
32
33
|
from ._handoff import valid_marker
|
|
33
|
-
from ._runtime import Attributes, Runtime, SpanMeta
|
|
34
|
+
from ._runtime import Attributes, McpEvidence, RequestFacts, Runtime, SpanMeta
|
|
34
35
|
from ._text import bounded, js_json, utf16_length, valid_text
|
|
35
36
|
|
|
36
37
|
_LIMIT = 4096
|
|
38
|
+
_HEADER_NAME = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+")
|
|
39
|
+
"""An HTTP token (RFC 9110), as a header name is written."""
|
|
40
|
+
REQUEST_PAYLOAD = "agentrail.mcp.request.payload"
|
|
41
|
+
RESPONSE_PAYLOAD = "agentrail.mcp.response.payload"
|
|
42
|
+
REQUEST_TRUNCATED = "agentrail.mcp.request.truncated"
|
|
43
|
+
RESPONSE_TRUNCATED = "agentrail.mcp.response.truncated"
|
|
44
|
+
_PAYLOADS = frozenset((REQUEST_PAYLOAD, RESPONSE_PAYLOAD))
|
|
45
|
+
_PAYLOAD_KEYS = _PAYLOADS | {REQUEST_TRUNCATED, RESPONSE_TRUNCATED}
|
|
37
46
|
|
|
38
47
|
|
|
39
48
|
def clean_context(context: SpanContext) -> SpanContext:
|
|
@@ -116,31 +125,41 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
|
|
|
116
125
|
# one per message) is supporting work, not a second entry.
|
|
117
126
|
kind = SpanKind.INTERNAL
|
|
118
127
|
mark = meta.mark
|
|
119
|
-
entry = mark is not None or kind in (SpanKind.SERVER, SpanKind.CONSUMER)
|
|
128
|
+
entry = (mark is not None and mark.step) or kind in (SpanKind.SERVER, SpanKind.CONSUMER)
|
|
120
129
|
if entry:
|
|
121
130
|
identity = mark.identity if mark is not None and mark.identity is not None else meta.state.principal()
|
|
122
131
|
attributes.update(identity)
|
|
123
132
|
attributes.update(meta.state.location)
|
|
124
133
|
if kind == SpanKind.SERVER:
|
|
125
134
|
attributes["agentrail.ingress.verified"] = meta.state.verified
|
|
135
|
+
# Only the request's own entry span: a CLI's header says nothing of the
|
|
136
|
+
# calls this server makes while answering it, nor of another server span.
|
|
137
|
+
this = span.get_span_context()
|
|
138
|
+
if this is not None and meta.state.entry is not None and this.span_id == meta.state.entry.span_id:
|
|
139
|
+
attributes.update(meta.state.cli)
|
|
126
140
|
method = attributes.get("http.request.method")
|
|
127
141
|
name = f"HTTP {method}" if isinstance(method, str) else "backend.operation"
|
|
128
142
|
if mark is not None:
|
|
129
143
|
name = mark.name
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
144
|
+
if mark.step:
|
|
145
|
+
attributes["agentrail.step"] = True
|
|
146
|
+
attributes["agentrail.step.surface"] = mark.details.surface
|
|
147
|
+
attributes["agentrail.step.kind"] = mark.details.kind
|
|
133
148
|
if mark.performance is not None:
|
|
134
149
|
attributes.update(mark.performance)
|
|
135
150
|
mcp = mark.details.mcp
|
|
136
151
|
if mcp is not None:
|
|
152
|
+
# Resource URIs have no standard name attribute.
|
|
137
153
|
for key, value, limit in (
|
|
138
|
-
("
|
|
139
|
-
("
|
|
140
|
-
("
|
|
154
|
+
("mcp.method.name", mcp.method, 128),
|
|
155
|
+
("gen_ai.tool.name", mcp.name if mcp.method == "tools/call" else None, 256),
|
|
156
|
+
("gen_ai.prompt.name", mcp.name if mcp.method == "prompts/get" else None, 256),
|
|
141
157
|
):
|
|
142
158
|
if value:
|
|
143
159
|
attributes[key] = bounded(value, limit)
|
|
160
|
+
_client_details(attributes, mcp.client, mcp.client_version, mcp.protocol)
|
|
161
|
+
if mark.mcp is not None:
|
|
162
|
+
_mcp_attributes(attributes, mark.mcp)
|
|
144
163
|
links = [Link(clean_context(link.context)) for link in span.links]
|
|
145
164
|
if kind == SpanKind.SERVER:
|
|
146
165
|
links.extend(Link(clean_context(link.context)) for link in meta.state.links)
|
|
@@ -162,6 +181,137 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
|
|
|
162
181
|
)
|
|
163
182
|
|
|
164
183
|
|
|
184
|
+
def _client_details(attributes: Attributes, client: str | None, version: str | None, protocol: str | None) -> None:
|
|
185
|
+
for key, value, limit in (
|
|
186
|
+
("agentrail.mcp.client.name", client, 128),
|
|
187
|
+
("agentrail.mcp.client.version", version, 128),
|
|
188
|
+
("agentrail.mcp.protocol.version", protocol, 64),
|
|
189
|
+
):
|
|
190
|
+
if value:
|
|
191
|
+
attributes[key] = bounded(value, limit)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _mcp_attributes(attributes: Attributes, evidence: McpEvidence) -> None:
|
|
195
|
+
"""The contract's ``otlp.mcpAttributes``. Payloads are exempt from the text limit."""
|
|
196
|
+
attributes["agentrail.mcp.layer"] = evidence.layer
|
|
197
|
+
if evidence.method is not None:
|
|
198
|
+
attributes["agentrail.mcp.method"] = evidence.method
|
|
199
|
+
_client_details(attributes, evidence.client, evidence.client_version, evidence.protocol)
|
|
200
|
+
values = (
|
|
201
|
+
("agentrail.mcp.session.id_hash", evidence.session_hash),
|
|
202
|
+
("agentrail.mcp.request.bytes", evidence.request_bytes),
|
|
203
|
+
("agentrail.mcp.response.bytes", evidence.response_bytes),
|
|
204
|
+
("agentrail.mcp.jsonrpc.error_code", evidence.error_code),
|
|
205
|
+
(REQUEST_PAYLOAD, evidence.request_payload),
|
|
206
|
+
(RESPONSE_PAYLOAD, evidence.response_payload),
|
|
207
|
+
)
|
|
208
|
+
for key, value in values:
|
|
209
|
+
if value is not None:
|
|
210
|
+
attributes[key] = value
|
|
211
|
+
for key, flag in (
|
|
212
|
+
("agentrail.mcp.result.is_error", evidence.is_error),
|
|
213
|
+
(REQUEST_TRUNCATED, evidence.request_truncated and evidence.request_payload is not None),
|
|
214
|
+
(RESPONSE_TRUNCATED, evidence.response_truncated and evidence.response_payload is not None),
|
|
215
|
+
):
|
|
216
|
+
if flag:
|
|
217
|
+
attributes[key] = True
|
|
218
|
+
if evidence.request is not None:
|
|
219
|
+
_request_facts(attributes, evidence.request)
|
|
220
|
+
if evidence.jsonrpc_id is not None:
|
|
221
|
+
attributes["agentrail.mcp.jsonrpc.id"] = evidence.jsonrpc_id
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _request_facts(attributes: Attributes, facts: RequestFacts) -> None:
|
|
225
|
+
"""The contract's ``otlp.mcpSpans.requestFacts``: the HTTP request that carried the message.
|
|
226
|
+
|
|
227
|
+
No HTTP status: a step can end before its answer's status is written (a JSON
|
|
228
|
+
response is written after it), so only the HTTP entry span carries one.
|
|
229
|
+
"""
|
|
230
|
+
attributes["http.request.method"] = bounded(facts.method, _LIMIT)
|
|
231
|
+
url = sanitized_url(facts.url)
|
|
232
|
+
if url is not None:
|
|
233
|
+
attributes["url.full"] = url
|
|
234
|
+
for key, value in (
|
|
235
|
+
("user_agent.original", facts.user_agent),
|
|
236
|
+
("agentrail.http.request.accept", facts.accept),
|
|
237
|
+
("agentrail.http.request.accept_encoding", facts.accept_encoding),
|
|
238
|
+
):
|
|
239
|
+
if value:
|
|
240
|
+
attributes[key] = bounded(value, _LIMIT)
|
|
241
|
+
names = _header_names(facts.header_names)
|
|
242
|
+
if names is not None:
|
|
243
|
+
attributes["agentrail.http.request.header_names"] = names
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _header_names(names: tuple[str, ...]) -> str | None:
|
|
247
|
+
"""Comma-joined, whole names within the text limit; None when any is no HTTP token.
|
|
248
|
+
|
|
249
|
+
A "name" that is no token holds a value, or part of one (a lax server's), so
|
|
250
|
+
no part of the list is sent: the collector would take none of it either.
|
|
251
|
+
"""
|
|
252
|
+
if not names or not all(_HEADER_NAME.fullmatch(name) for name in names):
|
|
253
|
+
return None
|
|
254
|
+
kept: list[str] = []
|
|
255
|
+
length = -1
|
|
256
|
+
for name in names:
|
|
257
|
+
length += len(name) + 1 # a token is ASCII: one UTF-16 unit a character
|
|
258
|
+
if length > _LIMIT:
|
|
259
|
+
break
|
|
260
|
+
kept.append(name)
|
|
261
|
+
return ",".join(kept)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _utf8_length(value: str) -> int:
|
|
265
|
+
return len(value.encode("utf-8", "surrogatepass"))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def span_weight(span: ReadableSpan) -> tuple[int, int]:
|
|
269
|
+
"""An over-estimate of the span's OTLP protobuf size, and its payload bytes."""
|
|
270
|
+
size = 256 + _utf8_length(span.name) + 64 * len(span.links)
|
|
271
|
+
payload = 0
|
|
272
|
+
for key, value in (span.attributes or {}).items():
|
|
273
|
+
size += 16 + len(key)
|
|
274
|
+
if isinstance(value, str):
|
|
275
|
+
length = _utf8_length(value)
|
|
276
|
+
size += length
|
|
277
|
+
if key in _PAYLOADS:
|
|
278
|
+
payload += length
|
|
279
|
+
else:
|
|
280
|
+
size += 16
|
|
281
|
+
return size, payload
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def log_weight(record: ReadableLogRecord) -> tuple[int, int]:
|
|
285
|
+
"""An over-estimate of the record's OTLP protobuf size; logs carry no payloads."""
|
|
286
|
+
log = record.log_record
|
|
287
|
+
body = log.body
|
|
288
|
+
size = 256 + (_utf8_length(body) if isinstance(body, str) else 0)
|
|
289
|
+
size += sum(
|
|
290
|
+
16 + len(key) + (_utf8_length(value) if isinstance(value, str) else 16)
|
|
291
|
+
for key, value in (log.attributes or {}).items()
|
|
292
|
+
)
|
|
293
|
+
return size, 0
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def without_payloads(span: ReadableSpan) -> ReadableSpan:
|
|
297
|
+
"""The same sanitized copy without its payload attributes."""
|
|
298
|
+
attributes = {key: value for key, value in (span.attributes or {}).items() if key not in _PAYLOAD_KEYS}
|
|
299
|
+
return ReadableSpan(
|
|
300
|
+
name=span.name,
|
|
301
|
+
context=span.get_span_context(),
|
|
302
|
+
parent=span.parent,
|
|
303
|
+
resource=span.resource,
|
|
304
|
+
attributes=attributes,
|
|
305
|
+
events=(),
|
|
306
|
+
links=span.links,
|
|
307
|
+
kind=span.kind,
|
|
308
|
+
status=span.status,
|
|
309
|
+
start_time=span.start_time,
|
|
310
|
+
end_time=span.end_time,
|
|
311
|
+
instrumentation_scope=span.instrumentation_scope,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
|
|
165
315
|
def _scalar(value: object) -> str | int | float | bool | type[_Skip] | None:
|
|
166
316
|
if value is None or isinstance(value, bool):
|
|
167
317
|
return value
|
agentrail_python/_processors.py
CHANGED
|
@@ -34,7 +34,7 @@ from opentelemetry.util.types import Attributes
|
|
|
34
34
|
from ._client import Client
|
|
35
35
|
from ._handoff import OWNED_HEADERS
|
|
36
36
|
from ._options import ConfigurationError, Options, resolve
|
|
37
|
-
from ._privacy import StructuredLog, copy_log, copy_span
|
|
37
|
+
from ._privacy import StructuredLog, copy_log, copy_span, log_weight, span_weight, without_payloads
|
|
38
38
|
from ._queue import ExportQueue
|
|
39
39
|
from ._runtime import Runtime, SpanMeta
|
|
40
40
|
from ._suppression import suppressed
|
|
@@ -229,6 +229,8 @@ class Processors:
|
|
|
229
229
|
lambda batch: _export_spans(span_exporter, batch),
|
|
230
230
|
lambda code, count: runtime.report(code, "traces", count),
|
|
231
231
|
span_exporter.shutdown,
|
|
232
|
+
weigh=span_weight,
|
|
233
|
+
strip=without_payloads,
|
|
232
234
|
)
|
|
233
235
|
self.logs: ExportQueue[ReadableLogRecord] = ExportQueue(
|
|
234
236
|
"logs",
|
|
@@ -236,6 +238,7 @@ class Processors:
|
|
|
236
238
|
lambda batch: _export_logs(log_exporter, batch),
|
|
237
239
|
lambda code, count: runtime.report(code, "logs", count),
|
|
238
240
|
log_exporter.shutdown,
|
|
241
|
+
weigh=log_weight,
|
|
239
242
|
)
|
|
240
243
|
self.span_processor: SpanProcessor = _SpanProcessor(runtime, self.spans)
|
|
241
244
|
self.log_processor: LogRecordProcessor = _LogProcessor(runtime, self.logs)
|