This repository was archived by the owner on Oct 27, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathfailure_lab.py
More file actions
2456 lines (2215 loc) · 93.3 KB
/
Copy pathfailure_lab.py
File metadata and controls
2456 lines (2215 loc) · 93.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Failure laboratory: the action completed, but the response was lost.
One consequential workflow (a vendor payout), one injected fault (the
downstream executes, then its response is lost on the wire), measured across
three integrations of the same simulated payment rail:
1. the existing integration -- the agent calls the tool directly and sends no
idempotency key;
2. the native-control baseline -- the same direct call, but the agent persists
an idempotency key across the retry and the downstream honors it, with
parameter-conflict detection (the control a correctly built integration
already has);
3. the gateway -- the agent calls through the governed MCP boundary, and the
fault is injected at either hop: between the gateway and the agent, or
between the downstream and the gateway.
The gateway side is the real thing: the real ``UpstreamMcpAdapter`` registered
through ``register_configured_upstream_mcp`` against a real in-process
Streamable HTTP MCP server, with the fault injected below the adapter at the
HTTP transport. A lost response after the durable dispatch claim is therefore
the adapter's own ``UpstreamMcpDeliveryUncertainError``, not a stand-in.
Two rules keep the numbers honest. Downstream effects are counted by a record
the gateway cannot reach (the payment rail's own effects log), never by the
gateway's receipts. Gateway dispatches are counted at the downstream's HTTP
layer, never from the gateway's own attempt rows. Every expectation is
asserted and the process exits non-zero when one breaks, after writing the
failing sequence, versions, configuration, and event history to the run
directory. The report is required to say when the native baseline already
handles the fault, and it does.
Run::
make failure-lab # transcript + report
make failure-lab-check # JSON summary only, same assertions
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import os
import platform
import statistics
import subprocess
import sys
import time
import tomllib
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from importlib import metadata as importlib_metadata
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_OUTPUT_DIR = ROOT / "data" / "failure-lab"
ADMIN_KEY = "failure-lab-admin-key"
# The same throwaway signing seed the other local demos use. Not a secret.
LAB_PRIVATE_KEY_B64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="
UPSTREAM_URL = "http://localhost:9000/mcp"
UPSTREAM_TOOL = "payout.send"
PUBLIC_TOOL = "vendor.payout.send"
# The adapter refuses an empty bearer credential; the rail is in-process and
# never checks it, and it is never written to any artifact.
UPSTREAM_BEARER = "failure-lab-upstream-bearer"
CREDITS_PER_CALL = "5"
CONNECT_TIMEOUT_SECONDS = 5.0
CALL_TIMEOUT_SECONDS = 10.0
DIRECT_CALL_TIMEOUT_SECONDS = 10.0
VENDOR = "Northwind Supply"
AMOUNT_USD = "250.00"
CONFLICT_AMOUNT_USD = "9500.00"
FAULT_NONE = "none"
FAULT_LOST_RESPONSE = "downstream action completed; response lost"
HOP_AGENT_DOWNSTREAM = "agent->downstream"
HOP_AGENT_GATEWAY = "agent->gateway"
HOP_GATEWAY_DOWNSTREAM = "gateway->downstream"
CONFIG_EXISTING = "existing integration (direct call, no idempotency key)"
CONFIG_NATIVE = "native idempotency baseline (direct call, key persisted and honored)"
CONFIG_GATEWAY = "gateway (downstream key not used)"
CONFIG_GATEWAY_NATIVE = "gateway + native idempotency (key forwarded to the downstream)"
PRINT_STEPS = True
# --------------------------------------------------------------------------- #
# Command line and environment (must precede the application import) #
# --------------------------------------------------------------------------- #
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument(
"--json",
action="store_true",
help="Print only the machine-readable summary (report.json) to stdout.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=DEFAULT_OUTPUT_DIR,
help="Parent directory for the run directory (default: data/failure-lab).",
)
parser.add_argument(
"--run-id",
default=None,
help="Run directory name (default: UTC timestamp plus a short suffix).",
)
parser.add_argument(
"--latency-samples",
type=int,
default=5,
help="Fault-free calls per configuration used to measure added latency.",
)
parser.add_argument(
"--assert",
dest="assert_mode",
action="store_true",
help="Compatibility flag: the lab always asserts its expectations.",
)
parser.add_argument(
"--self-check-guards",
action="store_true",
help=(
"Check the target safety fuse against transports it must and must "
"not admit, then exit. Runs no scenarios, makes no calls, and "
"causes no effects."
),
)
return parser.parse_args(argv)
ARGS = parse_args()
RUN_ID = ARGS.run_id or (
datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:6]
)
RUN_DIR = (ARGS.output_dir / RUN_ID).resolve()
GATEWAY_DB = RUN_DIR / "gateway.db"
def require_unused_run_dir() -> None:
"""Refuse a run directory that already holds a run.
The event history and the downstream effects log are append-only, while
the reports are overwritten and the gateway database is deleted. Running
twice into one directory would therefore leave ``effects.jsonl`` holding
two runs' effects, and ``events.jsonl`` two sequences both starting at 1,
beside a ``report.json`` describing only the second — contradictory
evidence of exactly the kind this lab exists not to produce.
The generated run id is unique, so this only fires when ``--run-id``
deliberately names an existing run. Refusing beats truncating: the
artifacts are the product here, and silently destroying a previous run's
evidence is the worse failure.
"""
if not RUN_DIR.exists():
return
existing = sorted(entry.name for entry in RUN_DIR.iterdir())
if not existing:
return
raise SystemExit(
f"failure-lab: {RUN_DIR} already holds a run "
f"({', '.join(existing[:6])}{'…' if len(existing) > 6 else ''}).\n"
"Two runs in one directory would leave the saved effects and event "
"history disagreeing with the report, so the lab will not append to "
"them. Pass a different --run-id, or remove that directory first."
)
def configure_environment() -> None:
"""Lab-safe defaults: strict trust mode, throwaway SQLite, throwaway seed."""
require_unused_run_dir()
RUN_DIR.mkdir(parents=True, exist_ok=True)
os.environ["DATABASE_URL"] = f"sqlite+aiosqlite:///{GATEWAY_DB}"
os.environ["VALID_API_KEYS"] = ADMIN_KEY
os.environ["ENVIRONMENT"] = "local"
os.environ["TRUST_MODE_ENABLED"] = "true"
os.environ["ALLOW_LEGACY_UNPERMITTED_MCP"] = "false"
os.environ["ENABLE_PROOF_SURFACES"] = "false"
os.environ["TRUST_SIGNING_KEY_ID"] = "lab-ed25519"
os.environ["TRUST_SIGNING_PRIVATE_KEY_B64"] = LAB_PRIVATE_KEY_B64
configure_environment()
sys.path.insert(0, str(ROOT))
# The offline verifier ships in the SDK and must not import the app.
sys.path.insert(0, str(ROOT / "b2a_sdk" / "src"))
import httpx # noqa: E402
from httpx import ASGITransport, AsyncClient # noqa: E402
from mcp import ClientSession # noqa: E402
from mcp.client.streamable_http import streamable_http_client # noqa: E402
from mcp.server.fastmcp import Context, FastMCP # noqa: E402
from mcp.server.transport_security import TransportSecuritySettings # noqa: E402
from mcp.shared.exceptions import McpError # noqa: E402
from pydantic import SecretStr # noqa: E402
from app.core.config import Settings # noqa: E402
from app.db.database import close_db, init_db # noqa: E402
from app.main import app # noqa: E402
from app.services.service_registry import get_service_registry # noqa: E402
from app.services.upstream_mcp import register_configured_upstream_mcp # noqa: E402
from b2a_sdk.receipt_verifier import ( # noqa: E402
key_set_from_document,
verify_bundle,
)
# --------------------------------------------------------------------------- #
# Event history #
# --------------------------------------------------------------------------- #
class EventLog:
"""Append-only, sequence-numbered record of everything the lab observed."""
def __init__(self, path: Path) -> None:
self.path = path
self.scenario: str | None = None
self._seq = 0
self._t0 = time.perf_counter()
self._handle = path.open("a", encoding="utf-8")
def emit(self, kind: str, **fields: Any) -> dict[str, Any]:
self._seq += 1
event = {
"seq": self._seq,
"t_ms": round((time.perf_counter() - self._t0) * 1000, 3),
"at": datetime.now(timezone.utc).isoformat(),
"scenario": self.scenario,
"kind": kind,
**fields,
}
self._handle.write(json.dumps(event, sort_keys=True, default=str) + "\n")
self._handle.flush()
return event
def close(self) -> None:
self._handle.close()
# --------------------------------------------------------------------------- #
# The fault: let the server finish, then lose its response #
# --------------------------------------------------------------------------- #
def _jsonrpc_method(content: bytes) -> str | None:
try:
payload = json.loads(content)
except (ValueError, UnicodeDecodeError):
return None
if isinstance(payload, dict) and isinstance(payload.get("method"), str):
return payload["method"]
return None
def _parse_json(content: bytes) -> Any:
try:
return json.loads(content)
except (ValueError, UnicodeDecodeError):
return None
class FaultInjector:
"""Arms the lost-response fault at one hop, for the next tool call only.
It also counts every tool call that crosses each hop, which is how the lab
observes gateway dispatches without consulting the gateway.
"""
def __init__(self, events: EventLog) -> None:
self._events = events
self.armed_hop: str | None = None
self.tool_calls: dict[str, int] = {}
self.drops: list[dict[str, Any]] = []
def arm(self, hop: str) -> None:
self.armed_hop = hop
self._events.emit("fault_armed", hop=hop, fault=FAULT_LOST_RESPONSE)
def reset_counts(self) -> None:
self.tool_calls = {}
def observe_tool_call(self, hop: str, *, status: int, elapsed_ms: float) -> None:
self.tool_calls[hop] = self.tool_calls.get(hop, 0) + 1
self._events.emit(
"tool_call_crossed_hop",
hop=hop,
status=status,
elapsed_ms=round(elapsed_ms, 3),
count_at_hop=self.tool_calls[hop],
)
def should_drop(self, hop: str) -> bool:
return self.armed_hop == hop
def record_drop(self, hop: str, *, lost_body: bytes) -> dict[str, Any]:
self.armed_hop = None
lost = _parse_json(lost_body)
drop = {"hop": hop, "lost_response": lost}
# What the agent would have seen, kept for the report's benefit only.
if isinstance(lost, dict):
result = lost.get("result") if isinstance(lost.get("result"), dict) else {}
receipt = result.get("receipt") if isinstance(result, dict) else None
if isinstance(receipt, dict):
drop["lost_receipt_id"] = receipt.get("receipt_id")
drop["lost_receipt_outcome"] = receipt.get("outcome")
structured = (
result.get("structuredContent") if isinstance(result, dict) else None
)
if isinstance(structured, dict):
drop["lost_confirmation"] = structured.get("confirmation")
self.drops.append(drop)
self._events.emit("response_lost", drop=drop)
return drop
class LossyTransport(httpx.AsyncBaseTransport):
"""Forwards every request; when armed, drops the response to a tool call.
The drop happens only after the inner transport has returned, so the
server has completed the call and any effect it has is already durable.
That is the fault under test: the action completed, the response did not
arrive. The caller sees the same timeout it would see from a dead socket.
"""
def __init__(
self,
inner: httpx.AsyncBaseTransport,
*,
hop: str,
injector: FaultInjector,
) -> None:
self._inner = inner
self._hop = hop
self._injector = injector
@property
def inner(self) -> httpx.AsyncBaseTransport:
"""The transport this one wraps. Read by the target safety fuse."""
return self._inner
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
if request.method != "POST":
return await self._inner.handle_async_request(request)
await request.aread()
if _jsonrpc_method(request.content) != "tools/call":
return await self._inner.handle_async_request(request)
started = time.perf_counter()
response = await self._inner.handle_async_request(request)
body = await response.aread()
await response.aclose()
elapsed_ms = (time.perf_counter() - started) * 1000
self._injector.observe_tool_call(
self._hop, status=response.status_code, elapsed_ms=elapsed_ms
)
if self._injector.should_drop(self._hop):
self._injector.record_drop(self._hop, lost_body=body)
raise httpx.ReadTimeout(
"response lost after the downstream completed", request=request
)
return httpx.Response(
status_code=response.status_code,
headers=response.headers,
content=body,
request=request,
)
async def aclose(self) -> None:
await self._inner.aclose()
# --------------------------------------------------------------------------- #
# The downstream: a payment rail with an independent record of its effects #
# --------------------------------------------------------------------------- #
@dataclass
class Effect:
seq: int
confirmation: str
vendor: str
invoice: str
amount_usd: str
idempotency_key: str | None
forwarded_meta: dict[str, Any]
scenario: str | None
class PaymentRail:
"""Stands in for the system of record the consequential tool writes to.
It is a real Streamable HTTP MCP server. Its effects list counts
executions of the tool body, which is what makes every "paid once" line
below evidence rather than a claim. It also implements the native control
a payment API such as Stripe documents: an optional idempotency key whose
stored response is replayed, and whose reuse with different parameters is
refused. Whether a caller uses that control is the caller's choice.
"""
def __init__(self, *, effects_path: Path, events: EventLog) -> None:
self.effects: list[Effect] = []
self._effects_path = effects_path
self._events = events
self._stored: dict[str, tuple[str, dict[str, Any]]] = {}
self.server = FastMCP(
"failure-lab-payment-rail",
stateless_http=True,
json_response=True,
transport_security=TransportSecuritySettings(
allowed_hosts=["localhost:9000"],
),
)
rail = self
@self.server.tool(
name=UPSTREAM_TOOL,
description=(
"Send one vendor payout. Executing it twice pays twice unless an "
"idempotency key is supplied and honored."
),
)
async def payout_send(
ctx: Context,
vendor: str,
invoice: str,
amount_usd: str,
idempotency_key: str | None = None,
) -> dict[str, Any]:
meta = ctx.request_context.meta
forwarded = (
meta.model_dump(mode="json", by_alias=True, exclude_none=True)
if meta is not None
else {}
)
return rail.execute(
vendor=vendor,
invoice=invoice,
amount_usd=amount_usd,
idempotency_key=idempotency_key,
forwarded_meta=forwarded,
)
self.asgi_app = self.server.streamable_http_app()
def lifespan(self) -> Any:
return self.asgi_app.router.lifespan_context(self.asgi_app)
def execute(
self,
*,
vendor: str,
invoice: str,
amount_usd: str,
idempotency_key: str | None,
forwarded_meta: dict[str, Any],
) -> dict[str, Any]:
params_hash = hashlib.sha256(
json.dumps(
{"vendor": vendor, "invoice": invoice, "amount_usd": amount_usd},
sort_keys=True,
).encode()
).hexdigest()
if idempotency_key:
stored = self._stored.get(idempotency_key)
if stored is not None:
stored_hash, stored_response = stored
if stored_hash != params_hash:
self._events.emit(
"downstream_idempotency_conflict",
idempotency_key=idempotency_key,
invoice=invoice,
amount_usd=amount_usd,
)
raise ValueError(
"idempotency_error: key already used with different parameters"
)
self._events.emit(
"downstream_replayed_stored_response",
idempotency_key=idempotency_key,
confirmation=stored_response["confirmation"],
)
return {**stored_response, "replayed": True}
effect = Effect(
seq=len(self.effects) + 1,
confirmation=f"PAY-{len(self.effects) + 1:04d}",
vendor=vendor,
invoice=invoice,
amount_usd=amount_usd,
idempotency_key=idempotency_key,
forwarded_meta=forwarded_meta,
scenario=self._events.scenario,
)
self.effects.append(effect)
with self._effects_path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(asdict(effect), sort_keys=True) + "\n")
self._events.emit(
"downstream_effect",
confirmation=effect.confirmation,
invoice=invoice,
amount_usd=amount_usd,
idempotency_key=idempotency_key,
forwarded_meta=forwarded_meta,
)
response = {
"confirmation": effect.confirmation,
"vendor": vendor,
"invoice": invoice,
"amount_usd": amount_usd,
"status": "settled",
"replayed": False,
}
if idempotency_key:
self._stored[idempotency_key] = (params_hash, response)
return response
def effects_for(self, invoice: str) -> list[Effect]:
return [effect for effect in self.effects if effect.invoice == invoice]
def stored_response(self, idempotency_key: str) -> dict[str, Any] | None:
stored = self._stored.get(idempotency_key)
return None if stored is None else dict(stored[1])
# --------------------------------------------------------------------------- #
# Target safety fuse #
# --------------------------------------------------------------------------- #
class UnsafeTargetError(RuntimeError):
"""An arm that sends an unauthorized payload faced a target it must not.
Raised instead of making the call. ``main`` exits 2 on this, which is
deliberately distinct from the 1 it exits when an expectation merely broke:
a safety refusal is not a failed measurement.
"""
# No legitimate chain wraps the leaf transport more than this.
_MAX_TRANSPORT_WRAPPERS = 4
def _terminates_in_asgi_app(transport: httpx.AsyncBaseTransport, app: object) -> bool:
"""Whether ``transport`` ends in an ``ASGITransport`` bound to ``app``.
Identity, not configuration. A URL constant, an environment variable, or a
settings field can all be edited without changing where the bytes actually
go, so the fuse walks the object graph the request will travel through and
compares the leaf's app by ``is``. A real network transport anywhere at the
leaf reads as foreign, which is the case that matters: it is what a real
partner tool would sit behind.
"""
hops = 0
while isinstance(transport, LossyTransport):
transport = transport.inner
hops += 1
if hops > _MAX_TRANSPORT_WRAPPERS:
return False
return isinstance(transport, ASGITransport) and transport.app is app
def require_in_process_rail(
caller: DirectCaller,
rail: PaymentRail,
*,
scenario: str,
hazard: str,
) -> None:
"""Fail closed unless this caller's bytes end in the lab's own rail.
One arm deliberately sends a payload the operator never authorized, with
no gateway in the path to refuse it. Its safety rests entirely on the
downstream refusing the call — a property this lab implements for its own
simulated rail (``PaymentRail.execute``) and cannot assume of anyone
else's tool. So that arm runs against that rail or it does not run.
The gateway's own conflict arm is deliberately **not** fused this way: it
is protected by the gateway refusing a reused key before dispatch, which
is our code and the thing under test, and verifying that refusal in front
of a real tool is both safe and worth doing.
"""
if caller.targets_in_process_rail(rail):
return
raise UnsafeTargetError(
f"{scenario} refused before any call: {hazard}. This arm puts no gateway "
"between itself and the tool, so nothing in the path would refuse the "
"call; it is safe only because the lab's own in-process rail implements "
"that refusal. This run's caller does not terminate in that rail, so the "
"arm did not run and no call was made. Run this arm against the "
"simulated rail, or remove it from the run."
)
# --------------------------------------------------------------------------- #
# The agent and the two ways it can reach the rail #
# --------------------------------------------------------------------------- #
class Agent:
"""An agent with a durable key store: one key per business operation.
A correct client reuses that key on every retry. A restart that loses the
store (the failure mode every configuration below shares) makes the same
business operation look like a new one.
"""
def __init__(self, name: str, *, generation: int = 0) -> None:
self.name = name
self.generation = generation
self._keys: dict[str, str] = {}
def key_for(self, operation: str) -> str:
if operation not in self._keys:
suffix = (
""
if self.generation == 0
else f"-g{self.generation}-{uuid.uuid4().hex[:6]}"
)
self._keys[operation] = f"pay-{operation}{suffix}"
return self._keys[operation]
def restarted(self) -> Agent:
return Agent(self.name, generation=self.generation + 1)
@dataclass
class Attempt:
number: int
kind: str
latency_ms: float
idempotency_key: str | None = None
confirmation: str | None = None
replayed_by_downstream: bool | None = None
receipt_id: str | None = None
receipt_outcome: str | None = None
credits_charged: str | None = None
detail: str | None = None
def _flatten_exceptions(exc: BaseException) -> list[BaseException]:
if isinstance(exc, BaseExceptionGroup):
return [
inner for member in exc.exceptions for inner in _flatten_exceptions(member)
]
return [exc]
def _is_transport_loss(exc: BaseException) -> bool:
for member in _flatten_exceptions(exc):
if isinstance(member, (httpx.TransportError, TimeoutError)):
return True
if isinstance(member, McpError) and "closed" in str(member).lower():
return True
return False
def _describe_exception(exc: BaseException) -> str:
return "; ".join(
f"{type(member).__name__}: {member}"[:160]
for member in _flatten_exceptions(exc)
)
class DirectCaller:
"""The agent speaks MCP straight to the rail. Nothing sits in between."""
def __init__(self, rail: PaymentRail, injector: FaultInjector, events: EventLog):
self._transport = LossyTransport(
ASGITransport(app=rail.asgi_app),
hop=HOP_AGENT_DOWNSTREAM,
injector=injector,
)
self._client = httpx.AsyncClient(
transport=self._transport,
follow_redirects=False,
)
self._events = events
def targets_in_process_rail(self, rail: PaymentRail) -> bool:
"""Whether this caller's requests end in ``rail``'s own ASGI app."""
return _terminates_in_asgi_app(self._transport, rail.asgi_app)
async def aclose(self) -> None:
await self._client.aclose()
async def call(
self,
*,
number: int,
arguments: dict[str, Any],
idempotency_key: str | None,
) -> Attempt:
args = dict(arguments)
if idempotency_key is not None:
args["idempotency_key"] = idempotency_key
self._events.emit(
"agent_attempt",
hop=HOP_AGENT_DOWNSTREAM,
number=number,
arguments=args,
)
started = time.perf_counter()
try:
async with asyncio.timeout(DIRECT_CALL_TIMEOUT_SECONDS):
async with streamable_http_client(
UPSTREAM_URL, http_client=self._client, terminate_on_close=True
) as (read_stream, write_stream, _get_session_id):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
result = await session.call_tool(
UPSTREAM_TOOL,
args,
read_timeout_seconds=timedelta(
seconds=DIRECT_CALL_TIMEOUT_SECONDS
),
)
except Exception as exc: # the lost response surfaces here
latency_ms = (time.perf_counter() - started) * 1000
kind = "response_lost" if _is_transport_loss(exc) else "error"
attempt = Attempt(
number=number,
kind=kind,
latency_ms=latency_ms,
idempotency_key=idempotency_key,
detail=_describe_exception(exc),
)
self._events.emit("agent_observed", attempt=asdict(attempt))
return attempt
latency_ms = (time.perf_counter() - started) * 1000
if result.isError:
text = " ".join(
getattr(item, "text", "") for item in result.content
).strip()
kind = (
"downstream_idempotency_conflict"
if "idempotency_error" in text
else "downstream_error"
)
attempt = Attempt(
number=number,
kind=kind,
latency_ms=latency_ms,
idempotency_key=idempotency_key,
detail=text[:200],
)
else:
payload = result.structuredContent
if not isinstance(payload, dict):
payload = json.loads(getattr(result.content[0], "text", "{}"))
attempt = Attempt(
number=number,
kind="success",
latency_ms=latency_ms,
idempotency_key=idempotency_key,
confirmation=payload.get("confirmation"),
replayed_by_downstream=bool(payload.get("replayed")),
)
self._events.emit("agent_observed", attempt=asdict(attempt))
return attempt
class GatewayCaller:
"""The agent calls the governed boundary; the boundary calls the rail."""
def __init__(
self,
*,
injector: FaultInjector,
events: EventLog,
api_key: str,
wallet_id: str,
) -> None:
self._client = AsyncClient(
transport=LossyTransport(
ASGITransport(app=app), hop=HOP_AGENT_GATEWAY, injector=injector
),
base_url="http://gateway",
headers={"X-API-Key": api_key},
)
self._events = events
self.wallet_id = wallet_id
async def aclose(self) -> None:
await self._client.aclose()
async def call(
self,
*,
number: int,
permit_id: str,
idempotency_key: str,
arguments: dict[str, Any],
request_id: str,
) -> Attempt:
body = {
"jsonrpc": "2.0",
"id": request_id,
"method": "tools/call",
"params": {
"name": PUBLIC_TOOL,
"arguments": arguments,
"mcpContext": {
"wallet_id": self.wallet_id,
"permit_id": permit_id,
"idempotency_key": idempotency_key,
},
},
}
self._events.emit(
"agent_attempt",
hop=HOP_AGENT_GATEWAY,
number=number,
idempotency_key=idempotency_key,
arguments=arguments,
)
started = time.perf_counter()
try:
response = await self._client.post("/mcp/messages", json=body)
except httpx.TransportError as exc:
attempt = Attempt(
number=number,
kind="response_lost",
latency_ms=(time.perf_counter() - started) * 1000,
idempotency_key=idempotency_key,
detail=f"{type(exc).__name__}: {exc}",
)
self._events.emit("agent_observed", attempt=asdict(attempt))
return attempt
latency_ms = (time.perf_counter() - started) * 1000
envelope = response.json()
error = envelope.get("error")
if isinstance(error, dict):
data: dict[str, Any] = (
error["data"] if isinstance(error.get("data"), dict) else {}
)
receipt: dict[str, Any] = (
data["receipt"] if isinstance(data.get("receipt"), dict) else {}
)
attempt = Attempt(
number=number,
kind=str(error.get("message")),
latency_ms=latency_ms,
idempotency_key=idempotency_key,
receipt_id=receipt.get("receipt_id"),
receipt_outcome=receipt.get("outcome"),
credits_charged=(
None
if receipt.get("credits_charged") is None
else str(receipt.get("credits_charged"))
),
detail=json.dumps(
{"code": error.get("code"), "http_status": response.status_code},
sort_keys=True,
),
)
else:
result: dict[str, Any] = envelope["result"]
receipt = (
result["receipt"] if isinstance(result.get("receipt"), dict) else {}
)
payload = result.get("structuredContent")
if not isinstance(payload, dict):
payload = json.loads(result["content"][0]["text"])
attempt = Attempt(
number=number,
kind="success",
latency_ms=latency_ms,
idempotency_key=idempotency_key,
confirmation=payload.get("confirmation"),
replayed_by_downstream=bool(payload.get("replayed")),
receipt_id=receipt.get("receipt_id"),
receipt_outcome=receipt.get("outcome"),
credits_charged=(
None
if receipt.get("credits_charged") is None
else str(receipt.get("credits_charged"))
),
)
self._events.emit("agent_observed", attempt=asdict(attempt))
return attempt
# --------------------------------------------------------------------------- #
# The gateway under test #
# --------------------------------------------------------------------------- #
class Gateway:
"""The real application, its real upstream adapter, and one agent wallet."""
def __init__(self, rail: PaymentRail, injector: FaultInjector, events: EventLog):
self._rail = rail
self._injector = injector
self._events = events
self._upstream_client: httpx.AsyncClient | None = None
self._admin: AsyncClient | None = None
self._agent: AsyncClient | None = None
self.wallet_id = ""
self.key_id = ""
self.api_key = ""
self.service: dict[str, Any] | None = None
self.configuration: dict[str, Any] = {}
async def start(self) -> None:
await close_db()
for suffix in ("", "-shm", "-wal"):
path = Path(f"{GATEWAY_DB}{suffix}")
if path.exists():
path.unlink()
await init_db()
self._upstream_client = httpx.AsyncClient(
transport=LossyTransport(
ASGITransport(app=self._rail.asgi_app),
hop=HOP_GATEWAY_DOWNSTREAM,
injector=self._injector,
),
headers={"Authorization": f"Bearer {UPSTREAM_BEARER}"},
follow_redirects=False,
)
settings = Settings( # type: ignore[call-arg]
_env_file=None,
ENVIRONMENT="local",
MCP_UPSTREAM_ENABLED=True,
MCP_UPSTREAM_URL=UPSTREAM_URL,
MCP_UPSTREAM_TOOL_NAME=UPSTREAM_TOOL,
MCP_UPSTREAM_PUBLIC_TOOL_ID=PUBLIC_TOOL,
MCP_UPSTREAM_BEARER_TOKEN=SecretStr(UPSTREAM_BEARER),
MCP_UPSTREAM_CREDITS_PER_CALL=Decimal(CREDITS_PER_CALL),
MCP_UPSTREAM_CONNECT_TIMEOUT_SECONDS=CONNECT_TIMEOUT_SECONDS,
MCP_UPSTREAM_CALL_TIMEOUT_SECONDS=CALL_TIMEOUT_SECONDS,
)
self.service = await register_configured_upstream_mcp(
settings=settings, http_client=self._upstream_client
)
self.configuration = {
"public_tool_id": PUBLIC_TOOL,
"upstream_tool_name": UPSTREAM_TOOL,
"upstream_url": UPSTREAM_URL,
"credits_per_call": CREDITS_PER_CALL,
"connect_timeout_seconds": CONNECT_TIMEOUT_SECONDS,
"call_timeout_seconds": CALL_TIMEOUT_SECONDS,
"trust_mode_enabled": True,
"allow_legacy_unpermitted_mcp": False,
"enable_proof_surfaces": False,
"database": "sqlite (throwaway, in the run directory)",
}
self._events.emit(
"gateway_started",
registered_tool=PUBLIC_TOOL,
execution_backend=(self.service or {}).get("execution_backend"),
)
self._admin = AsyncClient(
transport=ASGITransport(app=app),
base_url="http://gateway",
headers={"X-API-Key": ADMIN_KEY},
)
sponsor = await self._post(
self._admin,
"/v1/billing/wallets/sponsor",
expected_status=201,
json_body={
"sponsor_name": "Accounts Payable",
"email": "ap@example.com",
"initial_credits": 10000,
"require_kyc": False,
},
)
agent = await self._post(
self._admin,
"/v1/billing/wallets/agent",
expected_status=201,
json_body={
"sponsor_wallet_id": sponsor["wallet_id"],
"agent_id": "ap-agent",
"budget_credits": 5000,
"daily_limit": 2000,
},
)
self.wallet_id = agent["wallet_id"]
key = await self._post(
self._admin,
"/v1/api-keys",
expected_status=201,