# A2A Protocol Wiki (v1.0.1): Architecture, AgentCard JWS, MCP Bridge, x402/AP2 & Security Encyclopedia Canonical Hub: https://khoaphan.dev/a2a-wiki/ Full Single-File LLM Corpus: https://khoaphan.dev/llms-full.txt Interactive Agent IQ & JCS Playground: https://khoaphan.dev/a2a-iq/ Author: Khoa Phan (https://khoaphan.dev | @khoap1220-hue) | Updated: 2026-12-04 > Zero-filler engineering encyclopedia covering Agent2Agent (`A2A v1.0.1`), Model Context Protocol (`MCP`), `.mcpb` Manifest v0.3 desktop bundles, RFC 8785 JCS + Ed25519 JWKS `agent-card.json` signing, `S4-REJECT-005` ProtoJSON dual-case smuggling guards, `x402 v2` (`HTTP 402`) Base USDC EIP-3009 & Stacks sBTC settlement, Google `AP2` mandates, 11 verified A2A SDK CVEs, and the 8-dimension Agent IQ (`60–160`) benchmark. ## Chapters in This Encyclopedia 1. **A2A vs MCP (2026): Complete Architecture Comparison, `.mcpb` v0.3 Bundles & Bidirectional Bridging** — https://khoaphan.dev/a2a-wiki/a2a-vs-mcp-bridge/ 2. **A2A v0.3 to v1.0.1 Migration Guide: JSON-RPC Methods, ProtoJSON Enums & Dual-Card Compatibility** — https://khoaphan.dev/a2a-wiki/v0-3-to-v1-0-migration/ 3. **Signing `/.well-known/agent-card.json` with Ed25519 JWKS, RFC 8785 JCS & ProtoJSON `S4-REJECT-005` Guard** — https://khoaphan.dev/a2a-wiki/agent-card-jws-rfc8785/ 4. **`x402` HTTP 402 & AP2 Agent Payments Wiki: Base USDC EIP-3009, Stacks sBTC & Integer Minor-Unit Caps** — https://khoaphan.dev/a2a-wiki/x402-ap2-agent-payments/ 5. **A2A & MCP Security Encyclopedia: 11 SDK CVEs, 5-Layer Tool Poisoning, SSRF Webhooks & Agent IQ Rubric** — https://khoaphan.dev/a2a-wiki/security-cves-and-iq-benchmark/ ## Companion 1-Click `.mcpb` Bundles (Manifest v0.3) - `a2a-wiki.mcpb`: https://github.com/khoap1220-hue/a2a-wiki/releases/latest/download/a2a-wiki.mcpb - `a2a-iq-mcp.mcpb`: https://github.com/khoap1220-hue/a2a-iq-mcp/releases/latest/download/a2a-iq-mcp.mcpb - `mcp-tool-guard.mcpb`: https://github.com/khoap1220-hue/mcp-tool-guard/releases/latest/download/mcp-tool-guard.mcpb - `a2a-registry-bridge-mcp.mcpb`: https://github.com/khoap1220-hue/a2a-registry-bridge-mcp/releases/latest/download/a2a-registry-bridge-mcp.mcpb - `a2a-x402-guard-mcp.mcpb`: https://github.com/khoap1220-hue/a2a-x402-guard-mcp/releases/latest/download/a2a-x402-guard-mcp.mcpb - `a2a-task-orchestrator-mcp.mcpb`: https://github.com/khoap1220-hue/a2a-task-orchestrator-mcp/releases/latest/download/a2a-task-orchestrator-mcp.mcpb ## Frequently Asked Questions (A2A v1.0.1 & MCP) ### Q: What is the difference between A2A and MCP? Model Context Protocol (MCP) is a vertical agent-to-tool and agent-to-data protocol (JSON-RPC 2.0 over stdio or Streamable HTTP) where an LLM host inspects deterministic JSON Schemas and invokes tools, resources, and prompts directly. Agent2Agent (A2A v1.0.1) is a horizontal agent-to-agent delegation protocol where autonomous peers discover signed capabilities at /.well-known/agent-card.json and collaborate over opaque, stateful Tasks (SendMessage, SendStreamingMessage, GetTask, CancelTask) without exposing internal prompts, memory, or private tool credentials. ### Q: What changed from A2A v0.3 to v1.0.1? A2A v1.0.1 moved discovery from /.well-known/agent.json to /.well-known/agent-card.json, replaced top-level url, protocolVersion, and preferredTransport with non-empty supportedInterfaces[] ({url, protocolBinding, protocolVersion: '1.0'}), renamed slash JSON-RPC methods (message/send, tasks/get) to PascalCase (SendMessage, GetTask, CancelTask), switched task and role enums to ProtoJSON SCREAMING_SNAKE_CASE (TASK_STATE_WORKING, ROLE_USER), unified Part into a flat oneof (text, raw, url, data without a kind discriminator), and wrapped securitySchemes in explicit Proto3 oneof keys such as httpAuthSecurityScheme. ### Q: How do you sign agent-card.json with Ed25519 and RFC 8785 JCS? Remove the top-level signatures array from the AgentCard object, serialize the remaining JSON object using RFC 8785 JSON Canonicalization Scheme (UTF-16 code unit key sorting, ECMAScript shortest number representation, compact UTF-8 with zero insignificant whitespace), build an unpadded base64url protected JWS header ({alg: 'EdDSA', cty: 'application/a2a-agent-card+json', kid: '', typ: 'JOSE'}), sign ASCII(protected_b64) + '.' + UTF8(jcs_payload) with an RFC 8032 Ed25519 private key, and publish the matching OKP Ed25519 public key out-of-band at /.well-known/jwks.json. ### Q: What is S4-REJECT-005 in A2A ProtoJSON vs RFC 8785 JCS? S4-REJECT-005 (flagged as A2A_JSON_DUAL_CASE_SMUGGLING) is the conformance and security guard against parser-differential signature smuggling. Standard ProtoJSON parsers accept both camelCase (defaultInputModes) and snake_case (default_input_modes) or overwrite duplicate JSON keys, whereas RFC 8785 JCS treats them as distinct lexicographical keys. A hardened A2A v1.0.1 verifier rejects duplicate keys and simultaneous snake_case/camelCase field pairs during JSON decoding before verifying JWS signatures. ### Q: What is an .mcpb bundle in MCP? An .mcpb (MCP Bundle, formerly Desktop Extension .dxt) is a ZIP-archived single-click desktop package governed by Manifest v0.3 (manifest.json) containing a local stdio MCP server, runtime entrypoints using CWD-safe ${__dirname} paths, a 256x256 icon, typed user_config prompts, and tool declarations for zero-terminal installation in Claude Desktop, Cursor, and compatible IDEs. ### Q: How does x402 work with A2A and AP2? x402 v2 uses HTTP 402 Payment Required headers (PAYMENT-REQUIRED / PAYMENT-SIGNATURE / PAYMENT-RESPONSE) to settle per-call machine payments such as Base Mainnet USDC (eip155:8453 via EIP-3009 transferWithAuthorization) or Stacks sBTC in exact integer atomic units. Google AP2 (Agent Payments Protocol) provides the cryptographic authorization layer above settlement via signed IntentMandate, CartMandate, and PaymentMandate objects enforcing spend caps, payee allowlists, expiry bounds, and 4-tuple idempotency locks. ### Q: What are the 2026 A2A SDK CVEs and how do you scan lockfiles for them? Eleven 2025-2026 advisories affect official and community A2A SDKs across Python (CVE-2026-90790 webhook SSRF in a2a-sdk <= 1.1.3; CVE-2025-6167 path traversal in python-a2a < 0.5.6), TypeScript (CVE-2026-118128 Task FSM race in @a2a-js/sdk <= 1.1.0), Go (CVE-2026-116478 error leak in a2a-go <= 2.4.0), Rust (CVE-2026-113706 historyLength leak in a2a-rs <= 0.4.3), and Java/Maven (CVE-2026-90819 and CVE-2026-111761..111765 in io.a2a.sdk < 1.3.2.Final). Because several advisories are commit-mapped in OSV, run a2a-card-guard sca . across uv.lock, package-lock.json, go.mod, Cargo.lock, and pom.xml. ### Q: How is the 8-Dimension A2A & MCP Agent IQ (60-160) calculated? The deterministic Agent IQ benchmark evaluates an LLM or autonomous agent across 8 binary/rubric protocol security dimensions (D1 Protocol Discovery, D2 RFC 8785 JCS/JWKS, D3 5-Layer Tool-Poisoning Immunity, D4 Task FSM Isolation, D5 Monotonic Scope Attenuation, D6 x402/AP2 Integer Math, D7 JSON-RPC Dual-Case Smuggling, D8 Byzantine Quorum & Sybil Collapse) using IQ = 60 + round((passed / 8) * 100), producing a SHA-256 attested scorecard from 60 to 160. --- # A2A vs MCP (2026): Complete Architecture Comparison, .mcpb v0.3 Bundles & Bidirectional Bridging Canonical URL: https://khoaphan.dev/a2a-wiki/a2a-vs-mcp-bridge/ Author: Khoa Phan (https://khoaphan.dev) | Updated: 2026-12-04 ## 1. Orthogonal Protocol Layers: Horizontal Delegation (A2A) vs Vertical Execution (MCP) Production multi-agent architectures use **Agent2Agent (`A2A v1.0.1`)** and **Model Context Protocol (`MCP 2025-11-25` / Stateless `2026-07-28`)** as complementary, orthogonal layers rather than competing transports: - **MCP (Vertical `Agent -> Tool / Resource / Prompt`):** Connects a single reasoning runtime (Claude Desktop, Cursor, Windsurf, or an internal orchestrator) to deterministic tools, database connectors, and prompt templates via `JSON-RPC 2.0` over `stdio` or `Streamable HTTP`. The caller inspects exact `inputSchema` / `outputSchema` definitions and supplies explicit parameters. - **A2A v1.0.1 (Horizontal `Agent <-> Agent`):** Connects independent, opaque autonomous agents across organizational or trust boundaries. Peers discover signed capabilities via `/.well-known/agent-card.json` and exchange goal-oriented `Message` turns and `Artifact` outputs inside a stateful `Task` lifecycle (`SendMessage`, `SendStreamingMessage`, `GetTask`, `CancelTask`) without revealing internal system prompts, reasoning traces, or downstream API keys. | Dimension | Model Context Protocol (`MCP`) | Agent2Agent Protocol (`A2A v1.0.1`) | | :--- | :--- | :--- | | **Topology** | Vertical (`Host/Agent -> Tool/Resource`) | Horizontal (`Client Agent <-> Remote Peer Agent`) | | **Abstraction** | Deterministic function call (`tools/call`) | Opaque goal delegation (`SendMessage` -> `Task`) | | **Discovery** | Runtime `initialize` -> `tools/list` | HTTPS `/.well-known/agent-card.json` + `jwks.json` | | **Wire Bindings** | `stdio`, `Streamable HTTP` (POST + SSE) | `JSONRPC`, `HTTP+JSON` (REST), `GRPC`, custom URI | | **State Model** | Stateless per call (or session-scoped stream) | Explicit `TaskState` FSM (`SUBMITTED` -> `WORKING` -> `COMPLETED`) | | **Opacity** | White-box JSON Schema inputs/outputs | Black-box internal planning, tools & memory | | **Attestation** | JCS SHA-256 `tools/list` lockfile pinning | RFC 8785 JCS + RFC 7515 `EdDSA` JWS (`signatures[]`) | | **Desktop Packaging** | `.mcpb` Manifest v0.3 ZIP bundle | Registry `AgentCard` URL + `.mcpb` bridge server | | **Payments** | Tool-level `x402` metadata / API keys | `x402 v2` (`HTTP 402`) + Google `AP2` `CartMandate` | | **Primary Threats** | 5-layer tool poisoning & `ToolAnnotations` rug-pull | Unsigned card spoofing, `S4-REJECT-005`, webhook SSRF | ## 2. Inside `.mcpb` Manifest v0.3 Desktop Bundles An `.mcpb` archive (**MCP Bundle**, standardized from Anthropic's `.dxt` specification) packages a local `stdio` server so developers install it in 1 click without global path drift. Critical `manifest_version: "0.3"` invariants: 1. **CWD-Safe Entrypoints (`${__dirname}`):** Desktop hosts spawn servers from `/` or `C:\Windows\System32`; always anchor module paths via `${__dirname}` rather than relative `./`. 2. **Explicit `ToolAnnotations`:** Declare `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` so security guards (`mcp-tool-guard`) can pin behavior hashes. 3. **Zero-Secret `user_config`:** Collect API tokens or workspace paths via OS keychain-backed `user_config` fields (`sensitive: true`) rather than hardcoded `env` values. ```json { "manifest_version": "0.3", "name": "a2a-registry-bridge-mcp", "version": "1.0.0", "display_name": "A2A v1.0.1 <-> MCP Registry Bridge & Ed25519 Signer", "description": "Bidirectional A2A v1.0.1 AgentCard <-> MCP tools converter and pure-Python RFC 8032 Ed25519 JCS signer.", "author": { "name": "Khoa Phan", "url": "https://khoaphan.dev" }, "icon": "icon.png", "server": { "type": "python", "entry_point": "server/main.py", "mcp_config": { "command": "uv", "args": ["run", "--directory", "${__dirname}", "python", "-B", "${__dirname}/server/main.py"], "env": { "PYTHONDONTWRITEBYTECODE": "1" } } }, "tools": [ { "name": "bridge_agent_card_to_mcp_tools", "description": "Project verified A2A v1.0.1 AgentSkill entries into typed MCP tool schemas." } ], "license": "MIT" } ``` ## 3. Bidirectional Bridging Pattern (`A2A <-> MCP`) with Monotonic Attenuation When an A2A orchestrator delegates a subtask to a worker agent that calls MCP tools internally, **Confused Deputy** escalation occurs if the worker forwards ambient MCP credentials broader than the caller's A2A grant. Enforce monotonic narrowing (`child <= parent`) at the bridge boundary: ```python from dataclasses import dataclass from typing import Any @dataclass(frozen=True) class AttenuatedGrant: tenant_id: str allowed_tools: frozenset[str] max_spend_minor_units: int allowed_payees: frozenset[str] expires_at: int def project_a2a_skills_to_mcp_tools(agent_card: dict[str, Any]) -> list[dict[str, Any]]: """Convert A2A v1.0.1 AgentCard skills[] into read-only-annotated MCP Tool definitions.""" if not agent_card.get("supportedInterfaces"): raise ValueError("CARD-DISC-006: A2A v1.0.1 AgentCard requires non-empty supportedInterfaces[]") endpoint = agent_card["supportedInterfaces"][0]["url"] mcp_tools: list[dict[str, Any]] = [] for skill in agent_card.get("skills", []): mcp_tools.append({ "name": f"a2a_{skill['id'].replace('-', '_')}", "description": f"[A2A Peer {endpoint}] {skill['description']}", "inputSchema": { "type": "object", "required": ["prompt", "idempotency_key"], "additionalProperties": False, "properties": { "prompt": {"type": "string", "minLength": 1, "maxLength": 16000}, "context_id": {"type": "string"}, "idempotency_key": {"type": "string", "minLength": 8} } }, "annotations": { "title": skill["name"], "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True } }) return mcp_tools def attenuate_child_grant(parent: AttenuatedGrant, requested_tools: set[str], requested_cap: int, requested_payees: set[str], requested_exp: int) -> AttenuatedGrant: """Fail-closed A2A-06 monotonic attenuation across A2A -> MCP hops.""" if not requested_tools.issubset(parent.allowed_tools): escalated = sorted(requested_tools - parent.allowed_tools) raise PermissionError(f"A2A_TOOL_PRIVILEGE_ESCALATION: {escalated}") if not requested_payees or not requested_payees.issubset(parent.allowed_payees): raise PermissionError("A2A_PAYEE_ALLOWLIST_DROPPED_OR_WIDENED") if requested_cap < 0 or requested_cap > parent.max_spend_minor_units: raise PermissionError("A2A_SPEND_CAP_ESCALATION") if requested_exp > parent.expires_at: raise PermissionError("A2A_EXPIRY_EXTENSION_FORBIDDEN") return AttenuatedGrant( tenant_id=parent.tenant_id, allowed_tools=frozenset(requested_tools), max_spend_minor_units=requested_cap, allowed_payees=frozenset(requested_payees), expires_at=requested_exp, ) ``` --- # A2A v0.3 to v1.0.1 Migration Guide: JSON-RPC Methods, ProtoJSON Enums & Dual-Card Compatibility Canonical URL: https://khoaphan.dev/a2a-wiki/v0-3-to-v1-0-migration/ Author: Khoa Phan (https://khoaphan.dev) | Updated: 2026-12-04 ## 1. Breaking Wire Changes from A2A v0.3.0 to v1.0.1 A2A `v1.0.0` / `v1.0.1` unified the protocol around a canonical Protobuf IDL (`a2a.proto`) with strict ProtoJSON serialization. Upgrading an existing v0.3 agent requires updating six wire surfaces: | Surface | Legacy A2A `v0.3.0` | Canonical A2A `v1.0.1` | Conformance Rule | | :--- | :--- | :--- | :--- | | **Well-Known Path** | `/.well-known/agent.json` | `/.well-known/agent-card.json` | `CARD-DISC-002` | | **Transport / URL** | Top-level `url`, `protocolVersion`, `preferredTransport` | `supportedInterfaces: [{url, protocolBinding, protocolVersion: "1.0"}]` | `CARD-DISC-006` | | **Send / Stream** | `message/send`, `message/stream` | `SendMessage`, `SendStreamingMessage` | `RPC-METH-001` | | **Task Lifecycle RPCs** | `tasks/get`, `tasks/cancel`, `tasks/resubscribe` | `GetTask`, `ListTasks`, `CancelTask`, `SubscribeToTask` | `RPC-METH-002` | | **Extended Card RPC** | `agent/getAuthenticatedExtendedCard` (`supportsAuthenticatedExtendedCard`) | `GetExtendedAgentCard` (`capabilities.extendedAgentCard: true`) | `CARD-EXT-001` | | **TaskState & Role** | `"submitted"`, `"working"`, `"input-required"` / `"user"` | `"TASK_STATE_SUBMITTED"`, `"TASK_STATE_WORKING"`, `"ROLE_USER"` | `PROTO-ENUM-001` | | **Part Envelope** | `{"kind": "text", "text": "..."}` / `{"kind": "file", ...}` | Flat `oneof`: `{"text": "..."}` or `{"url": "...", "mediaType": "..."}` | `PART-ONEOF-001` | | **Security Schemes** | OpenAPI-flat `{"type": "http", "scheme": "bearer"}` | Proto3 `oneof`: `{"httpAuthSecurityScheme": {"scheme": "Bearer"}}` | `SEC-ONEOF-001` | ## 2. Side-by-Side `AgentCard` Wire Diff (`v0.3` vs `v1.0.1`) ```diff -// Legacy /.well-known/agent.json (v0.3.0) -{ - "name": "Order Reconciler", - "url": "https://agent.acme.dev/a2a", - "protocolVersion": "0.3.0", - "preferredTransport": "JSONRPC", - "supportsAuthenticatedExtendedCard": false -} +// Canonical /.well-known/agent-card.json (v1.0.1) +{ + "name": "Order Reconciler", + "version": "1.1.0", + "supportedInterfaces": [ + { + "url": "https://agent.acme.dev/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0" + } + ], + "capabilities": { + "streaming": true, + "pushNotifications": false, + "extendedAgentCard": false + }, + "securitySchemes": { + "bearerAuth": { + "httpAuthSecurityScheme": { "scheme": "Bearer", "bearerFormat": "JWT" } + } + }, + "securityRequirements": [ + { "schemes": { "bearerAuth": { "list": ["a2a:task.invoke"] } } } + ] +} ``` ## 3. Zero-Downtime Dual-Card & Dual-Method Compatibility Adapter During ecosystem transition, enterprise gateways serve **both** `/.well-known/agent-card.json` (`v1.0.1`, Ed25519-signed) and a deterministic read-only projection at `/.well-known/agent.json` (`v0.3.0`), while normalizing legacy slash methods at the JSON-RPC ingress: ```typescript export const LEGACY_V03_TO_V1_METHODS: Readonly> = Object.freeze({ "message/send": "SendMessage", "message/stream": "SendStreamingMessage", "tasks/get": "GetTask", "tasks/list": "ListTasks", "tasks/cancel": "CancelTask", "tasks/resubscribe": "SubscribeToTask", "tasks/pushNotificationConfig/set": "CreateTaskPushNotificationConfig", "tasks/pushNotificationConfig/get": "GetTaskPushNotificationConfig", "tasks/pushNotificationConfig/list": "ListTaskPushNotificationConfigs", "tasks/pushNotificationConfig/delete": "DeleteTaskPushNotificationConfig", "agent/getAuthenticatedExtendedCard": "GetExtendedAgentCard", }); export const V03_TO_V1_TASK_STATE: Readonly> = Object.freeze({ "submitted": "TASK_STATE_SUBMITTED", "working": "TASK_STATE_WORKING", "input-required": "TASK_STATE_INPUT_REQUIRED", "auth-required": "TASK_STATE_AUTH_REQUIRED", "completed": "TASK_STATE_COMPLETED", "canceled": "TASK_STATE_CANCELED", "failed": "TASK_STATE_FAILED", "rejected": "TASK_STATE_REJECTED", }); export function normalizeJsonRpcMethod(method: string): { canonical: string; isLegacyV03: boolean } { if (Object.hasOwn(LEGACY_V03_TO_V1_METHODS, method)) { return { canonical: LEGACY_V03_TO_V1_METHODS[method], isLegacyV03: true }; } return { canonical: method, isLegacyV03: false }; } ``` --- # Signing /.well-known/agent-card.json with Ed25519 JWKS, RFC 8785 JCS & ProtoJSON S4-REJECT-005 Guard Canonical URL: https://khoaphan.dev/a2a-wiki/agent-card-jws-rfc8785/ Author: Khoa Phan (https://khoaphan.dev) | Updated: 2026-12-04 ## 1. Cryptographic Pipeline for A2A v1.0.1 `AgentCardSignature` (§8.4.2) Unsigned `/.well-known/agent-card.json` endpoints allow DNS/BGP/CDN attackers or compromised registries to swap `supportedInterfaces[].url` or inject malicious `skills[]` descriptions. A2A v1.0.1 §8.4.2 standardizes detached-payload **RFC 7515 JSON Web Signatures (`signatures[]`)** over **RFC 8785 JSON Canonicalization Scheme (JCS)**: 1. **Strip `signatures`:** Clone the `AgentCard` JSON object and delete only the top-level `"signatures"` key. 2. **RFC 8785 JCS Serialization:** - Sort object keys lexicographically by **UTF-16BE code units** (note: characters above `U+FFFF` encode as surrogate pairs `0xD800..0xDFFF`, differing from naive UTF-8 codepoint sorting!). - Format numbers per **ECMAScript `Number.prototype.toString()`** (`-0.0 -> 0`, integer form for exact integers `< 10^21`, reject `NaN`/`Infinity`). - Emit compact UTF-8 with zero whitespace between tokens. 3. **Protected JWS Header (`EdDSA`):** Encode `{"alg":"EdDSA","cty":"application/a2a-agent-card+json","kid":"","typ":"JOSE"}` using unpadded URL-safe Base64. Never allow `"alg": "none"`, symmetric `"HS256"` on public cards, inline self-asserted `"jwk"`, or arbitrary remote `"jku"`/`"x5u"` headers. 4. **Out-of-Band JWKS (`/.well-known/jwks.json`):** Publish public `OKP` `Ed25519` keys over HTTPS on the provider's verified origin so verifiers match `protected.kid` deterministically. ## 2. Why ProtoJSON Breaks Naive JWS Verification (`S4-REJECT-005` / `A2A_JSON_DUAL_CASE_SMUGGLING`) Cross-SDK interoperability audits (`A2A#2122`, `a2a-js#627`, `a2a-tck#261`) exposed a subtle parser differential between **RFC 8785 JCS** and **Google Protobuf JSON (`ProtoJSON`)**: | Input Anomaly | RFC 8785 JCS Verifier | Unhardened ProtoJSON Parser | Security Impact | | :--- | :--- | :--- | :--- | | **Dual-Case Twins** (`defaultInputModes` + `default_input_modes`) | Preserves both keys in canonical digest | Hydrates both into the same Proto3 field (last wins) | Attacker smuggles unverified field values past JWS check | | **Duplicate JSON Keys** (`{"url": "https://good", "url": "https://evil"}`) | Undefined / last-key overwrite in `json.loads` | Last key wins or silently overwrites | Signature mismatch or SSRF endpoint swap | | **Default-Value Elision** (`"streaming": false`) | Hashes explicit `false` if present | `emit_defaults=False` drops `false` on re-serialize | Cross-SDK re-serialization breaks valid Ed25519 signatures | **Mandatory Mitigation (`S4-REJECT-005`):** Parse raw `agent-card.json` bytes with a strict `object_pairs_hook` that rejects both exact duplicate keys and normalized `snake_case <-> camelCase` collisions *before* JCS hashing or Protobuf hydration, and always sign the exact raw JSON document served over HTTPS rather than re-serializing through `MessageToJson`. ## 3. Copy-Paste Python Reference: `S4-REJECT-005` Guard + RFC 8785 JCS + Ed25519 Signer ```python import base64 import json import re from typing import Any def _to_camel(key: str) -> str: return re.sub(r"_([a-zA-Z0-9])", lambda m: m.group(1).upper(), key) def parse_strict_a2a_json(raw_text: str) -> dict[str, Any]: """Enforce S4-REJECT-005: block duplicate keys & snake_case/camelCase smuggling.""" def _pairs_hook(pairs: list[tuple[str, Any]]) -> dict[str, Any]: out: dict[str, Any] = {} seen_canonical: dict[str, str] = {} for k, v in pairs: if k in out: raise ValueError(f"S4-REJECT-005 duplicate JSON key: {k!r}") canon = _to_camel(k) if canon in seen_canonical: raise ValueError( f"A2A_JSON_DUAL_CASE_SMUGGLING (S4-REJECT-005): {k!r} collides with {seen_canonical[canon]!r}" ) seen_canonical[canon] = k out[k] = v return out parsed = json.loads(raw_text, object_pairs_hook=_pairs_hook) if not isinstance(parsed, dict): raise ValueError("AgentCard root must be a JSON object") return parsed def _utf16_sort_key(s: str) -> bytes: return s.encode("utf-16-be") def jcs_canonicalize(value: Any) -> str: """Deterministic RFC 8785 JCS serializer for JSON values.""" if value is None or isinstance(value, bool): return json.dumps(value) if isinstance(value, int): return str(value) if isinstance(value, float): if value != value or value in (float("inf"), float("-inf")): raise ValueError("RFC 8785 forbids NaN and Infinity") if value == 0.0: return "0" if value.is_integer() and abs(value) < 10**21: return str(int(value)) return json.dumps(value, allow_nan=False) if isinstance(value, str): return json.dumps(value, ensure_ascii=False) if isinstance(value, list): return "[" + ",".join(jcs_canonicalize(item) for item in value) + "]" if isinstance(value, dict): items = sorted(value.items(), key=lambda kv: _utf16_sort_key(kv[0])) return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{jcs_canonicalize(v)}" for k, v in items) + "}" raise TypeError(f"Unsupported JSON type: {type(value)!r}") def b64url_encode(raw: bytes) -> str: return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") def build_signing_input(agent_card: dict[str, Any], kid: str) -> tuple[str, bytes]: unsigned = {k: v for k, v in agent_card.items() if k != "signatures"} jcs_bytes = jcs_canonicalize(unsigned).encode("utf-8") protected = {"alg": "EdDSA", "cty": "application/a2a-agent-card+json", "kid": kid, "typ": "JOSE"} protected_b64 = b64url_encode(jcs_canonicalize(protected).encode("utf-8")) signing_input = f"{protected_b64}.".encode("ascii") + jcs_bytes return protected_b64, signing_input ``` --- # x402 HTTP 402 & AP2 Agent Payments Wiki: Base USDC EIP-3009, Stacks sBTC & Integer Minor-Unit Caps Canonical URL: https://khoaphan.dev/a2a-wiki/x402-ap2-agent-payments/ Author: Khoa Phan (https://khoaphan.dev) | Updated: 2026-12-04 ## 1. How `x402 v2` (`HTTP 402`) and Google `AP2` Compose in A2A v1.0.1 Autonomous commerce combines two complementary layers: - **Google AP2 (`Agent Payments Protocol` — Authorization Layer):** Cryptographically signed `IntentMandate` -> `CartMandate` -> `PaymentMandate` objects proving *what* a human or root treasury authorized an agent to buy, from *which* `allowed_payees`, within *what* integer `max_spend_minor_units` ceiling and Unix `expires_at` window. - **`x402 v2` (`HTTP 402 Payment Required` — Settlement Transport):** Per-request machine settlement rail where an A2A skill or MCP gateway responds with `HTTP 402` + `PAYMENT-REQUIRED` metadata, and the buyer retries with a signed `PAYMENT-SIGNATURE` payload settled on **Base Mainnet USDC (`eip155:8453`)** or **Stacks sBTC (`SIP-010`)**. | Rail / Layer | Wire Artifact | Asset & Precision | Replay & Finality Guard | | :--- | :--- | :--- | :--- | | **AP2 Authorization** | `CartMandate` + `PaymentMandate` (JWS) | ISO-4217 / atomic minor units (`int`) | `mandate_id` + `allowed_payees` + `expires_at` | | **Base `x402 v2` (EVM)** | `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` | Base USDC `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (`6` dec) | EIP-712 `EIP-3009` 32-byte random `nonce` + `validBefore` | | **Stacks `x402` (Bitcoin L2)** | `X402_RELAY` RPC + Clarity post-conditions | `sBTC` (`8` dec satoshis, 128-bit `uint`) | `HTTP 409 PAYER_NONCE_UNVERIFIED` + 3-stage DO `is_terminal=1` | | **Gateway Ledger** | SQLite `WAL` / PostgreSQL `ON CONFLICT` | Exact integer atomic strings/ints (`0` floats) | 4-tuple `(tenant_id, token_id, tool_name, client_key)` + `args_sha256` | ## 2. Hard FinTech Invariants (`SPEC_CLASS_09` & `A2A-06`) 1. **Zero IEEE-754 Floating-Point Money Math:** Binary floats (`0.1 + 0.2 == 0.30000000000000004`) corrupt JCS hashes and fee splits. Parse human strings exclusively through `decimal.Decimal` and execute all fee/cap math in strict integer atomic units: `net_atomic = (gross_atomic * (10_000 - fee_bps)) // 10_000`. 2. **Bounded Non-Negative Slippage:** Reject `slippage_bps < 0` or `slippage_bps > 5000` (`A2A_INVALID_SLIPPAGE_BPS`). 3. **Payee & Expiry Binding:** Verify `mandate.pay_to in grant.allowed_payees` and `mandate.expires_at <= grant.expires_at` before signing an EIP-3009 or sBTC authorization. 4. **4-Tuple Idempotency Lock:** Scope payment-bearing tool retries by `(tenant_id, token_id, tool_name, client_key)` so retrying after a network timeout replays the settled receipt (`PAYMENT-RESPONSE`) instead of double-charging. ## 3. Copy-Paste Python Reference: Exact USDC Atomic Math & AP2 / x402 Mandate Guard ```python from decimal import Decimal, InvalidOperation import re import time from typing import Any BASE_MAINNET_NETWORK = "eip155:8453" BASE_USDC_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" USDC_DECIMALS = 6 EVM_ADDR_RE = re.compile(r"^0x[0-9a-fA-F]{40}$") def usdc_str_to_atomic_int(amount_usdc: str) -> int: """Exact Decimal -> 6-decimal USDC atomic integer conversion (zero IEEE-754 float).""" try: dec = Decimal(amount_usdc.strip()) except (InvalidOperation, AttributeError) as exc: raise ValueError(f"Invalid USDC string: {amount_usdc!r}") from exc if not dec.is_finite() or dec <= 0: raise ValueError("USDC amount must be finite and > 0") scaled = dec * (Decimal(10) ** USDC_DECIMALS) if scaled != int(scaled): raise ValueError(f"Exceeds {USDC_DECIMALS} decimal places: {amount_usdc!r}") return int(scaled) def compute_net_settlement_atomic(gross_atomic: int, fee_bps: int) -> int: if isinstance(gross_atomic, bool) or not isinstance(gross_atomic, int) or gross_atomic <= 0: raise ValueError("gross_atomic must be a positive int") if isinstance(fee_bps, bool) or not isinstance(fee_bps, int) or not (0 <= fee_bps <= 10_000): raise ValueError("fee_bps must be an int in [0, 10000]") return (gross_atomic * (10_000 - fee_bps)) // 10_000 def verify_x402_ap2_mandate( mandate: dict[str, Any], *, allowed_payees: set[str], max_spend_atomic: int, delegation_expires_at: int, now_epoch: int | None = None, ) -> dict[str, Any]: now = int(time.time()) if now_epoch is None else now_epoch amt = mandate.get("amount_minor_units") if isinstance(amt, bool) or not isinstance(amt, int) or amt <= 0: raise ValueError("A2A_FLOAT_OR_NONPOSITIVE_AMOUNT: integer minor units required") if amt > max_spend_atomic: raise PermissionError(f"A2A_SPEND_CAP_EXCEEDED: {amt} > {max_spend_atomic}") pay_to = str(mandate.get("pay_to") or "") if not EVM_ADDR_RE.match(pay_to) or pay_to not in allowed_payees: raise PermissionError(f"A2A_UNAUTHORIZED_PAYEE: {pay_to!r}") slip = mandate.get("slippage_bps", 0) if isinstance(slip, bool) or not isinstance(slip, int) or not (0 <= slip <= 5000): raise ValueError(f"A2A_INVALID_SLIPPAGE_BPS: {slip!r}") exp = mandate.get("expires_at") if isinstance(exp, bool) or not isinstance(exp, int) or now > exp or exp > delegation_expires_at: raise PermissionError("A2A_PAYMENT_MANDATE_EXPIRED_OR_EXCEEDS_HOP") if not str(mandate.get("mandate_id") or "").strip() or not str(mandate.get("idempotency_key") or "").strip(): raise ValueError("A2A_MISSING_MANDATE_OR_IDEMPOTENCY_KEY") return {"approved": True, "network": BASE_MAINNET_NETWORK, "asset": BASE_USDC_CONTRACT, "amount_atomic": amt} ``` --- # A2A & MCP Security Encyclopedia: 11 SDK CVEs, 5-Layer Tool Poisoning, SSRF Webhooks & Agent IQ Rubric Canonical URL: https://khoaphan.dev/a2a-wiki/security-cves-and-iq-benchmark/ Author: Khoa Phan (https://khoaphan.dev) | Updated: 2026-12-04 ## 1. Ground-Truth Catalog of 11 A2A SDK CVEs (`a2a-sca` Multi-Language Lockfile Matrix) Standard package vulnerability scanners often miss 2026 `a2aproject/*` OSV entries mapped to git commit ranges. Pinning lockfiles (`uv.lock`, `poetry.lock`, `package-lock.json`, `pnpm-lock.yaml`, `go.mod`, `Cargo.lock`, `pom.xml`) against all 11 verified advisories closes these exploit paths: | Advisory ID | Ecosystem & Package | Vulnerable | Patched | Vulnerability Class & Attack Vector | | :--- | :--- | :---: | :---: | :--- | | `CVE-2026-90790` | PyPI `a2a-sdk` | `<= 1.1.3` | `1.1.4` | Push Notification webhook SSRF hitting internal/cloud metadata | | `CVE-2025-6167` | PyPI `python-a2a` | `< 0.5.6` | `0.5.6` | Workflow identifier path traversal outside workspace root | | `CVE-2026-118128` | npm `@a2a-js/sdk` | `<= 1.1.0` | `1.2.0` | Task FSM concurrent status transition race / TOCTOU | | `CVE-2026-116478` | Go `github.com/a2aproject/a2a-go` | `<= 2.4.0` | `2.5.0` | Internal network topology & socket error disclosure in push handler | | `CVE-2026-113706` | Cargo `a2a-rs` / `a2a-lf` | `<= 0.4.3` | `>= 0.4.4` | Cross-turn `historyLength` conversation history disclosure | | `CVE-2026-90819` | Maven `io.a2a.sdk:*` | `< 1.3.0` | `1.3.0.Final` | Push `Authorization` HTTP header CRLF response splitting | | `CVE-2026-111761` | Maven `io.a2a.sdk:server-common` | `< 1.3.0` | `1.3.0.Final` | Unvalidated push webhook SSRF to RFC 1918 & link-local targets | | `CVE-2026-111762` | Maven `io.a2a.sdk:transport-rest` | `< 1.3.0` | `1.3.0.Final` | Cleartext Bearer token logged on malformed Protobuf payload | | `CVE-2026-111763` | Maven `io.a2a.sdk:client` | `< 1.3.0` | `1.3.0.Final` | Cross-domain API key leak on HTTP `30x` redirect | | `CVE-2026-111764` | Maven `io.a2a.sdk:server-common` | `< 1.3.0` | `1.3.0.Final` | Fail-open `InMemoryTaskStore` cross-tenant `taskId` IDOR | | `CVE-2026-111765` | Maven `io.a2a.sdk:http-client-android` | `< 1.3.2` | `1.3.2.Final` | Synchronous POST cross-authority credential redirect leak | ## 2. 5-Layer MCP Tool-Poisoning & `ToolAnnotations` Rug-Pull Defense Hashing `sha256(name + description)` alone leaves `inputSchema.$defs`, `outputSchema`, and `annotations` unprotected. `mcp-tool-guard` combines full-envelope RFC 8785 JCS SHA-256 lockfile pinning with 5 deterministic inspection layers: 1. **Layer 1 — Structural & Directive Injection:** Hidden HTML/XML comments (``), system-role spoofing, and covert cross-tool invocation instructions inside `description` or `examples`. 2. **Layer 2 — Invisible Unicode & BiDi Trojan Source:** Zero-width characters (`U+200B..U+200D`, `U+FEFF`), right-to-left overrides (`U+202A..U+202E`, `U+2066..U+2069`), and invisible Plane-14 Unicode Tags (`U+E0000..U+E007F`). 3. **Layer 3 — UTS #39 Confusable Homoglyphs & Typosquatting:** Mixed-script Cyrillic/Greek lookalike identifiers impersonating trusted MCP servers or tool names. 4. **Layer 4 — Schema `$defs` & `ToolAnnotations` Rug-Pulls:** Detecting silent post-approval flips such as `readOnlyHint: true -> false`, `destructiveHint: false -> true`, or `openWorldHint: false -> true`. 5. **Layer 5 — Entropy Anomaly & Exfiltration Sinks:** High-entropy encoded payloads, external webhook/IMG markdown beacons, and cloud metadata SSRF targets (`169.254.169.254`, `metadata.google.internal`, CGNAT `100.64.0.0/10`, IPv4-mapped IPv6 `::ffff:127.0.0.1`). ## 3. DNS-Pinned Webhook SSRF Guard & 8-Dimension Agent IQ Rubric (`60–160`) ```python import ipaddress import socket from urllib.parse import urlparse EXTRA_BLOCKED_CIDRS = ( ipaddress.ip_network("0.0.0.0/8"), ipaddress.ip_network("100.64.0.0/10"), # Tailscale / Carrier-Grade NAT ipaddress.ip_network("169.254.0.0/16"), # AWS/GCP/Azure IMDSv1/v2 link-local ipaddress.ip_network("fc00::/7"), # IPv6 Unique Local ipaddress.ip_network("fe80::/10"), # IPv6 Link-Local ) def assert_ssrf_safe_https_webhook(raw_url: str) -> tuple[str, list[str]]: parsed = urlparse(raw_url.strip()) if parsed.scheme != "https" or not parsed.hostname: raise ValueError("A2A_SSRF_BLOCKED_TARGET: push webhook must use https:// with explicit host") host = parsed.hostname.lower().rstrip(".") if host in {"localhost", "metadata.google.internal", "metadata", "instance-data"} or host.endswith((".local", ".internal", ".localhost")): raise ValueError(f"A2A_SSRF_BLOCKED_HOST: {host}") port = parsed.port or 443 infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) pinned_ips: list[str] = [] for _, _, _, _, sockaddr in infos: ip_obj = ipaddress.ip_address(sockaddr[0]) check_ip = ip_obj.ipv4_mapped if isinstance(ip_obj, ipaddress.IPv6Address) and ip_obj.ipv4_mapped else ip_obj if ( check_ip.is_private or check_ip.is_loopback or check_ip.is_link_local or check_ip.is_multicast or check_ip.is_reserved or any(check_ip in net for net in EXTRA_BLOCKED_CIDRS) ): raise ValueError(f"A2A_SSRF_BLOCKED_IP: {host} resolved to non-public {ip_obj}") pinned_ips.append(str(ip_obj)) return host, sorted(set(pinned_ips)) ``` ### Deterministic Agent IQ Formula (`IQ 60–160` at `khoaphan.dev/a2a-iq/`) `IQ = 60 + round((passed_dimensions / 8) * 100)` across: - **D1:** A2A v1.0.1 Discovery (`/.well-known/agent-card.json` + `supportedInterfaces[]`) - **D2:** RFC 8785 JCS + Out-of-Band Ed25519 JWKS Verification - **D3:** 5-Layer MCP Tool-Poisoning & Full-Envelope JCS Pinning - **D4:** CSPRNG `(tenant, client_id)` Task FSM CAS Atomicity - **D5:** Monotonic Multi-Hop `A2A -> MCP` Capability Attenuation - **D6:** `x402 / AP2` Integer Minor-Unit Math & 4-Tuple WAL Idempotency - **D7:** JSON-RPC 2.0 & `S4-REJECT-005` Dual-Case Smuggling Rejection - **D8:** Byzantine `2f + 1` Quorum & Sybil `kid`/Domain Collapse --- ## Transparency & Direct Async Engineering Contact - **Practice:** Khoa Phan (`https://khoaphan.dev`) — Transparent A2A (AI-Orchestrated Senior Engineering) operation working 100% via written specifications, Email (`mailto:khoa@khoaphan.dev`), and automated test-verified GitHub Pull Requests (zero live meetings). - **Fixed-Scope Sprints:** https://khoaphan.dev/services/ (`Custom MCP Server $145–$290`, `48h Idempotent Webhook Fix $150`, `72h A2A v1.0.1 & MCP Security Hardening $450`, `$0` upfront Pay-on-Green-PR-Pass first-time trials `$145–$250`). - **Signed A2A v1.0.1 AgentCard:** https://khoaphan.dev/.well-known/agent-card.json - **Public Ed25519 JWKS:** https://khoaphan.dev/.well-known/jwks.json