From ca091a62dee11e396072d162fd70f9c2000ebbbb Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Thu, 8 Oct 2026 01:17:24 -0700 Subject: [PATCH 1/4] QA: agent-middleware examples/mcp-client/ Audit fix by Muse Code fleet instance qa5-am-examples-mcp-client (Grok Bot reviews before PR). --- QUICKSTART.md | 6 + examples/mcp-client/call_with_retry.py | 198 +++++++++-- examples/mcp-client/mcp.json | 3 +- examples/mcp-client/test_call_with_retry.py | 366 ++++++++++++++++++++ 4 files changed, 548 insertions(+), 25 deletions(-) create mode 100644 examples/mcp-client/test_call_with_retry.py diff --git a/QUICKSTART.md b/QUICKSTART.md index 8ef639575..e9d14e6af 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -49,10 +49,16 @@ uv run --with "mcp>=1.29,<2" python ../examples/mcp-client/call_with_retry.py ``` ```text +idempotency key: mcp-example-... first receipt: rcpt-... retry receipt: rcpt-... <- the same id: no second dispatch, no second debit ``` +If the script stops after printing the key, run it again with +`AMW_IDEMPOTENCY_KEY` set to that value. A new key would be a second charge. +The `mcp.json` config does not set an idempotency key: a connection header +would pin one key onto every tool call. + Check the effect count yourself: `wc -l data/dogfood_partner_notes.jsonl` grew by one, not two. diff --git a/examples/mcp-client/call_with_retry.py b/examples/mcp-client/call_with_retry.py index e93a24339..8576337ce 100644 --- a/examples/mcp-client/call_with_retry.py +++ b/examples/mcp-client/call_with_retry.py @@ -6,8 +6,18 @@ AGENT_API_KEY=... python examples/mcp-client/call_with_retry.py -The second call reuses the idempotency key, so the gateway returns the original -receipt instead of dispatching or charging again. +The script prints its idempotency key before the first call. The second call +sends that same key, so the gateway returns the original receipt instead of +dispatching or charging again. If the process dies after the first call, rerun +with that printed value in AMW_IDEMPOTENCY_KEY. A new process with no saved key +is a new charged call. + +examples/mcp-client/mcp.json only sends the API key. A connection header would +attach one idempotency key to every tool call, so the second distinct action +would replay the first or be refused. + +The process exits with an error when either call failed, when a receipt id is +missing, or when the two receipt ids differ. Licensed under Apache-2.0. """ @@ -16,7 +26,9 @@ import asyncio import os +import re import uuid +from collections.abc import Mapping from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client @@ -24,37 +36,177 @@ URL = os.environ.get("AMW_MCP_URL", "http://127.0.0.1:8000/mcp") TOOL = os.environ.get("AMW_TOOL", "partner.notes.write") +RECEIPT_META_KEY = "io.agentmiddleware/receipt" +# Same bound the gateway stores in idempotency_records.idempotency_key. +_MAX_IDEMPOTENCY_KEY_LENGTH = 128 +# Same minimum the gateway applies before it will look up an API key. +_MIN_API_KEY_LENGTH = 8 +_CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f]") +_NOTE = {"text": "hello from an MCP client"} + + +def require_api_key(environ: Mapping[str, str]) -> str: + """Return AGENT_API_KEY, or stop before any request is sent.""" + api_key = environ.get("AGENT_API_KEY") + if ( + isinstance(api_key, str) + and _CONTROL_CHARACTERS.search(api_key) is None + and len(api_key.strip()) >= _MIN_API_KEY_LENGTH + ): + return api_key + raise SystemExit( + "AGENT_API_KEY is missing, shorter than 8 characters, or contains a " + "control character. Mint a wallet-scoped key as shown in QUICKSTART.md." + ) + + +def _validate_idempotency_key(key: object) -> str: + if not isinstance(key, str) or key.strip() == "": + raise SystemExit( + "The idempotency key is blank. Set a non-blank key of at most " + "128 characters, or unset AMW_IDEMPOTENCY_KEY to mint one." + ) + if len(key) > _MAX_IDEMPOTENCY_KEY_LENGTH: + raise SystemExit( + "The idempotency key is longer than 128 characters. The gateway " + "refuses that key before any charge." + ) + if _CONTROL_CHARACTERS.search(key): + raise SystemExit( + "The idempotency key contains a control character. The gateway " + "refuses that key before any charge." + ) + return key + + +def idempotency_key_for_run(environ: Mapping[str, str]) -> str: + """Reuse AMW_IDEMPOTENCY_KEY when set, otherwise mint one key for this run.""" + if "AMW_IDEMPOTENCY_KEY" not in environ: + return f"mcp-example-{uuid.uuid4()}" + return _validate_idempotency_key(environ["AMW_IDEMPOTENCY_KEY"]) + + +def _receipt_copies(result: dict) -> list[dict] | None: + """Receipt objects from meta, _meta, and the top-level receipt field. + + None means the payload is malformed. Callers must not pick a receipt id + out of it. An empty list means no receipt was present. + """ + if not isinstance(result, dict): + return None + copies: list[dict] = [] + for key in ("meta", "_meta"): + container = result.get(key) + if container is None: + continue + if not isinstance(container, dict): + return None + if RECEIPT_META_KEY not in container: + continue + receipt = container[RECEIPT_META_KEY] + if not isinstance(receipt, dict): + return None + copies.append(receipt) + if "receipt" in result: + top = result["receipt"] + if not isinstance(top, dict): + return None + copies.append(top) + return copies + + +def _agreed_receipt(result: dict) -> dict | None: + """The one receipt whose copies all name the same id and outcome.""" + copies = _receipt_copies(result) + if not copies: + return None + ids: list[str] = [] + outcomes: list[str] = [] + for receipt in copies: + receipt_value = receipt.get("receipt_id") + if not isinstance(receipt_value, str) or receipt_value.strip() == "": + return None + ids.append(receipt_value) + if "outcome" in receipt and receipt.get("outcome") is not None: + outcome = receipt.get("outcome") + if not isinstance(outcome, str) or outcome.strip() == "": + return None + outcomes.append(outcome) + if len(set(ids)) != 1 or len(set(outcomes)) > 1: + return None + return copies[0] + + +def receipt_id(result: dict) -> str | None: + """The gateway receipt id, when every copy of the receipt agrees.""" + receipt = _agreed_receipt(result) + if receipt is None: + return None + value = receipt.get("receipt_id") + if not isinstance(value, str) or value.strip() == "": + return None + return value + + +def _outcome(result: dict) -> str | None: + receipt = _agreed_receipt(result) + if receipt is None: + return None + value = receipt.get("outcome") + if not isinstance(value, str) or value.strip() == "": + return None + return value + + +def retry_failure(first: dict, retry: dict) -> str | None: + """Why this pair is not a successful replay, or None when it is.""" + if not isinstance(first, dict) or not isinstance(retry, dict): + return "the tool result was not an object, so the retry cannot be checked" + if first.get("isError") or retry.get("isError"): + return ( + "the tool call returned an error, so this run did not show a " + "successful governed call" + ) + first_id = receipt_id(first) + retry_id = receipt_id(retry) + if not first_id or not retry_id: + return ( + "a signed receipt id was missing or the receipt copies disagreed, " + "so the retry cannot be checked" + ) + if first_id != retry_id: + return ( + "the retry returned a different receipt id, so this was not a " + "replay of the first call" + ) + if _outcome(first) != _outcome(retry): + return "the two calls report different outcomes for the same receipt id" + return None + async def call_once(api_key: str, idempotency_key: str) -> dict: - headers = {"X-API-Key": api_key, "Idempotency-Key": idempotency_key} + require_api_key({"AGENT_API_KEY": api_key}) + checked_key = _validate_idempotency_key(idempotency_key) + headers = {"X-API-Key": api_key, "Idempotency-Key": checked_key} async with streamablehttp_client(URL, headers=headers) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() - result = await session.call_tool(TOOL, {"text": "hello from an MCP client"}) + result = await session.call_tool(TOOL, dict(_NOTE)) return result.model_dump(mode="json") -RECEIPT_META_KEY = "io.agentmiddleware/receipt" - - -def receipt_id(result: dict) -> str | None: - """The gateway returns the signed receipt in the tool result's _meta.""" - receipt = (result.get("meta") or result.get("_meta") or {}).get(RECEIPT_META_KEY) or {} - return receipt.get("receipt_id") - - async def main() -> None: - api_key = os.environ["AGENT_API_KEY"] - key = f"mcp-example-{uuid.uuid4()}" + api_key = require_api_key(os.environ) + key = idempotency_key_for_run(os.environ) + # Printed before the call so a lost response can be retried with the same key. + print("idempotency key:", key, flush=True) first = await call_once(api_key, key) - retry = await call_once(api_key, key) # same key: same receipt, no second charge - print("first receipt:", receipt_id(first), "outcome:", _outcome(first)) - print("retry receipt:", receipt_id(retry), "outcome:", _outcome(retry)) - - -def _outcome(result: dict) -> str | None: - receipt = (result.get("meta") or result.get("_meta") or {}).get(RECEIPT_META_KEY) or {} - return receipt.get("outcome") + retry = await call_once(api_key, key) + print("first receipt:", receipt_id(first), "outcome:", _outcome(first), flush=True) + print("retry receipt:", receipt_id(retry), "outcome:", _outcome(retry), flush=True) + problem = retry_failure(first, retry) + if problem is not None: + raise SystemExit(problem) if __name__ == "__main__": diff --git a/examples/mcp-client/mcp.json b/examples/mcp-client/mcp.json index b6313c1b3..cb1fcebbd 100644 --- a/examples/mcp-client/mcp.json +++ b/examples/mcp-client/mcp.json @@ -4,8 +4,7 @@ "type": "http", "url": "http://127.0.0.1:8000/mcp", "headers": { - "X-API-Key": "${AGENT_API_KEY}", - "Idempotency-Key": "${AMW_IDEMPOTENCY_KEY}" + "X-API-Key": "${AGENT_API_KEY}" } } } diff --git a/examples/mcp-client/test_call_with_retry.py b/examples/mcp-client/test_call_with_retry.py new file mode 100644 index 000000000..8a05ab117 --- /dev/null +++ b/examples/mcp-client/test_call_with_retry.py @@ -0,0 +1,366 @@ +"""Behavior tests for the standard MCP retry example. + +The example is a client, not the gateway. These tests stay offline: they check +the config, the receipt reader, and the retry decision. They do not open a +socket and they do not read a database URL. +""" + +from __future__ import annotations + +import asyncio +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +HERE = Path(__file__).resolve().parent +MODULE_PATH = HERE / "call_with_retry.py" +CONFIG_PATH = HERE / "mcp.json" + +_spec = importlib.util.spec_from_file_location("mcp_client_call_with_retry", MODULE_PATH) +assert _spec is not None and _spec.loader is not None +client = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = client +_spec.loader.exec_module(client) + +API_KEY = "amw_dev_example_key" +RECEIPT_KEY = "io.agentmiddleware/receipt" + + +def _receipt(receipt_id: str, outcome: str = "success") -> dict: + return {"receipt_id": receipt_id, "outcome": outcome} + + +def _sdk_result(receipt_id: str, *, outcome: str = "success", is_error: bool = False) -> dict: + """Shape produced by CallToolResult.model_dump (field name meta, plus receipt).""" + receipt = _receipt(receipt_id, outcome) + return { + "meta": {RECEIPT_KEY: dict(receipt)}, + "receipt": dict(receipt), + "isError": is_error, + "content": [], + } + + +def _wire_result(receipt_id: str, *, outcome: str = "success") -> dict: + """Shape of the JSON result body on POST /mcp (alias _meta, plus receipt).""" + receipt = _receipt(receipt_id, outcome) + return { + "_meta": {RECEIPT_KEY: dict(receipt)}, + "receipt": dict(receipt), + "isError": False, + "content": [], + } + + +def test_client_config_authenticates_without_pinning_one_action() -> None: + """A connection header is sent on every request, including every tool call. + + One Idempotency-Key there makes the second distinct action a replay or a + conflict, and an unset placeholder becomes a blank key the gateway refuses + before any effect. The API key stays. The retry script supplies a per-run key. + """ + config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) + server = config["mcpServers"]["agent-middleware"] + assert server["type"] == "http" + assert server["url"] == "http://127.0.0.1:8000/mcp" + headers = server["headers"] + assert headers["X-API-Key"] == "${AGENT_API_KEY}" + folded = {name.lower(): value for name, value in headers.items()} + assert "idempotency-key" not in folded + assert "idempotency" not in json.dumps(headers).lower() + + +def test_receipt_id_reads_sdk_dump_and_wire_result() -> None: + assert client.receipt_id(_sdk_result("rcpt-sdk")) == "rcpt-sdk" + assert client._outcome(_sdk_result("rcpt-sdk")) == "success" + assert client.receipt_id(_wire_result("rcpt-wire")) == "rcpt-wire" + assert client._outcome(_wire_result("rcpt-wire", outcome="denied")) == "denied" + + +def test_receipt_id_reads_top_level_receipt_when_meta_is_absent() -> None: + result = {"isError": False, "receipt": _receipt("rcpt-top")} + assert client.receipt_id(result) == "rcpt-top" + assert client._outcome(result) == "success" + + +def test_receipt_reader_does_not_crash_on_a_non_dict_receipt() -> None: + for result in ( + {"_meta": {RECEIPT_KEY: "rcpt-not-an-object"}, "isError": False}, + {"meta": "nope", "isError": False}, + {"receipt": "rcpt-not-an-object", "isError": False}, + ): + assert client.receipt_id(result) is None + assert client._outcome(result) is None + + +def test_receipt_reader_refuses_disagreeing_copies() -> None: + disagreed_ids = { + "meta": {RECEIPT_KEY: _receipt("rcpt-a")}, + "_meta": {RECEIPT_KEY: _receipt("rcpt-b")}, + } + assert client.receipt_id(disagreed_ids) is None + + disagreed_outcomes = { + "meta": {RECEIPT_KEY: _receipt("rcpt-1", "success")}, + "receipt": _receipt("rcpt-1", "denied"), + } + assert client.receipt_id(disagreed_outcomes) is None + assert client._outcome(disagreed_outcomes) is None + + +def test_matching_copies_still_return_the_one_receipt_id() -> None: + result = { + "meta": {RECEIPT_KEY: _receipt("rcpt-same")}, + "_meta": {RECEIPT_KEY: _receipt("rcpt-same")}, + "receipt": _receipt("rcpt-same"), + } + assert client.receipt_id(result) == "rcpt-same" + assert client._outcome(result) == "success" + + +class _Result: + def __init__(self, payload: dict) -> None: + self._payload = payload + + def model_dump(self, mode: str = "json") -> dict: + assert mode == "json" + return self._payload + + +class _Session: + def __init__(self, payload: dict, seen: dict) -> None: + self._payload = payload + self._seen = seen + + async def __aenter__(self) -> _Session: + return self + + async def __aexit__(self, *exc: object) -> bool: + return False + + async def initialize(self) -> None: + self._seen["initialized"] = True + + async def call_tool(self, name: str, arguments: dict) -> _Result: + self._seen["tool"] = name + self._seen["arguments"] = arguments + return _Result(self._payload) + + +def test_call_once_sends_key_headers_and_does_not_put_the_secret_in_the_url( + monkeypatch: pytest.MonkeyPatch, +) -> None: + seen: dict = {} + + class _Client: + def __init__(self, url: str, headers: dict | None = None) -> None: + seen["url"] = url + seen["headers"] = dict(headers or {}) + + async def __aenter__(self) -> tuple: + return (None, None, None) + + async def __aexit__(self, *exc: object) -> bool: + return False + + monkeypatch.setattr(client, "streamablehttp_client", _Client) + monkeypatch.setattr( + client, + "ClientSession", + lambda read, write: _Session(_sdk_result("rcpt-1"), seen), + ) + + payload = asyncio.run(client.call_once(API_KEY, "retry-key-1")) + + assert payload["isError"] is False + assert seen["initialized"] is True + assert seen["url"] == client.URL + assert API_KEY not in seen["url"] + assert seen["headers"] == { + "X-API-Key": API_KEY, + "Idempotency-Key": "retry-key-1", + } + assert seen["tool"] == client.TOOL + assert seen["arguments"] == {"text": "hello from an MCP client"} + + +def test_call_once_refuses_a_blank_or_short_api_key_before_connecting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def _boom(*args: object, **kwargs: object) -> None: + raise AssertionError("client connected") + + monkeypatch.setattr(client, "streamablehttp_client", _boom) + for api_key in ("", " ", "short", "bad\nkey-value"): + with pytest.raises(SystemExit): + asyncio.run(client.call_once(api_key, "retry-key-1")) + + +def test_call_once_refuses_an_unusable_idempotency_key_before_connecting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def _boom(*args: object, **kwargs: object) -> None: + raise AssertionError("client connected") + + monkeypatch.setattr(client, "streamablehttp_client", _boom) + for key in ("", " ", "x" * 129, "bad\nkey", "bad\x7fkey"): + with pytest.raises(SystemExit): + asyncio.run(client.call_once(API_KEY, key)) + + +def _patch_main( + monkeypatch: pytest.MonkeyPatch, + results: list[dict], +) -> list[str]: + keys: list[str] = [] + + async def _fake(api_key: str, idempotency_key: str) -> dict: + assert api_key == API_KEY + keys.append(idempotency_key) + return results[len(keys) - 1] + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + return keys + + +def test_main_reuses_one_generated_key_and_prints_it_before_calling( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + printed_before_call: list[str] = [] + sent: list[str] = [] + + async def _fake(api_key: str, idempotency_key: str) -> dict: + printed_before_call.append(capsys.readouterr().out) + sent.append(idempotency_key) + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + + asyncio.run(client.main()) + first_out = printed_before_call[0] + assert sent[0] == sent[1] + assert f"idempotency key: {sent[0]}" in first_out + assert API_KEY not in first_out + assert API_KEY not in capsys.readouterr().out + + +def test_main_uses_the_env_key_for_both_calls( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + keys = _patch_main( + monkeypatch, + [_sdk_result("rcpt-1"), _sdk_result("rcpt-1")], + ) + monkeypatch.setenv("AMW_IDEMPOTENCY_KEY", "kept-for-a-lost-response") + asyncio.run(client.main()) + assert keys == ["kept-for-a-lost-response", "kept-for-a-lost-response"] + assert "idempotency key: kept-for-a-lost-response" in capsys.readouterr().out + + +def test_main_mints_a_fresh_key_per_process_when_env_is_unset( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + first = _patch_main(monkeypatch, [_sdk_result("rcpt-1"), _sdk_result("rcpt-1")]) + asyncio.run(client.main()) + second = _patch_main(monkeypatch, [_sdk_result("rcpt-2"), _sdk_result("rcpt-2")]) + asyncio.run(client.main()) + assert first[0] == first[1] + assert second[0] == second[1] + assert first[0] != second[0] + assert first[0].startswith("mcp-example-") + assert len(first[0]) <= 128 + + +def test_main_exits_when_the_retry_is_not_the_same_receipt( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _patch_main(monkeypatch, [_sdk_result("rcpt-1"), _sdk_result("rcpt-2")]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert raised.value.code not in (0, None) + assert "different receipt" in str(raised.value) + + +def test_main_exits_when_only_the_retry_failed(monkeypatch: pytest.MonkeyPatch) -> None: + _patch_main( + monkeypatch, + [_sdk_result("rcpt-1"), _sdk_result("rcpt-1", is_error=True)], + ) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "error" in str(raised.value).lower() + + +def test_main_exits_when_outcomes_differ(monkeypatch: pytest.MonkeyPatch) -> None: + _patch_main( + monkeypatch, + [_sdk_result("rcpt-1", outcome="success"), _sdk_result("rcpt-1", outcome="denied")], + ) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "outcome" in str(raised.value).lower() + + +def test_main_exits_when_the_tool_call_failed(monkeypatch: pytest.MonkeyPatch) -> None: + failed = _sdk_result("rcpt-1", is_error=True) + _patch_main(monkeypatch, [failed, failed]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "error" in str(raised.value).lower() + + +def test_main_exits_when_the_receipt_id_is_missing(monkeypatch: pytest.MonkeyPatch) -> None: + empty = {"meta": {}, "isError": False, "content": []} + _patch_main(monkeypatch, [empty, empty]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "receipt" in str(raised.value).lower() + + +def test_main_refuses_a_blank_api_key_without_calling( + monkeypatch: pytest.MonkeyPatch, +) -> None: + called = False + + async def _fake(api_key: str, idempotency_key: str) -> dict: + nonlocal called + called = True + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", " ") + with pytest.raises(SystemExit): + asyncio.run(client.main()) + assert called is False + + +def test_main_refuses_a_bad_saved_idempotency_key_without_calling( + monkeypatch: pytest.MonkeyPatch, +) -> None: + called = False + + async def _fake(api_key: str, idempotency_key: str) -> dict: + nonlocal called + called = True + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + monkeypatch.setenv("AMW_IDEMPOTENCY_KEY", "bad\nkey") + with pytest.raises(SystemExit): + asyncio.run(client.main()) + assert called is False From 836b4a97513fdfa9e686f3c21f6f8c898f72a7d5 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:11:50 -0700 Subject: [PATCH 2/4] examples: verify successful MCP retry before reporting receipts Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- QUICKSTART.md | 6 + examples/mcp-client/call_with_retry.py | 206 ++++++++- examples/mcp-client/expected_output.txt | 1 + examples/mcp-client/mcp.json | 3 +- examples/mcp-client/test_call_with_retry.py | 464 ++++++++++++++++++++ 5 files changed, 654 insertions(+), 26 deletions(-) create mode 100644 examples/mcp-client/test_call_with_retry.py diff --git a/QUICKSTART.md b/QUICKSTART.md index 8ef639575..e9d14e6af 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -49,10 +49,16 @@ uv run --with "mcp>=1.29,<2" python ../examples/mcp-client/call_with_retry.py ``` ```text +idempotency key: mcp-example-... first receipt: rcpt-... retry receipt: rcpt-... <- the same id: no second dispatch, no second debit ``` +If the script stops after printing the key, run it again with +`AMW_IDEMPOTENCY_KEY` set to that value. A new key would be a second charge. +The `mcp.json` config does not set an idempotency key: a connection header +would pin one key onto every tool call. + Check the effect count yourself: `wc -l data/dogfood_partner_notes.jsonl` grew by one, not two. diff --git a/examples/mcp-client/call_with_retry.py b/examples/mcp-client/call_with_retry.py index e93a24339..119950c81 100644 --- a/examples/mcp-client/call_with_retry.py +++ b/examples/mcp-client/call_with_retry.py @@ -6,8 +6,18 @@ AGENT_API_KEY=... python examples/mcp-client/call_with_retry.py -The second call reuses the idempotency key, so the gateway returns the original -receipt instead of dispatching or charging again. +The script prints its idempotency key before the first call. The second call +sends that same key, so the gateway returns the original receipt instead of +dispatching or charging again. If the process dies after the first call, rerun +with that printed value in AMW_IDEMPOTENCY_KEY. A new process with no saved key +is a new charged call. + +examples/mcp-client/mcp.json only sends the API key. A connection header would +attach one idempotency key to every tool call, so the second distinct action +would replay the first or be refused. + +The process exits with an error when either call failed, when a receipt id is +missing, or when the two receipt ids differ. Licensed under Apache-2.0. """ @@ -16,7 +26,9 @@ import asyncio import os +import re import uuid +from collections.abc import Mapping from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client @@ -24,37 +36,183 @@ URL = os.environ.get("AMW_MCP_URL", "http://127.0.0.1:8000/mcp") TOOL = os.environ.get("AMW_TOOL", "partner.notes.write") +RECEIPT_META_KEY = "io.agentmiddleware/receipt" +# Same bound the gateway stores in idempotency_records.idempotency_key. +_MAX_IDEMPOTENCY_KEY_LENGTH = 128 +# Same minimum the gateway applies before it will look up an API key. +_MIN_API_KEY_LENGTH = 8 +_CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f]") +_NOTE = {"text": "hello from an MCP client"} + + +def require_api_key(environ: Mapping[str, str]) -> str: + """Return AGENT_API_KEY, or stop before any request is sent.""" + api_key = environ.get("AGENT_API_KEY") + if ( + isinstance(api_key, str) + and _CONTROL_CHARACTERS.search(api_key) is None + and len(api_key.strip()) >= _MIN_API_KEY_LENGTH + ): + return api_key + raise SystemExit( + "AGENT_API_KEY is missing, shorter than 8 characters, or contains a " + "control character. Mint a wallet-scoped key as shown in QUICKSTART.md." + ) + + +def _validate_idempotency_key(key: object) -> str: + if not isinstance(key, str) or key.strip() == "": + raise SystemExit( + "The idempotency key is blank. Set a non-blank key of at most " + "128 characters, or unset AMW_IDEMPOTENCY_KEY to mint one." + ) + if len(key) > _MAX_IDEMPOTENCY_KEY_LENGTH: + raise SystemExit( + "The idempotency key is longer than 128 characters. The gateway " + "refuses that key before any charge." + ) + if _CONTROL_CHARACTERS.search(key): + raise SystemExit( + "The idempotency key contains a control character. The gateway " + "refuses that key before any charge." + ) + return key + + +def idempotency_key_for_run(environ: Mapping[str, str]) -> str: + """Reuse AMW_IDEMPOTENCY_KEY when set, otherwise mint one key for this run.""" + if "AMW_IDEMPOTENCY_KEY" not in environ: + return f"mcp-example-{uuid.uuid4()}" + return _validate_idempotency_key(environ["AMW_IDEMPOTENCY_KEY"]) + + +def _receipt_copies(result: dict) -> list[dict] | None: + """Receipt objects from meta, _meta, and the top-level receipt field. + + None means the payload is malformed. Callers must not pick a receipt id + out of it. An empty list means no receipt was present. + """ + if not isinstance(result, dict): + return None + copies: list[dict] = [] + for key in ("meta", "_meta"): + container = result.get(key) + if container is None: + continue + if not isinstance(container, dict): + return None + if RECEIPT_META_KEY not in container: + continue + receipt = container[RECEIPT_META_KEY] + if not isinstance(receipt, dict): + return None + copies.append(receipt) + if "receipt" in result: + top = result["receipt"] + if not isinstance(top, dict): + return None + copies.append(top) + return copies + + +def _agreed_receipt(result: dict) -> dict | None: + """The one receipt whose copies all name the same id and outcome.""" + copies = _receipt_copies(result) + if not copies: + return None + ids: list[str] = [] + outcomes: list[str] = [] + for receipt in copies: + receipt_value = receipt.get("receipt_id") + if not isinstance(receipt_value, str) or receipt_value.strip() == "": + return None + ids.append(receipt_value) + if "outcome" in receipt and receipt.get("outcome") is not None: + outcome = receipt.get("outcome") + if not isinstance(outcome, str) or outcome.strip() == "": + return None + outcomes.append(outcome) + if len(set(ids)) != 1 or len(set(outcomes)) > 1: + return None + return copies[0] -async def call_once(api_key: str, idempotency_key: str) -> dict: - headers = {"X-API-Key": api_key, "Idempotency-Key": idempotency_key} - async with streamablehttp_client(URL, headers=headers) as (read, write, _): - async with ClientSession(read, write) as session: - await session.initialize() - result = await session.call_tool(TOOL, {"text": "hello from an MCP client"}) - return result.model_dump(mode="json") +def receipt_id(result: dict) -> str | None: + """The gateway receipt id, when every copy of the receipt agrees.""" + receipt = _agreed_receipt(result) + if receipt is None: + return None + value = receipt.get("receipt_id") + if not isinstance(value, str) or value.strip() == "": + return None + return value -RECEIPT_META_KEY = "io.agentmiddleware/receipt" +def _outcome(result: dict) -> str | None: + receipt = _agreed_receipt(result) + if receipt is None: + return None + value = receipt.get("outcome") + if not isinstance(value, str) or value.strip() == "": + return None + return value + + +def retry_failure(first: dict, retry: dict) -> str | None: + """Why this pair is not a successful replay, or None when it is.""" + if not isinstance(first, dict) or not isinstance(retry, dict): + return "the tool result was not an object, so the retry cannot be checked" + if first.get("isError") or retry.get("isError"): + return ( + "the tool call returned an error, so this run did not show a " + "successful governed call" + ) + first_id = receipt_id(first) + retry_id = receipt_id(retry) + if not first_id or not retry_id: + return ( + "a signed receipt id was missing or the receipt copies disagreed, " + "so the retry cannot be checked" + ) + if first_id != retry_id: + return ( + "the retry returned a different receipt id, so this was not a " + "replay of the first call" + ) + first_outcome = _outcome(first) + retry_outcome = _outcome(retry) + if first_outcome != retry_outcome: + return "the two calls report different outcomes for the same receipt id" + if first_outcome != "success": + return "the receipt outcome was not success, so this was not a successful governed call" + return None -def receipt_id(result: dict) -> str | None: - """The gateway returns the signed receipt in the tool result's _meta.""" - receipt = (result.get("meta") or result.get("_meta") or {}).get(RECEIPT_META_KEY) or {} - return receipt.get("receipt_id") + +async def call_once(api_key: str, idempotency_key: str) -> dict: + require_api_key({"AGENT_API_KEY": api_key}) + checked_key = _validate_idempotency_key(idempotency_key) + headers = {"X-API-Key": api_key, "Idempotency-Key": checked_key} + async with ( + streamablehttp_client(URL, headers=headers) as (read, write, _), + ClientSession(read, write) as session, + ): + await session.initialize() + result = await session.call_tool(TOOL, dict(_NOTE)) + return result.model_dump(mode="json") async def main() -> None: - api_key = os.environ["AGENT_API_KEY"] - key = f"mcp-example-{uuid.uuid4()}" + api_key = require_api_key(os.environ) + key = idempotency_key_for_run(os.environ) + # Printed before the call so a lost response can be retried with the same key. + print("idempotency key:", key, flush=True) first = await call_once(api_key, key) - retry = await call_once(api_key, key) # same key: same receipt, no second charge - print("first receipt:", receipt_id(first), "outcome:", _outcome(first)) - print("retry receipt:", receipt_id(retry), "outcome:", _outcome(retry)) - - -def _outcome(result: dict) -> str | None: - receipt = (result.get("meta") or result.get("_meta") or {}).get(RECEIPT_META_KEY) or {} - return receipt.get("outcome") + retry = await call_once(api_key, key) + problem = retry_failure(first, retry) + if problem is not None: + raise SystemExit(problem) + print("first receipt:", receipt_id(first), "outcome:", _outcome(first), flush=True) + print("retry receipt:", receipt_id(retry), "outcome:", _outcome(retry), flush=True) if __name__ == "__main__": diff --git a/examples/mcp-client/expected_output.txt b/examples/mcp-client/expected_output.txt index 002b09798..cb88f6c29 100644 --- a/examples/mcp-client/expected_output.txt +++ b/examples/mcp-client/expected_output.txt @@ -3,5 +3,6 @@ # characters. Local gateway (make quickstart), tool partner.notes.write, # same idempotency key on both calls. The retry returns the original # signed receipt: both receipt ids match. +idempotency key: mcp-example-... first receipt: rcpt-9f2c41a7b6e04d21 outcome: success retry receipt: rcpt-9f2c41a7b6e04d21 outcome: success diff --git a/examples/mcp-client/mcp.json b/examples/mcp-client/mcp.json index b6313c1b3..cb1fcebbd 100644 --- a/examples/mcp-client/mcp.json +++ b/examples/mcp-client/mcp.json @@ -4,8 +4,7 @@ "type": "http", "url": "http://127.0.0.1:8000/mcp", "headers": { - "X-API-Key": "${AGENT_API_KEY}", - "Idempotency-Key": "${AMW_IDEMPOTENCY_KEY}" + "X-API-Key": "${AGENT_API_KEY}" } } } diff --git a/examples/mcp-client/test_call_with_retry.py b/examples/mcp-client/test_call_with_retry.py new file mode 100644 index 000000000..26b5d4fbc --- /dev/null +++ b/examples/mcp-client/test_call_with_retry.py @@ -0,0 +1,464 @@ +"""Behavior tests for the standard MCP retry example. + +The example is a client, not the gateway. These tests stay offline: they check +the config, the receipt reader, and the retry decision. They do not open a +socket and they do not read a database URL. +""" + +from __future__ import annotations + +import asyncio +import importlib.util +import json +import sys +from pathlib import Path + +import pytest +from mcp.types import CallToolResult +from typing_extensions import Self + +HERE = Path(__file__).resolve().parent +MODULE_PATH = HERE / "call_with_retry.py" +CONFIG_PATH = HERE / "mcp.json" + +_spec = importlib.util.spec_from_file_location( + "mcp_client_call_with_retry", MODULE_PATH +) +assert _spec is not None and _spec.loader is not None +client = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = client +_spec.loader.exec_module(client) + +API_KEY = "amw_dev_example_key" +RECEIPT_KEY = "io.agentmiddleware/receipt" + + +def _receipt(receipt_id: str, outcome: str = "success") -> dict: + return {"receipt_id": receipt_id, "outcome": outcome} + + +def _sdk_result( + receipt_id: str, *, outcome: str = "success", is_error: bool = False +) -> dict: + """Shape produced by CallToolResult.model_dump (field name meta, plus receipt).""" + receipt = _receipt(receipt_id, outcome) + return { + "meta": {RECEIPT_KEY: dict(receipt)}, + "receipt": dict(receipt), + "isError": is_error, + "content": [], + } + + +def _wire_result(receipt_id: str, *, outcome: str = "success") -> dict: + """Shape of the JSON result body on POST /mcp (alias _meta, plus receipt).""" + receipt = _receipt(receipt_id, outcome) + return { + "_meta": {RECEIPT_KEY: dict(receipt)}, + "receipt": dict(receipt), + "isError": False, + "content": [], + } + + +def test_client_config_authenticates_without_pinning_one_action() -> None: + """A connection header is sent on every request, including every tool call. + + One Idempotency-Key there makes the second distinct action a replay or a + conflict, and an unset placeholder becomes a blank key the gateway refuses + before any effect. The API key stays. The retry script supplies a per-run key. + """ + config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) + server = config["mcpServers"]["agent-middleware"] + assert server["type"] == "http" + assert server["url"] == "http://127.0.0.1:8000/mcp" + headers = server["headers"] + assert headers["X-API-Key"] == "${AGENT_API_KEY}" + folded = {name.lower(): value for name, value in headers.items()} + assert "idempotency-key" not in folded + assert "idempotency" not in json.dumps(headers).lower() + + +def test_receipt_id_reads_sdk_dump_and_wire_result() -> None: + assert client.receipt_id(_sdk_result("rcpt-sdk")) == "rcpt-sdk" + assert client._outcome(_sdk_result("rcpt-sdk")) == "success" + assert client.receipt_id(_wire_result("rcpt-wire")) == "rcpt-wire" + assert client._outcome(_wire_result("rcpt-wire", outcome="denied")) == "denied" + + +def test_receipt_reader_accepts_official_mcp_result_dump() -> None: + receipt = _receipt("rcpt-sdk") + result = CallToolResult.model_validate( + { + "content": [], + "isError": False, + "_meta": {RECEIPT_KEY: receipt}, + "receipt": receipt, + } + ).model_dump(mode="json") + assert client.retry_failure(result, result) is None + + +def test_receipt_id_reads_top_level_receipt_when_meta_is_absent() -> None: + result = {"isError": False, "receipt": _receipt("rcpt-top")} + assert client.receipt_id(result) == "rcpt-top" + assert client._outcome(result) == "success" + + +def test_receipt_reader_does_not_crash_on_a_non_dict_receipt() -> None: + for result in ( + {"_meta": {RECEIPT_KEY: "rcpt-not-an-object"}, "isError": False}, + {"meta": "nope", "isError": False}, + {"receipt": "rcpt-not-an-object", "isError": False}, + ): + assert client.receipt_id(result) is None + assert client._outcome(result) is None + + +def test_receipt_reader_refuses_disagreeing_copies() -> None: + disagreed_ids = { + "meta": {RECEIPT_KEY: _receipt("rcpt-a")}, + "_meta": {RECEIPT_KEY: _receipt("rcpt-b")}, + } + assert client.receipt_id(disagreed_ids) is None + + disagreed_outcomes = { + "meta": {RECEIPT_KEY: _receipt("rcpt-1", "success")}, + "receipt": _receipt("rcpt-1", "denied"), + } + assert client.receipt_id(disagreed_outcomes) is None + assert client._outcome(disagreed_outcomes) is None + + +def test_matching_copies_still_return_the_one_receipt_id() -> None: + result = { + "meta": {RECEIPT_KEY: _receipt("rcpt-same")}, + "_meta": {RECEIPT_KEY: _receipt("rcpt-same")}, + "receipt": _receipt("rcpt-same"), + } + assert client.receipt_id(result) == "rcpt-same" + assert client._outcome(result) == "success" + + +class _Result: + def __init__(self, payload: dict) -> None: + self._payload = payload + + def model_dump(self, mode: str = "json") -> dict: + assert mode == "json" + return self._payload + + +class _Session: + def __init__(self, payload: dict, seen: dict) -> None: + self._payload = payload + self._seen = seen + + async def __aenter__(self) -> Self: + return self + + async def __aexit__(self, *exc: object) -> bool: + return False + + async def initialize(self) -> None: + self._seen["initialized"] = True + + async def call_tool(self, name: str, arguments: dict) -> _Result: + self._seen["tool"] = name + self._seen["arguments"] = arguments + return _Result(self._payload) + + +def test_call_once_sends_key_headers_and_does_not_put_the_secret_in_the_url( + monkeypatch: pytest.MonkeyPatch, +) -> None: + seen: dict = {} + + class _Client: + def __init__(self, url: str, headers: dict | None = None) -> None: + seen["url"] = url + seen["headers"] = dict(headers or {}) + + async def __aenter__(self) -> tuple: + return (None, None, None) + + async def __aexit__(self, *exc: object) -> bool: + return False + + monkeypatch.setattr(client, "streamablehttp_client", _Client) + monkeypatch.setattr( + client, + "ClientSession", + lambda read, write: _Session(_sdk_result("rcpt-1"), seen), + ) + + payload = asyncio.run(client.call_once(API_KEY, "retry-key-1")) + + assert payload["isError"] is False + assert seen["initialized"] is True + assert seen["url"] == client.URL + assert API_KEY not in seen["url"] + assert seen["headers"] == { + "X-API-Key": API_KEY, + "Idempotency-Key": "retry-key-1", + } + assert seen["tool"] == client.TOOL + assert seen["arguments"] == {"text": "hello from an MCP client"} + + +def test_call_once_refuses_a_blank_or_short_api_key_before_connecting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def _boom(*args: object, **kwargs: object) -> None: + raise AssertionError("client connected") + + monkeypatch.setattr(client, "streamablehttp_client", _boom) + for api_key in ("", " ", "short", "bad\nkey-value"): + with pytest.raises(SystemExit): + asyncio.run(client.call_once(api_key, "retry-key-1")) + + +def test_call_once_refuses_an_unusable_idempotency_key_before_connecting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def _boom(*args: object, **kwargs: object) -> None: + raise AssertionError("client connected") + + monkeypatch.setattr(client, "streamablehttp_client", _boom) + for key in ("", " ", "x" * 129, "bad\nkey", "bad\x7fkey"): + with pytest.raises(SystemExit): + asyncio.run(client.call_once(API_KEY, key)) + + +def _patch_main( + monkeypatch: pytest.MonkeyPatch, + results: list[dict], +) -> list[str]: + keys: list[str] = [] + + async def _fake(api_key: str, idempotency_key: str) -> dict: + assert api_key == API_KEY + keys.append(idempotency_key) + return results[len(keys) - 1] + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + return keys + + +def test_main_reuses_one_generated_key_and_prints_it_before_calling( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + printed_before_call: list[str] = [] + sent: list[str] = [] + + async def _fake(api_key: str, idempotency_key: str) -> dict: + printed_before_call.append(capsys.readouterr().out) + sent.append(idempotency_key) + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + + asyncio.run(client.main()) + first_out = printed_before_call[0] + assert sent[0] == sent[1] + assert f"idempotency key: {sent[0]}" in first_out + assert API_KEY not in first_out + assert API_KEY not in capsys.readouterr().out + + +def test_main_uses_the_env_key_for_both_calls( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + keys = _patch_main( + monkeypatch, + [_sdk_result("rcpt-1"), _sdk_result("rcpt-1")], + ) + monkeypatch.setenv("AMW_IDEMPOTENCY_KEY", "kept-for-a-lost-response") + asyncio.run(client.main()) + assert keys == ["kept-for-a-lost-response", "kept-for-a-lost-response"] + output = capsys.readouterr().out + assert "idempotency key: kept-for-a-lost-response" in output + assert "first receipt: rcpt-1 outcome: success" in output + assert "retry receipt: rcpt-1 outcome: success" in output + + +def test_main_mints_a_fresh_key_per_process_when_env_is_unset( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + first = _patch_main(monkeypatch, [_sdk_result("rcpt-1"), _sdk_result("rcpt-1")]) + asyncio.run(client.main()) + second = _patch_main(monkeypatch, [_sdk_result("rcpt-2"), _sdk_result("rcpt-2")]) + asyncio.run(client.main()) + assert first[0] == first[1] + assert second[0] == second[1] + assert first[0] != second[0] + assert first[0].startswith("mcp-example-") + assert len(first[0]) <= 128 + + +def test_main_exits_when_the_retry_is_not_the_same_receipt( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _patch_main(monkeypatch, [_sdk_result("rcpt-1"), _sdk_result("rcpt-2")]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert raised.value.code not in (0, None) + assert "different receipt" in str(raised.value) + + +def test_main_exits_when_only_the_retry_failed(monkeypatch: pytest.MonkeyPatch) -> None: + _patch_main( + monkeypatch, + [_sdk_result("rcpt-1"), _sdk_result("rcpt-1", is_error=True)], + ) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "error" in str(raised.value).lower() + + +def test_main_exits_when_outcomes_differ(monkeypatch: pytest.MonkeyPatch) -> None: + _patch_main( + monkeypatch, + [ + _sdk_result("rcpt-1", outcome="success"), + _sdk_result("rcpt-1", outcome="denied"), + ], + ) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "outcome" in str(raised.value).lower() + + +def test_main_exits_when_the_tool_call_failed(monkeypatch: pytest.MonkeyPatch) -> None: + failed = _sdk_result("rcpt-1", is_error=True) + _patch_main(monkeypatch, [failed, failed]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "error" in str(raised.value).lower() + + +def test_main_exits_when_the_receipt_id_is_missing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + empty = {"meta": {}, "isError": False, "content": []} + _patch_main(monkeypatch, [empty, empty]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert "receipt" in str(raised.value).lower() + + +@pytest.mark.parametrize( + "result", + [ + _sdk_result("rcpt-1", outcome="denied"), + {"meta": {RECEIPT_KEY: {"receipt_id": "rcpt-1"}}, "isError": False}, + _sdk_result(" "), + ], + ids=["denied", "missing-outcome", "blank-receipt-id"], +) +def test_main_refuses_matching_receipts_without_successful_nonblank_claims( + monkeypatch: pytest.MonkeyPatch, result: dict +) -> None: + _patch_main(monkeypatch, [result, result]) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit) as raised: + asyncio.run(client.main()) + assert raised.value.code not in (0, None) + + +def test_main_refuses_a_blank_api_key_without_calling( + monkeypatch: pytest.MonkeyPatch, +) -> None: + called = False + + async def _fake(api_key: str, idempotency_key: str) -> dict: + nonlocal called + called = True + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", " ") + with pytest.raises(SystemExit): + asyncio.run(client.main()) + assert called is False + + +def test_main_refuses_a_bad_saved_idempotency_key_without_calling( + monkeypatch: pytest.MonkeyPatch, +) -> None: + called = False + + async def _fake(api_key: str, idempotency_key: str) -> dict: + nonlocal called + called = True + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + monkeypatch.setenv("AMW_IDEMPOTENCY_KEY", "bad\nkey") + with pytest.raises(SystemExit): + asyncio.run(client.main()) + assert called is False + + +@pytest.mark.parametrize( + "results", + [ + [_sdk_result("rcpt-1", outcome="denied")] * 2, + [{"meta": {RECEIPT_KEY: {"receipt_id": "rcpt-1"}}}] * 2, + [_sdk_result(" ")] * 2, + [_sdk_result("rcpt-1"), _sdk_result("rcpt-2")], + [{"meta": "malformed"}] * 2, + ], + ids=["denied", "missing-outcome", "blank-id", "changed-id", "malformed"], +) +def test_failed_pair_does_not_print_a_successful_receipt( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + results: list[dict], +) -> None: + _patch_main(monkeypatch, results) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(SystemExit): + asyncio.run(client.main()) + output = capsys.readouterr().out + assert output.startswith("idempotency key: mcp-example-") + assert "receipt:" not in output + assert "outcome: success" not in output + + +@pytest.mark.parametrize("failure_call", [1, 2]) +def test_transport_failure_does_not_print_a_successful_receipt( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + failure_call: int, +) -> None: + calls = 0 + + async def _fake(api_key: str, idempotency_key: str) -> dict: + nonlocal calls + calls += 1 + if calls == failure_call: + raise OSError("transport failed") + return _sdk_result("rcpt-1") + + monkeypatch.setattr(client, "call_once", _fake) + monkeypatch.setenv("AGENT_API_KEY", API_KEY) + monkeypatch.delenv("AMW_IDEMPOTENCY_KEY", raising=False) + with pytest.raises(OSError, match="transport failed"): + asyncio.run(client.main()) + output = capsys.readouterr().out + assert output.startswith("idempotency key: mcp-example-") + assert "receipt:" not in output + assert "outcome: success" not in output From f835ceaa64905c72065ce886d606332f01f130c8 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:13:24 -0700 Subject: [PATCH 3/4] test: reject receipt copies without an outcome Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- examples/mcp-client/call_with_retry.py | 9 ++++---- examples/mcp-client/test_call_with_retry.py | 23 ++++++++++++++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/examples/mcp-client/call_with_retry.py b/examples/mcp-client/call_with_retry.py index 119950c81..ebed6b359 100644 --- a/examples/mcp-client/call_with_retry.py +++ b/examples/mcp-client/call_with_retry.py @@ -127,11 +127,10 @@ def _agreed_receipt(result: dict) -> dict | None: if not isinstance(receipt_value, str) or receipt_value.strip() == "": return None ids.append(receipt_value) - if "outcome" in receipt and receipt.get("outcome") is not None: - outcome = receipt.get("outcome") - if not isinstance(outcome, str) or outcome.strip() == "": - return None - outcomes.append(outcome) + outcome = receipt.get("outcome") + if not isinstance(outcome, str) or outcome.strip() == "": + return None + outcomes.append(outcome) if len(set(ids)) != 1 or len(set(outcomes)) > 1: return None return copies[0] diff --git a/examples/mcp-client/test_call_with_retry.py b/examples/mcp-client/test_call_with_retry.py index 26b5d4fbc..5b8c9dd78 100644 --- a/examples/mcp-client/test_call_with_retry.py +++ b/examples/mcp-client/test_call_with_retry.py @@ -129,6 +129,13 @@ def test_receipt_reader_refuses_disagreeing_copies() -> None: assert client.receipt_id(disagreed_outcomes) is None assert client._outcome(disagreed_outcomes) is None + missing_outcome = { + "meta": {RECEIPT_KEY: _receipt("rcpt-1")}, + "receipt": {"receipt_id": "rcpt-1"}, + } + assert client.receipt_id(missing_outcome) is None + assert client._outcome(missing_outcome) is None + def test_matching_copies_still_return_the_one_receipt_id() -> None: result = { @@ -420,8 +427,22 @@ async def _fake(api_key: str, idempotency_key: str) -> dict: [_sdk_result(" ")] * 2, [_sdk_result("rcpt-1"), _sdk_result("rcpt-2")], [{"meta": "malformed"}] * 2, + [ + { + "meta": {RECEIPT_KEY: _receipt("rcpt-1")}, + "receipt": {"receipt_id": "rcpt-1"}, + } + ] + * 2, + ], + ids=[ + "denied", + "missing-outcome", + "blank-id", + "changed-id", + "malformed", + "missing-copy-outcome", ], - ids=["denied", "missing-outcome", "blank-id", "changed-id", "malformed"], ) def test_failed_pair_does_not_print_a_successful_receipt( monkeypatch: pytest.MonkeyPatch, From 67f45926bf646433247db90268d77601089508a4 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:22:43 -0700 Subject: [PATCH 4/4] Preserve wire MCP receipt metadata in retry example Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- examples/mcp-client/call_with_retry.py | 2 +- examples/mcp-client/test_call_with_retry.py | 60 +++++++++++++++++---- gateway/tests/test_examples_smoke.py | 14 ++++- 3 files changed, 62 insertions(+), 14 deletions(-) diff --git a/examples/mcp-client/call_with_retry.py b/examples/mcp-client/call_with_retry.py index ebed6b359..a68eaf87d 100644 --- a/examples/mcp-client/call_with_retry.py +++ b/examples/mcp-client/call_with_retry.py @@ -197,7 +197,7 @@ async def call_once(api_key: str, idempotency_key: str) -> dict: ): await session.initialize() result = await session.call_tool(TOOL, dict(_NOTE)) - return result.model_dump(mode="json") + return result.model_dump(mode="json", by_alias=True) async def main() -> None: diff --git a/examples/mcp-client/test_call_with_retry.py b/examples/mcp-client/test_call_with_retry.py index 5b8c9dd78..b443c775c 100644 --- a/examples/mcp-client/test_call_with_retry.py +++ b/examples/mcp-client/test_call_with_retry.py @@ -147,15 +147,6 @@ def test_matching_copies_still_return_the_one_receipt_id() -> None: assert client._outcome(result) == "success" -class _Result: - def __init__(self, payload: dict) -> None: - self._payload = payload - - def model_dump(self, mode: str = "json") -> dict: - assert mode == "json" - return self._payload - - class _Session: def __init__(self, payload: dict, seen: dict) -> None: self._payload = payload @@ -170,10 +161,10 @@ async def __aexit__(self, *exc: object) -> bool: async def initialize(self) -> None: self._seen["initialized"] = True - async def call_tool(self, name: str, arguments: dict) -> _Result: + async def call_tool(self, name: str, arguments: dict) -> CallToolResult: self._seen["tool"] = name self._seen["arguments"] = arguments - return _Result(self._payload) + return CallToolResult.model_validate(self._payload) def test_call_once_sends_key_headers_and_does_not_put_the_secret_in_the_url( @@ -213,6 +204,53 @@ async def __aexit__(self, *exc: object) -> bool: assert seen["arguments"] == {"text": "hello from an MCP client"} +@pytest.mark.parametrize( + "actual_receipt", + [ + _receipt("rcpt-other"), + _receipt("rcpt-good", "denied"), + {"receipt_id": "rcpt-good"}, + "malformed", + ], + ids=["conflicting-id", "denied", "missing-outcome", "malformed"], +) +def test_call_once_keeps_wire_meta_when_an_extra_meta_claims_success( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + actual_receipt: dict | str, +) -> None: + """The MCP model must not let an extra meta overwrite the wire _meta.""" + good = _receipt("rcpt-good") + wire = { + "content": [], + "isError": False, + "_meta": {RECEIPT_KEY: actual_receipt}, + "meta": {RECEIPT_KEY: good}, + "receipt": good, + } + + class _Client: + async def __aenter__(self) -> tuple: + return (None, None, None) + + async def __aexit__(self, *exc: object) -> bool: + return False + + monkeypatch.setattr( + client, "streamablehttp_client", lambda *args, **kwargs: _Client() + ) + monkeypatch.setattr(client, "ClientSession", lambda read, write: _Session(wire, {})) + + result = asyncio.run(client.call_once(API_KEY, "retry-key-1")) + assert result["_meta"][RECEIPT_KEY] == actual_receipt + assert client.retry_failure(result, result) is not None + + _patch_main(monkeypatch, [result, result]) + with pytest.raises(SystemExit): + asyncio.run(client.main()) + assert "receipt:" not in capsys.readouterr().out + + def test_call_once_refuses_a_blank_or_short_api_key_before_connecting( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/gateway/tests/test_examples_smoke.py b/gateway/tests/test_examples_smoke.py index a1cfe39a5..2196b6240 100644 --- a/gateway/tests/test_examples_smoke.py +++ b/gateway/tests/test_examples_smoke.py @@ -119,8 +119,18 @@ def test_retry_receipt_parsing_returns_identical_ids() -> None: def test_retry_receipt_parsing_tolerates_meta_shapes() -> None: """The gateway may spell the envelope meta or _meta; both must parse.""" module = _load_retry_module() - via_meta = {"meta": {"io.agentmiddleware/receipt": {"receipt_id": "r1"}}} + via_meta = { + "meta": { + "io.agentmiddleware/receipt": { + "receipt_id": "r1", + "outcome": "success", + } + } + } assert module.receipt_id(via_meta) == "r1" + assert module._outcome(via_meta) == "success" + missing_outcome = {"meta": {"io.agentmiddleware/receipt": {"receipt_id": "r1"}}} + assert module.receipt_id(missing_outcome) is None assert module.receipt_id({}) is None @@ -144,7 +154,7 @@ def test_mcp_json_is_a_valid_local_template() -> None: assert server["type"] == "http" assert server["url"].endswith("/mcp") assert "X-API-Key" in server["headers"] - assert "Idempotency-Key" in server["headers"] + assert "Idempotency-Key" not in server["headers"] def test_readme_documents_every_script_with_status() -> None: