agentrail-python 0.4.1__py3-none-any.whl → 0.5.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.
@@ -32,9 +32,21 @@ from ._options import (
32
32
  from ._privacy import StructuredLog
33
33
  from ._queue import QueueStats
34
34
  from ._version import VERSION
35
+ from .trust import (
36
+ DEFAULT_TRUST_ENDPOINT,
37
+ TrustClient,
38
+ TrustClientConfigError,
39
+ create_trust_client,
40
+ effective_trust_action,
41
+ extract_trust_request,
42
+ format_agent_trust_response,
43
+ incoming_request,
44
+ verify_trust_webhook,
45
+ )
35
46
 
36
47
  __version__ = VERSION
37
48
  __all__ = [
49
+ "DEFAULT_TRUST_ENDPOINT",
38
50
  "VERSION",
39
51
  "AuthorizedOperation",
40
52
  "CaptureCode",
@@ -60,6 +72,14 @@ __all__ = [
60
72
  "QueueStats",
61
73
  "StructuredLog",
62
74
  "Surface",
75
+ "TrustClient",
76
+ "TrustClientConfigError",
63
77
  "VerifiedIdentity",
78
+ "create_trust_client",
79
+ "effective_trust_action",
80
+ "extract_trust_request",
81
+ "format_agent_trust_response",
82
+ "incoming_request",
64
83
  "init",
84
+ "verify_trust_webhook",
65
85
  ]
agentrail_python/_cli.py CHANGED
@@ -21,6 +21,7 @@ from ._runtime import Attributes
21
21
  CLI_HEADER = "x-agentrail-cli" # also in ``_handoff.AGENTRAIL_HEADERS``
22
22
 
23
23
  _TEXT = re.compile(r"[\x20-\x7e]{1,64}")
24
+ _MACHINE_ID = re.compile(r"[0-9a-f]{64}")
24
25
  _COMMAND = re.compile(r"[\x20-\x7e]{1,128}")
25
26
  _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
27
  _SESSION = re.compile(r"[0-9a-f]{32}")
@@ -47,6 +48,7 @@ class CliHeader:
47
48
  agent_version: str | None = None
48
49
  evidence: tuple[str, ...] | None = None
49
50
  command: str | None = None
51
+ machine_id: str | None = None
50
52
 
51
53
 
52
54
  class _Unread(Exception):
@@ -108,7 +110,7 @@ def _evidence(members: Mapping[str, object]) -> tuple[str, ...] | None:
108
110
  return tuple(names)
109
111
 
110
112
 
111
- def read_cli_header(value: str | None) -> CliHeader | None:
113
+ def read_cli_header(value: str | None, *, trust: bool = False) -> CliHeader | None:
112
114
  """What the header says, or None for none, or one that is not a CLI header of
113
115
  any version: not a Dictionary, a member missing, one outside the contract's
114
116
  rules, or one given twice, as two header lines a server joined are. Any ``v``
@@ -141,6 +143,7 @@ def read_cli_header(value: str | None) -> CliHeader | None:
141
143
  agent=_optional(fields, "agent", _AGENT),
142
144
  agent_version=_optional(fields, "agentv", _TEXT),
143
145
  evidence=_evidence(fields),
146
+ machine_id=_optional(fields, "mid", _MACHINE_ID) if trust else None,
144
147
  command=_optional(fields, "cmd", _COMMAND),
145
148
  )
146
149
  except _Unread:
@@ -25,6 +25,8 @@ LOCATION_SOURCES: frozenset[str] = frozenset(("dbip", "cloudflare", "vercel", "s
25
25
  CaptureCode = Literal[
26
26
  "queue_full",
27
27
  "export_failed",
28
+ "trust_unavailable",
29
+ "trust_invalid_response",
28
30
  "deadline",
29
31
  "closed",
30
32
  "handoff_refused",
@@ -36,7 +38,7 @@ CaptureCode = Literal[
36
38
  "payload_redact_failed",
37
39
  "payload_budget",
38
40
  ]
39
- Signal = Literal["traces", "logs", "context"]
41
+ Signal = Literal["traces", "logs", "context", "trust"]
40
42
 
41
43
 
42
44
  class ConfigurationError(ValueError):
@@ -231,17 +233,20 @@ class Resolved:
231
233
  include_fields: tuple[str, ...]
232
234
 
233
235
  def report(self, error: CaptureError) -> None:
234
- from ._suppression import reporting
236
+ report_capture_error(self.input.on_error, error)
235
237
 
236
- with reporting():
237
- callback = self.input.on_error
238
- if callback is None:
239
- print(error, file=sys.stderr)
240
- return
241
- try:
242
- callback(error)
243
- except Exception as callback_error: # noqa: BLE001 - an application callback may raise anything
244
- print("Agentrail on_error callback failed:", repr(callback_error), error, file=sys.stderr)
238
+
239
+ def report_capture_error(callback: Callable[[CaptureError], None] | None, error: CaptureError) -> None:
240
+ from ._suppression import reporting
241
+
242
+ with reporting():
243
+ if callback is None:
244
+ print(error, file=sys.stderr)
245
+ return
246
+ try:
247
+ callback(error)
248
+ except Exception as callback_error: # noqa: BLE001 - an application callback may raise anything
249
+ print("Agentrail on_error callback failed:", repr(callback_error), error, file=sys.stderr)
245
250
 
246
251
 
247
252
  def origin_of(parts: SplitResult) -> str:
@@ -256,7 +261,7 @@ def origin_of(parts: SplitResult) -> str:
256
261
  return f"{scheme}://{host}"
257
262
 
258
263
 
259
- def _url(value: str) -> SplitResult | None:
264
+ def http_endpoint(value: str) -> SplitResult | None:
260
265
  try:
261
266
  parts = urlsplit(value)
262
267
  _ = parts.port # raises for an invalid port
@@ -272,7 +277,7 @@ def _url(value: str) -> SplitResult | None:
272
277
 
273
278
 
274
279
  def resolve(options: Options) -> Resolved:
275
- endpoint = _url(options.collector.endpoint)
280
+ endpoint = http_endpoint(options.collector.endpoint)
276
281
  if endpoint is None:
277
282
  raise ConfigurationError("Use an absolute http(s) collector base URL without credentials, query or fragment.")
278
283
  secret = options.collector.secret
@@ -306,7 +311,7 @@ def resolve(options: Options) -> Resolved:
306
311
  )
307
312
  origins: set[str] = set()
308
313
  for raw in options.outbound_origins:
309
- parts = _url(raw)
314
+ parts = http_endpoint(raw)
310
315
  if parts is None or parts.path != "" or origin_of(parts) != raw:
311
316
  raise ConfigurationError("outbound_origins must contain exact canonical http(s) origins.")
312
317
  origins.add(raw)
@@ -1,2 +1,2 @@
1
1
  # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
- VERSION = "0.4.1"
2
+ VERSION = "0.5.0"
agentrail_python/mcp.py CHANGED
@@ -59,7 +59,13 @@ from typing import TYPE_CHECKING, Any, TypeVar, cast
59
59
 
60
60
  from mcp.server.mcpserver import Context
61
61
  from mcp.shared.exceptions import MCPError
62
- from mcp_types import CLIENT_INFO_META_KEY, INTERNAL_ERROR, INVALID_PARAMS, PROTOCOL_VERSION_META_KEY
62
+ from mcp_types import (
63
+ CLIENT_CAPABILITIES_META_KEY,
64
+ CLIENT_INFO_META_KEY,
65
+ INTERNAL_ERROR,
66
+ INVALID_PARAMS,
67
+ PROTOCOL_VERSION_META_KEY,
68
+ )
63
69
  from mcp_types.version import MODERN_PROTOCOL_VERSIONS
64
70
  from opentelemetry import context as otel_context
65
71
  from opentelemetry.trace import Span, SpanContext, StatusCode, TraceFlags
@@ -218,6 +224,45 @@ def _client_details(ctx: Any, method: str, params: Mapping[str, Any] | None) ->
218
224
  return _text(getattr(info, "name", None), 128), _text(getattr(info, "version", None), 128)
219
225
 
220
226
 
227
+ def _capabilities(ctx: Any, method: str, params: Mapping[str, Any] | None) -> tuple[str, ...] | None:
228
+ params = params or {}
229
+ meta = params.get("_meta")
230
+ if method == "initialize":
231
+ value = params.get("capabilities")
232
+ elif isinstance(meta, Mapping) and CLIENT_CAPABILITIES_META_KEY in meta:
233
+ value = cast(Mapping[str, object], meta)[CLIENT_CAPABILITIES_META_KEY]
234
+ else:
235
+ client = getattr(getattr(ctx, "session", None), "client_params", None)
236
+ value = getattr(client, "capabilities", None)
237
+ if isinstance(value, BaseModel):
238
+ value = value.model_dump(by_alias=True, exclude_none=True)
239
+ if not isinstance(value, Mapping):
240
+ return None
241
+ return tuple(
242
+ sorted(
243
+ k
244
+ for k in cast(Mapping[object, object], value)
245
+ if isinstance(k, str) and re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]{0,63}", k)
246
+ )[:50]
247
+ )
248
+
249
+
250
+ def mcp_trust_request(context: Context[Any, Any]) -> dict[str, Any]:
251
+ """Checkpoint request facts from the current MCP handler's Context."""
252
+ ctx = context.request_context
253
+ protocol = _carried_protocol(ctx, ctx.method, ctx.params)
254
+ if not protocol:
255
+ client = getattr(getattr(ctx, "session", None), "client_params", None)
256
+ protocol = _text(getattr(client, "protocol_version", None), 64)
257
+ capabilities = _capabilities(ctx, ctx.method, ctx.params)
258
+ facts: dict[str, Any] = {}
259
+ if protocol:
260
+ facts["mcpProtocolVersion"] = protocol
261
+ if capabilities is not None:
262
+ facts["mcpCapabilities"] = list(capabilities)
263
+ return facts
264
+
265
+
221
266
  def _carried_protocol(ctx: Any, method: str, params: Mapping[str, Any] | None) -> str | None:
222
267
  """The protocol version the message itself carried, never the negotiated one."""
223
268
  if method == "initialize":
@@ -0,0 +1,461 @@
1
+ # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
+ """Server-side Actor Trust checkpoints and webhook authentication."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hmac
7
+ import ipaddress
8
+ import json
9
+ import math
10
+ import re
11
+ import time
12
+ from collections.abc import Callable, Mapping, Sequence
13
+ from types import TracebackType
14
+ from typing import Any, Literal, cast
15
+ from urllib.parse import parse_qs
16
+
17
+ import requests
18
+
19
+ from ._cli import read_cli_header
20
+ from ._options import CaptureCode, CaptureError, http_endpoint, report_capture_error
21
+ from ._suppression import reporting
22
+
23
+ DEFAULT_TRUST_ENDPOINT = "https://api.agentrail.co"
24
+
25
+ _MODES = frozenset({"active", "shadow"})
26
+ _ACTIONS = frozenset(
27
+ {
28
+ "allow",
29
+ "allow_sandbox",
30
+ "allow_with_owner_invite",
31
+ "require_owner_claim",
32
+ "step_up",
33
+ "withhold_free_tier",
34
+ "block",
35
+ }
36
+ )
37
+ _ACTOR_CLASSES = frozenset({"human", "delegated_agent", "autonomous_agent", "crawler", "spoofed", "unknown"})
38
+ _ACCOUNTABILITIES = frozenset({"verified_operator", "claimed_owner", "anonymous_agent", "none"})
39
+ _DISPOSITIONS = frozenset(
40
+ {
41
+ "welcome_delegated_agent",
42
+ "welcome_evaluating_agent",
43
+ "crawler",
44
+ "suspicious_scraper_or_prober",
45
+ "malicious_spoofer",
46
+ "unknown",
47
+ }
48
+ )
49
+ _RISK_LEVELS = frozenset({"low", "medium", "high", "critical"})
50
+ _CONFIDENCES = frozenset({"low", "medium", "high"})
51
+ _MAX_SAFE_INT = 9_007_199_254_740_991
52
+ _CLI_STARTED_BY = {"agent": "agent", "ci": "ci", "interactive": "terminal", "non-interactive": "script"}
53
+
54
+
55
+ def _non_empty_str(value: object) -> bool:
56
+ return type(value) is str and len(value) > 0
57
+
58
+
59
+ def _strict_int(value: object, low: int, high: int) -> bool:
60
+ return type(value) is int and low <= value <= high
61
+
62
+
63
+ def _valid_rule(value: object) -> bool:
64
+ if not isinstance(value, dict):
65
+ return False
66
+ rule = cast(dict[str, object], value)
67
+ return (
68
+ _non_empty_str(rule.get("ruleId"))
69
+ and _non_empty_str(rule.get("ruleName"))
70
+ and rule.get("mode") in _MODES
71
+ and _strict_int(rule.get("rung"), 1, 3)
72
+ and rule.get("recommendedAction") in _ACTIONS
73
+ )
74
+
75
+
76
+ def _valid_reason(value: object) -> bool:
77
+ if not isinstance(value, dict):
78
+ return False
79
+ reason = cast(dict[str, object], value)
80
+ return _non_empty_str(reason.get("signal")) and _non_empty_str(reason.get("summary"))
81
+
82
+
83
+ def _parse_verdict(raw: bytes) -> dict[str, Any] | None:
84
+ try:
85
+ parsed: object = json.loads(raw)
86
+ except (ValueError, UnicodeDecodeError):
87
+ return None
88
+ if not isinstance(parsed, dict):
89
+ return None
90
+ body = cast(dict[str, Any], parsed)
91
+ signals = body.get("signals")
92
+ reasons = body.get("reasons")
93
+ matched_rule = body.get("matchedRule")
94
+ shadow_matches = body.get("shadowRuleMatches")
95
+ cluster = body.get("cluster")
96
+ p_agent = body.get("pAgent")
97
+ if not (
98
+ _non_empty_str(body.get("checkpointId"))
99
+ and body.get("mode") in _MODES
100
+ and type(body.get("enforced")) is bool
101
+ and body.get("actorClass") in _ACTOR_CLASSES
102
+ and body.get("accountability") in _ACCOUNTABILITIES
103
+ and body.get("behavioralDisposition") in _DISPOSITIONS
104
+ and _strict_int(body.get("rung"), 1, 3)
105
+ and body.get("riskLevel") in _RISK_LEVELS
106
+ and body.get("confidence") in _CONFIDENCES
107
+ and body.get("recommendedAction") in _ACTIONS
108
+ and isinstance(signals, list)
109
+ and all(_non_empty_str(item) for item in cast(list[object], signals))
110
+ and isinstance(reasons, list)
111
+ and all(_valid_reason(item) for item in cast(list[object], reasons))
112
+ and "matchedRule" in body
113
+ and (matched_rule is None or _valid_rule(matched_rule))
114
+ and isinstance(shadow_matches, list)
115
+ and all(_valid_rule(item) for item in cast(list[object], shadow_matches))
116
+ and isinstance(cluster, dict)
117
+ and _non_empty_str(body.get("engineVersion"))
118
+ ):
119
+ return None
120
+ cluster_dict = cast(dict[str, object], cluster)
121
+ primary_id = cluster_dict.get("primaryClusterId")
122
+ if not (
123
+ "primaryClusterId" in cluster_dict
124
+ and (primary_id is None or _non_empty_str(primary_id))
125
+ and _strict_int(cluster_dict.get("linkedAccounts24h"), 0, _MAX_SAFE_INT)
126
+ ):
127
+ return None
128
+ if p_agent is not None and (
129
+ type(p_agent) not in (int, float) or not math.isfinite(p_agent) or not 0 <= p_agent <= 1
130
+ ):
131
+ return None
132
+ return body
133
+
134
+
135
+ def _degraded(on_error: Callable[[CaptureError], None] | None, code: CaptureCode) -> dict[str, Any]:
136
+ report_capture_error(on_error, CaptureError(code, "trust", 1))
137
+ return dict(
138
+ degraded=True,
139
+ mode="active",
140
+ enforced=False,
141
+ actorClass="unknown",
142
+ accountability="none",
143
+ behavioralDisposition="unknown",
144
+ rung=1,
145
+ riskLevel="low",
146
+ confidence="low",
147
+ recommendedAction="allow",
148
+ signals=[],
149
+ reasons=[],
150
+ matchedRule=None,
151
+ shadowRuleMatches=[],
152
+ cluster={"primaryClusterId": None, "linkedAccounts24h": 0},
153
+ engineVersion="degraded",
154
+ )
155
+
156
+
157
+ def _text(value: object, limit: int) -> str | None:
158
+ if isinstance(value, bytes):
159
+ value = value.decode("latin-1")
160
+ if isinstance(value, str):
161
+ value = value.strip()
162
+ if value and len(value) <= limit and value.isprintable():
163
+ return value
164
+ return None
165
+
166
+
167
+ def extract_trust_request(
168
+ incoming_request: Any,
169
+ *,
170
+ trusted_proxy_headers: bool = False,
171
+ trust_peer_address: bool = False,
172
+ ip: str | None = None,
173
+ ) -> dict[str, Any]:
174
+ """Extract checkpoint fields from an ASGI scope, WSGI environ or framework request.
175
+
176
+ Client IP headers are read only when ``trusted_proxy_headers=True``. The TCP
177
+ peer address (``REMOTE_ADDR`` / ASGI ``client``) is read only when
178
+ ``trust_peer_address=True`` (safe only when no reverse proxy sits in front
179
+ of the app). Prefer passing an explicit ``ip`` resolved by your framework.
180
+ """
181
+ raw = getattr(
182
+ incoming_request,
183
+ "scope",
184
+ getattr(incoming_request, "environ", getattr(incoming_request, "META", incoming_request)),
185
+ )
186
+ if not isinstance(raw, Mapping):
187
+ raise TypeError("Expected a framework request, WSGI environ or ASGI scope")
188
+ scope = cast(Mapping[str, Any], raw)
189
+ if "headers" in scope:
190
+ pairs = scope["headers"]
191
+ client = scope.get("client")
192
+ peer = cast(Sequence[object], client)[0] if isinstance(client, (list, tuple)) and client else None
193
+ query = scope.get("query_string", b"")
194
+ else:
195
+ pairs = [(k[5:].replace("_", "-"), v) for k, v in scope.items() if k.startswith("HTTP_")]
196
+ pairs.extend((k.replace("_", "-"), scope[k]) for k in ("CONTENT_TYPE", "CONTENT_LENGTH") if k in scope)
197
+ peer = scope.get("REMOTE_ADDR")
198
+ query = scope.get("QUERY_STRING", "")
199
+ headers: dict[str, str] = {}
200
+ names: list[str] = []
201
+ for key, raw_value in pairs:
202
+ name = _text(key, 128)
203
+ if name and re.fullmatch(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+", name):
204
+ name = name.lower()
205
+ names.append(name)
206
+ value = raw_value.decode("latin-1") if isinstance(raw_value, bytes) else raw_value
207
+ if isinstance(value, str):
208
+ if name == "x-agentrail-cli" and name in headers:
209
+ headers[name] = ""
210
+ else:
211
+ headers.setdefault(name, value)
212
+ facts: dict[str, Any] = {}
213
+ if names:
214
+ facts["headerNames"] = names[:100]
215
+ forwarded = (
216
+ (headers.get("cf-connecting-ip"), headers.get("x-forwarded-for", "").split(",")[0], headers.get("x-real-ip"))
217
+ if trusted_proxy_headers
218
+ else ()
219
+ )
220
+ peer_candidates = (peer,) if trust_peer_address else ()
221
+ for candidate in (ip,) if ip is not None else (*forwarded, *peer_candidates):
222
+ address = _text(candidate, 64)
223
+ if address and "%" not in address:
224
+ try:
225
+ facts["ip"] = str(ipaddress.ip_address(address))
226
+ except ValueError:
227
+ continue
228
+ break
229
+ for header, field, limit in (("user-agent", "userAgent", 1024), ("mcp-protocol-version", "mcpProtocolVersion", 64)):
230
+ if value := _text(headers.get(header), limit):
231
+ facts[field] = value
232
+ cli = read_cli_header(headers.get("x-agentrail-cli"), trust=True)
233
+ if cli:
234
+ facts["cliStartedBy"] = _CLI_STARTED_BY[cli.mode]
235
+ if cli.machine_id:
236
+ facts["cliMachineId"] = cli.machine_id
237
+ result: dict[str, Any] = {"request": facts} if facts else {}
238
+ for cookie in headers.get("cookie", "").split(";"):
239
+ name, _, value = cookie.strip().partition("=")
240
+ if name == "agentrail_at" and (token := _text(value, 4096)):
241
+ result["actorToken"] = token
242
+ break
243
+ params = parse_qs(query.decode("latin-1") if isinstance(query, bytes) else query)
244
+ tokens = [
245
+ headers.get("x-agentrail-self-test"),
246
+ *params.get("agentrail_self_test", [])[:1],
247
+ *params.get("agentrail_test", [])[:1],
248
+ ]
249
+ for value in tokens:
250
+ if token := _text(value, 128):
251
+ result["selfTestToken"] = token
252
+ break
253
+ return result
254
+
255
+
256
+ incoming_request = extract_trust_request
257
+
258
+
259
+ class TrustClientConfigError(ValueError):
260
+ """Invalid server-side credentials or client configuration."""
261
+
262
+ def __init__(self, message: str, status: int | None = None):
263
+ super().__init__(message)
264
+ self.status = status
265
+
266
+
267
+ class TrustClient:
268
+ def __init__(
269
+ self,
270
+ secret_key: str,
271
+ *,
272
+ endpoint: str = DEFAULT_TRUST_ENDPOINT,
273
+ timeout: float = 0.4,
274
+ trusted_proxy_headers: bool = False,
275
+ trust_peer_address: bool = False,
276
+ on_error: Callable[[CaptureError], None] | None = None,
277
+ session: requests.Session | None = None,
278
+ ):
279
+ trimmed_key = secret_key.strip()
280
+ if not trimmed_key:
281
+ raise TrustClientConfigError("Expected a non-empty Agentrail server secret key")
282
+ if http_endpoint(endpoint) is None or timeout <= 0:
283
+ raise TrustClientConfigError("Expected an absolute HTTP(S) endpoint and a positive timeout")
284
+ self._on_error = on_error
285
+ self._secret_key = trimmed_key
286
+ self._url = endpoint.rstrip("/") + "/v1/trust/checkpoints"
287
+ self._timeout = timeout
288
+ self._trusted_proxy_headers = trusted_proxy_headers
289
+ self._trust_peer_address = trust_peer_address
290
+ self._owns_session = session is None
291
+ self._session = session if session is not None else requests.Session()
292
+
293
+ def close(self) -> None:
294
+ if self._owns_session:
295
+ self._session.close()
296
+
297
+ def __enter__(self) -> TrustClient:
298
+ return self
299
+
300
+ def __exit__(
301
+ self,
302
+ _exc_type: type[BaseException] | None,
303
+ _exc: BaseException | None,
304
+ _tb: TracebackType | None,
305
+ ) -> None:
306
+ self.close()
307
+
308
+ def checkpoint(
309
+ self,
310
+ payload: Mapping[str, Any],
311
+ *,
312
+ incoming_request: Any = None,
313
+ trusted_proxy_headers: bool | None = None,
314
+ trust_peer_address: bool | None = None,
315
+ ip: str | None = None,
316
+ mcp_protocol_version: str | None = None,
317
+ mcp_capabilities: Sequence[str] | None = None,
318
+ cli_started_by: Literal["agent", "ci", "terminal", "script"] | None = None,
319
+ cli_machine_id: str | None = None,
320
+ self_test_token: str | None = None,
321
+ ) -> dict[str, Any]:
322
+ body = dict(payload)
323
+ if incoming_request is not None:
324
+ extracted = extract_trust_request(
325
+ incoming_request,
326
+ trusted_proxy_headers=(
327
+ self._trusted_proxy_headers if trusted_proxy_headers is None else trusted_proxy_headers
328
+ ),
329
+ trust_peer_address=self._trust_peer_address if trust_peer_address is None else trust_peer_address,
330
+ ip=ip,
331
+ )
332
+ if facts := extracted.get("request"):
333
+ body["request"] = {**facts, **body.get("request", {})}
334
+ body = {**extracted, **body}
335
+ facts = dict(body.get("request", {}))
336
+ if ip is not None:
337
+ facts["ip"] = ip
338
+ if mcp_protocol_version is not None:
339
+ facts["mcpProtocolVersion"] = mcp_protocol_version
340
+ if mcp_capabilities is not None:
341
+ facts["mcpCapabilities"] = list(mcp_capabilities)
342
+ if cli_started_by is not None:
343
+ facts["cliStartedBy"] = cli_started_by
344
+ if cli_machine_id is not None:
345
+ facts["cliMachineId"] = cli_machine_id
346
+ if facts:
347
+ body["request"] = facts
348
+ if self_test_token is not None:
349
+ body["selfTestToken"] = self_test_token
350
+ try:
351
+ with reporting():
352
+ response = self._session.post(
353
+ self._url,
354
+ json=body,
355
+ headers={"Authorization": f"Bearer {self._secret_key}"},
356
+ timeout=self._timeout,
357
+ allow_redirects=False,
358
+ )
359
+ except requests.RequestException:
360
+ return _degraded(self._on_error, "trust_unavailable")
361
+ if response.status_code in (401, 403):
362
+ raise TrustClientConfigError(f"Server API key refused (HTTP {response.status_code})", response.status_code)
363
+ if response.status_code != 200:
364
+ return _degraded(self._on_error, "trust_unavailable")
365
+ verdict = _parse_verdict(response.content)
366
+ if verdict is None:
367
+ return _degraded(self._on_error, "trust_invalid_response")
368
+ return {**verdict, "degraded": False}
369
+
370
+
371
+ create_trust_client = TrustClient
372
+
373
+
374
+ def effective_trust_action(outcome: Mapping[str, Any]) -> str:
375
+ if not outcome.get("enforced"):
376
+ return "allow"
377
+ return cast(str, outcome["recommendedAction"])
378
+
379
+
380
+ _GUIDANCE: dict[str, tuple[int, str, str]] = {
381
+ "allow_sandbox": (
382
+ 200,
383
+ "sandbox_access_granted",
384
+ "Sandbox access granted. Ask a workspace owner to confirm full access.",
385
+ ),
386
+ "allow_with_owner_invite": (
387
+ 200,
388
+ "owner_confirmation_requested",
389
+ "Access granted while awaiting owner confirmation.",
390
+ ),
391
+ "require_owner_claim": (
392
+ 403,
393
+ "owner_claim_required",
394
+ "A human account owner must claim this agent before continuing.",
395
+ ),
396
+ "step_up": (
397
+ 403,
398
+ "verification_required",
399
+ "Additional account verification is required before completing this action.",
400
+ ),
401
+ "withhold_free_tier": (
402
+ 402,
403
+ "free_tier_withheld",
404
+ "Account created without complimentary credits. Add a payment method or verify ownership to unlock credits.",
405
+ ),
406
+ "block": (403, "access_blocked", "This request cannot be completed automatically."),
407
+ }
408
+
409
+
410
+ def format_agent_trust_response(
411
+ outcome: Mapping[str, Any],
412
+ claim_url: str | None = None,
413
+ *,
414
+ mcp_endpoint: str | None = None,
415
+ docs_url: str | None = None,
416
+ ) -> dict[str, Any] | None:
417
+ action = effective_trust_action(outcome)
418
+ if action == "allow":
419
+ return None
420
+ status, code, message = _GUIDANCE[action]
421
+ if claim_url and action in ("require_owner_claim", "allow_with_owner_invite", "allow_sandbox"):
422
+ message += " Share the claim URL with the account owner."
423
+ body: dict[str, Any] = dict(action=action, code=code, message=message)
424
+ for key, url in (("claimUrl", claim_url), ("mcpEndpoint", mcp_endpoint), ("docsUrl", docs_url)):
425
+ if url:
426
+ body[key] = url
427
+ return {"status": status, "body": body}
428
+
429
+
430
+ def verify_trust_webhook(
431
+ payload: bytes | str,
432
+ signature_header: str | None,
433
+ secrets: str | Sequence[str],
434
+ *,
435
+ tolerance_sec: int = 300,
436
+ now: float | None = None,
437
+ ) -> bool:
438
+ """Authenticate the exact received bytes with every configured rotation secret."""
439
+ timestamps: list[int] = []
440
+ signatures: list[bytes] = []
441
+ for part in (signature_header or "").split(","):
442
+ key, _, value = part.strip().partition("=")
443
+ if key == "t" and re.fullmatch(r"[0-9]{1,16}", value):
444
+ timestamps.append(int(value))
445
+ elif key == "v1" and re.fullmatch(r"[a-fA-F0-9]{64}", value):
446
+ signatures.append(bytes.fromhex(value))
447
+ if (
448
+ len(timestamps) != 1
449
+ or not signatures
450
+ or abs(int(time.time() if now is None else now) - timestamps[0]) > tolerance_sec
451
+ ):
452
+ return False
453
+ raw = payload.encode() if isinstance(payload, str) else payload
454
+ message = str(timestamps[0]).encode("ascii") + b"." + raw
455
+ matched = False
456
+ for secret in (secrets,) if isinstance(secrets, str) else secrets:
457
+ if secret:
458
+ expected = hmac.digest(secret.encode(), message, "sha256")
459
+ for candidate in signatures:
460
+ matched |= hmac.compare_digest(expected, candidate)
461
+ return matched
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentrail-python
3
- Version: 0.4.1
3
+ Version: 0.5.0
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
@@ -157,6 +157,45 @@ records nothing and reports `entry_not_recording` to `on_error`.
157
157
  With `DD_TRACE_OTEL_ENABLED` and `import ddtrace.auto`, import ddtrace before
158
158
  `agentrail_python`, as Datadog asks anyway.
159
159
 
160
+ ### Actor Trust checkpoints
161
+
162
+ Use a server API key at account checkpoints such as signup. The synchronous
163
+ client accepts the checkpoint contract's JSON field names. In an async route,
164
+ run the call in a worker thread (for example with `asyncio.to_thread`).
165
+
166
+ ```python
167
+ trust = ar.create_trust_client(os.environ["AGENTRAIL_SECRET_KEY"])
168
+ outcome = trust.checkpoint(
169
+ {"surface": "api", "checkpoint": "signup", "principalId": account.id},
170
+ incoming_request=request,
171
+ )
172
+ guidance = ar.format_agent_trust_response(outcome, claim_url=claim_url)
173
+ if guidance:
174
+ return JSONResponse(guidance["body"], status_code=guidance["status"])
175
+ ```
176
+
177
+ An ASGI scope, WSGI environ, Starlette/FastAPI, Flask or Django request
178
+ supplies the peer address, user agent, header names, actor cookie and self-test
179
+ marker. Only set `trusted_proxy_headers=True` behind a proxy that overwrites
180
+ the forwarding headers. Pass `ip=` for a client address resolved by your app.
181
+ Values supplied in the checkpoint's `request` dictionary take precedence.
182
+ CLI requests can supply the starter and salted machine proof. For MCP
183
+ handlers, pass `{"request": mcp_trust_request(ctx), ...}` using
184
+ `agentrail_python.mcp.mcp_trust_request`. A caller that already knows the
185
+ facts can pass `mcp_protocol_version`, `mcp_capabilities`, `cli_started_by`,
186
+ `cli_machine_id` and `self_test_token` as checkpoint keyword arguments.
187
+
188
+ `effective_trust_action(outcome)` returns `"allow"` in shadow mode. An
189
+ unavailable service or malformed verdict allows the request to proceed and
190
+ sets `outcome["degraded"]`. Pass `on_error=` to receive the diagnostic.
191
+ HTTP 401 and 403 raise `TrustClientConfigError` with the HTTP status.
192
+
193
+ For webhooks, call `verify_trust_webhook(raw_body, signature_header, secrets)`
194
+ before decoding the body. Pass the exact received bytes and the
195
+ `x-agentrail-trust-signature` value. During the 24-hour rotation window,
196
+ pass both the current and previous secrets, then remove the previous one.
197
+ Each delivery has a five-minute timestamp tolerance.
198
+
160
199
  ### MCP
161
200
 
162
201
  With the official `mcp` SDK, add the middleware first. Each JSON-RPC message
@@ -1,9 +1,9 @@
1
- agentrail_python/__init__.py,sha256=79IEAmVe7F1ZLrWCslxFNs8yxF4pw-JD90QI16Fk84U,1487
2
- agentrail_python/_cli.py,sha256=FkR28lNeezFjjpFu3fxiPGHUJhJqnIN0aK5P_OPLN50,6535
1
+ agentrail_python/__init__.py,sha256=6DLZMiphSzOhkU6OeILRUbdc-WK3PeE4w5lsyvpUC3g,1996
2
+ agentrail_python/_cli.py,sha256=gQjJCmlZkZvFwuxRq8_MFvB1NEwBgrEgD7MgeQnoYHk,6716
3
3
  agentrail_python/_client.py,sha256=oy1J3YZYnVh7eiZdnV2CyWsfk67jkPATWJjTOxIuRg0,16354
4
4
  agentrail_python/_handoff.py,sha256=GAmSz6xhixqMt6_e2IPqYiGX-oCi1rAuuhXPxJfiTyk,7535
5
5
  agentrail_python/_init.py,sha256=mXW2aDJ990x7SYXKj-Olj_t9sSgHeA7_kWzJAe0WFeY,1540
6
- agentrail_python/_options.py,sha256=b5iFkd_SiDs5UB666kY_yQc_w6PSnDffK0IlEHn_2Oc,11403
6
+ agentrail_python/_options.py,sha256=5OPK3EhpGBwdvK93Y4re6zoaCTuTXvb2N0bHywQjQSo,11578
7
7
  agentrail_python/_outbound.py,sha256=GioM9YsvoZSWZD4J6r8Jipp4V4xk7YrLw5f0ddn6WaQ,3587
8
8
  agentrail_python/_performance.py,sha256=d42OslVWBLCXrE4VmUqrQ-V2K_7ntSVOQDOVj5hhx9Q,3228
9
9
  agentrail_python/_privacy.py,sha256=iPpMGxwoMu7Z3bZoRLvMeO47J2Fn4UNMmaxTR9Rmrco,16247
@@ -12,15 +12,16 @@ agentrail_python/_queue.py,sha256=xon0CS4o1qqBC8U67o07yqO9UnkrWw0TswrKDYYGSNQ,12
12
12
  agentrail_python/_runtime.py,sha256=oHuuKj6bfdeJI4VD7ELi5MCA4EI91ZLU6pfD1FFwXkQ,8450
13
13
  agentrail_python/_suppression.py,sha256=v0yZngosDp-4Cg99H4DybJeu5UEcX4-aN1cezPVjd24,1045
14
14
  agentrail_python/_text.py,sha256=VEPWuHFU9O0tovScuG9wLNFc1oRwcnk2Egx7diTfdVc,1681
15
- agentrail_python/_version.py,sha256=O1etTD58ObNAEqowSXbTVFQMu8ZzUkuDK1gdEdyweLg,94
15
+ agentrail_python/_version.py,sha256=vykFfr6fSJ5liTiHqhmSTSmFwNitjTrwGWn4FtEUzP8,94
16
16
  agentrail_python/asgi.py,sha256=rSPh-9xbVjoGOke7WsB4EZRzx6bq3nKAPCq5LYTADgY,4854
17
17
  agentrail_python/httpx.py,sha256=Tbtr8dKZRUcnRG3owOpjxB_OXY-NWemwgV2FIrg-lRM,5763
18
18
  agentrail_python/logging.py,sha256=BWReSqXCSHwN01rU5uUWaFPMmNyReN3xSLLOMjCui9k,2623
19
- agentrail_python/mcp.py,sha256=977SiX4DbhqUfIij_sFdw2JaEZ38l_S44ppChL4OJpY,25109
19
+ agentrail_python/mcp.py,sha256=lYeo6nF-ev-vy53F1c1lqeVQG_x9J4eIQnL4t5UE-SQ,26758
20
20
  agentrail_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
21
  agentrail_python/requests.py,sha256=OAIfA5aEfDB0K-XSKkLAgay-DWog6xqWl2KEQhxMISo,2542
22
+ agentrail_python/trust.py,sha256=FnrCcB3Hz80qhngWeshZT61WBGRvmeOMm6-UEX3dqDw,17043
22
23
  agentrail_python/wsgi.py,sha256=I77b2_UbiM7y63oFKnBRhvrJXF3krClHAkOCQ7L92lM,6301
23
- agentrail_python-0.4.1.dist-info/METADATA,sha256=BoziMHkK2OiyIGw0DKWEwgPmveRqBrOmG0vT89SpGuQ,12389
24
- agentrail_python-0.4.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
- agentrail_python-0.4.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
26
- agentrail_python-0.4.1.dist-info/RECORD,,
24
+ agentrail_python-0.5.0.dist-info/METADATA,sha256=iZ7CTREJZfZukewUIulr5qXpMLtJ76bDYWp0FgBiSdg,14393
25
+ agentrail_python-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
26
+ agentrail_python-0.5.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
27
+ agentrail_python-0.5.0.dist-info/RECORD,,