diff --git a/README.md b/README.md
index ad9f36d..3ddf7f8 100644
--- a/README.md
+++ b/README.md
@@ -8,12 +8,14 @@
+
+
## What it is, in ten seconds
@@ -71,7 +73,8 @@ agent-commerce doctor
Requires **Node >= 22**. The package includes the `agent-commerce` CLI
(`init`, `validate`, `start`, `doctor`, `reconcile`, `resolve`, `demo`,
-`import openapi`, `version`) and a library for embedding the gateway.
+`import openapi`, `export mcp-registry`, `version`) and a library for embedding
+the gateway.
The default install excludes optional protocol, payment and authorization
peers. The OpenAPI parser is a regular dependency because import is part of the
CLI.
@@ -84,10 +87,10 @@ agent-commerce start --config config.yaml --env-file .env
Install the optional peers for the features you enable, listed below. Missing
startup imports stop the gateway with an error naming the package; missing
Solana, NEAR or CDP peers fail provider health checks or payment requests.
-`start`, `validate`, `doctor`, `reconcile` and `resolve` accept `--env-file ` to
-load environment variables before reading the config. Variables already set in
-the environment take precedence. To embed the gateway in your own process, use
-the library:
+`start`, `validate`, `doctor`, `reconcile`, `resolve` and `export mcp-registry`
+accept `--env-file ` to load environment variables before reading the
+config. Variables already set in the environment take precedence. To embed the
+gateway in your own process, use the library:
```ts
import { createGateway, loadConfig, receipts } from '@devlab.group/agent-commerce';
@@ -303,17 +306,22 @@ See [docs/configuration.md](docs/configuration.md).
## Protocol support
-| Protocol | Status | Pinned revision |
-| ------------ | ------------ | ------------------------------------------------------------------------------------------------------------ |
-| **HTTP** | Supported | native routes |
-| **MCP** | Supported | `2026-07-28` and `2025-11-25`, `@modelcontextprotocol/server@2.3.0` |
-| **x402** | Supported | x402 v2 (`@x402/core`, `@x402/evm`, `@x402/svm`, `@x402/near`), scheme `exact`, EVM and Solana; NEAR partial |
-| **MPP** | Experimental | `mppx@0.13.1`, `charge` + `evm` + EIP-3009, USDC on Base Sepolia and Base |
-| **A2A** | Experimental | A2A v1.0.1, binding `JSONRPC`, method `SendMessage`, x402 extension |
-| **ACP** | Experimental | ACP `2026-04-17`, REST checkout + discovery |
-| **AP2** | Experimental | AP2 `v0.2.0`, Direct Checkout Mandate verification |
-| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230`: signed quotes on x402 EVM offers |
-| UCP | Planned | no implementation |
+
+
+| Protocol | Status | Pinned revision | Implemented subset |
+| ------------ | ------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
+| **HTTP** | Supported | native | resource routes and rail-specific payment headers |
+| **MCP** | Supported | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping |
+| **x402** | Supported | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding |
+| **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A |
+| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension |
+| **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations |
+| **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement |
+| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` |
+
+
+
+UCP is planned and has no implementation.
[AP2](docs/protocols/ap2.md) is an authorization method, not a transport. It verifies a
mandate before a paid resource settles; the gateway does not issue the mandate
@@ -333,11 +341,24 @@ prints the `unsupported` lists for A2A, ACP and AP2 when they are enabled.
### Versioning
-Minor releases may break experimental configurations, integrations or types:
-MPP, A2A, ACP, AP2, ERC-8409 quotes, `agent-commerce import openapi`,
-`PaymentProvider.reconcile`, the `ReceiptStore` methods and types added in
-2.6.0, the `idempotency` resource settings with the store and provider methods
-added in 2.7.0, and the `./testing` entry.
+Minor releases may break experimental configurations, integrations or types.
+This includes MPP, A2A, ACP, AP2, ERC-8409 quotes, the
+[public resource URL](docs/configuration.md#public-resource-url) and
+[Bazaar metadata](docs/configuration.md#bazaar-metadata) in payment
+challenges, and these interfaces:
+
+- `agent-commerce import openapi`.
+- `agent-commerce export mcp-registry`, `doctor --registry` and the
+ `protocols.mcp.registry` keys.
+- `PaymentProvider.reconcile` and the `ReceiptStore` methods and types added
+ in 2.6.0.
+- The `idempotency` resource settings and the store and provider methods added
+ in 2.7.0.
+- `PaymentContext.protocol` and `AdapterHealthComponent.undetermined` (added
+ in 2.8.0), and the `./testing` entry.
+
+A profile moves from experimental to supported only when it meets the
+[promotion criteria](docs/protocols.md#promotion-criteria).
The journal's `Transaction` type, `ReceiptStore` journal methods and
`/api/transactions` response shape are supported. The `transactionId` fields,
@@ -494,6 +515,7 @@ spend real USDC when their opt-ins and credentials are present.
$ npm run agent-commerce -- doctor --config config-demo.yaml
PASS Config valid: 2 resource(s), merchant "Demo Data Store" (using local chain manifest .deploy/local.json for X402_ASSET, X402_ASSET_NAME, X402_ASSET_VERSION, X402_ASSET_DECIMALS, MERCHANT_WALLET, X402_FACILITATOR_PRIVATE_KEY)
+PASS Secrets 6 set (MERCHANT_WALLET, X402_ASSET, X402_ASSET_DECIMALS, X402_ASSET_NAME, X402_ASSET_VERSION, X402_FACILITATOR_PRIVATE_KEY); 8 defaulted (ADMIN_TOKEN, DASHBOARD_ORIGIN, GATEWAY_PORT, GATEWAY_PUBLIC_BASE_URL, MERCHANT_API_BASE_URL, RECEIPT_STORE_PATH, X402_NETWORK, X402_RPC_URL)
PASS Gateway healthy and ready at http://127.0.0.1:8080
PASS Backend 2/2 backend host(s) reachable
PASS Protocols http=on mcp=on (/mcp) a2a=off acp=off
@@ -501,12 +523,13 @@ INFO A2A disabled
INFO ACP disabled
INFO AP2 disabled
PASS Payments x402 v2 (scheme=exact) enabled - LOCAL dev chain (eip155:31337), destination=0x7099…79C8, facilitator=local (in-process), paymentFlow=authorization
+PASS Payments (offers) 1 offer(s) pass their health checks
INFO Payments (MPP) MPP not configured
PASS Storage sqlite schema v5 writable; receipts=2
PASS Transactions none unresolved
PASS Protocol versions reported by gateway /.well-known/agent-commerce
-Score: 8/8 checks passed
+Score: 10/10 checks passed
```
`doctor` compares live settlement terms with local config for each rail and
@@ -514,6 +537,29 @@ resource: offer order, network, token, payee and transfer method, plus decimals
and payment flows when published. Mismatches fail the check. It also names
failing offers when health is published; reasons appear in gateway debug logs.
+`Secrets` lists each config placeholder (`${VAR}`) as missing, set or
+defaulted. Config loading stops at the first missing variable; this check
+reports them all. It fails if any are missing and prints names only, never
+values or defaults.
+
+A check that cannot reach a verdict carries `undetermined`: `unreachable`
+for known transport failures, such as refused or reset connections, timeouts
+or temporary DNS failures; `skipped` when a prerequisite fails. Unresolvable
+hostnames and TLS errors leave the check unmarked.
+Text output appends `[not determined: ]`. The marker does not affect
+status, score or exit code; an unreachable gateway still fails its check.
+
+`--registry` (experimental) adds an `MCP Registry` check. It fetches the
+latest listing for `protocols.mcp.registry.name` from
+`registry.modelcontextprotocol.io`, sending only that name and a fixed
+`include_deleted=true` flag, and compares it with what `export mcp-registry`
+would write. Differences, deprecated or deleted listings, missing listings and
+request failures produce WARN rather than FAIL.
+Recognized transport failures also get the `unreachable` marker. The check
+names differing fields and uses fixed messages for known lifecycle statuses,
+without echoing arbitrary registry values or request error messages. See
+[MCP Registry listing](docs/protocols/mcp.md#mcp-registry-listing).
+
Exits non-zero if anything fails. `--json` for machines.
### `agent-commerce reconcile`
@@ -675,8 +721,9 @@ See [CONTRIBUTING.md](CONTRIBUTING.md).
mainnet, Solana devnet and Solana mainnet, receipts, doctor, deterministic
demo, experimental A2A v1.0.1 and ACP `2026-04-17` checkout adapters,
experimental AP2 v0.2.0 mandate verification, experimental MPP `charge`
-payments, experimental OpenAPI import, and experimental retries after a lost
-response.
+payments, experimental OpenAPI import, experimental retries after a lost
+response, and experimental discovery metadata for x402 Bazaar and MCP Registry
+listings.
**Next** - a `doctor` GitHub Action · UCP ·
autonomous-mode AP2 (open mandates, agent key binding, constraint evaluation) ·
diff --git a/biome.json b/biome.json
index c1d906a..fb7ff14 100644
--- a/biome.json
+++ b/biome.json
@@ -18,7 +18,9 @@
"!contracts/lib",
"!package-lock.json",
"!src/protocols/acp/spec",
- "!tests/fixtures/acp"
+ "!tests/fixtures/acp",
+ "!tests/fixtures/mcp-registry",
+ "!tests/integration/goldens"
]
},
"formatter": {
diff --git a/config.example.yaml b/config.example.yaml
index 4923ea4..7a13df6 100644
--- a/config.example.yaml
+++ b/config.example.yaml
@@ -44,6 +44,13 @@ protocols:
mcp:
enabled: true
mountPath: /mcp
+ # Experimental MCP Registry fields. Export them to server.json with
+ # `agent-commerce export mcp-registry`. The gateway also reports name and
+ # version in MCP serverInfo. See docs/configuration.md#protocolsmcpregistry.
+ # registry:
+ # name: io.github.acme/weather
+ # version: 1.0.0
+ # description: Weather forecasts, paid per call
# A2A (Agent2Agent) v1.0.1 - experimental, off by default.
# Serves JSON-RPC `SendMessage` at mountPath and the Agent Card at
# /.well-known/agent-card.json. Enable at least one resource with
@@ -140,6 +147,13 @@ payments:
# quote:
# enabled: true
# signerPrivateKey: ${X402_QUOTE_SIGNER_KEY}
+ # Experimental discovery. publicResourceUrl replaces resource:// identifiers
+ # with public endpoint URLs in x402 challenges on HTTP, MCP and A2A.
+ # bazaar adds catalog metadata on HTTP and MCP and requires publicResourceUrl.
+ # See docs/configuration.md#public-resource-url.
+ # publicResourceUrl: true
+ # bazaar:
+ # enabled: true
# Settlement order: authorization (the default) calls the backend first
# and settles only if it succeeds; upfront settles first. A paid resource
# can set its own paymentFlow, which applies to the rail that serves it.
diff --git a/docs/configuration.md b/docs/configuration.md
index bbe2c63..1dd0407 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -214,6 +214,43 @@ literal prefix (see
Generated by [`agent-commerce import openapi`](openapi-import.md); nothing
about the field is OpenAPI-specific.
+## `protocols.mcp.registry`
+
+Experimental and optional. This block supplies the listing fields that
+[`agent-commerce export mcp-registry`](protocols/mcp.md#mcp-registry-listing)
+writes to `server.json` and `doctor --registry` compares with the live
+listing. Config loading validates these fields. When started with this block,
+the gateway also reports `name` and `version` as its MCP `serverInfo` at
+`initialize`. Without the block, it reports `agent-commerce` and the package
+version.
+
+```yaml
+protocols:
+ mcp:
+ enabled: true
+ mountPath: /mcp
+ registry:
+ name: io.github.acme/weather
+ version: 1.4.0 # the listing's version, not the package's
+ description: Weather forecasts, paid per call
+```
+
+Config loading checks the following MCP Registry field rules and names invalid
+keys:
+
+- `name`: at most 200 characters, a namespace and a name joined by one `/`.
+ Each side has at least two characters and starts and ends with an ASCII
+ letter or digit. The namespace may also contain `.` and `-`; the name may
+ contain `.`, `_` and `-`.
+- `version`: 1 to 255 characters. Not `latest`, and not a range such as
+ `^1.2.3`, `>= 1.2.3`, `1.x`, `1.*`, `1.2.3 - 2.0.0` or `1.2 || 1.3`. The
+ range check also treats dotted versions containing `x`, `X` or `*` as ranges,
+ including in the prerelease part, so it rejects `1.0.0-next.1`. Quote versions
+ that YAML would read as numbers, such as `"1.4"`.
+- `description`: 1 to 100 characters.
+
+Lengths count Unicode code points.
+
## `protocols.acp`
Experimental, off by default, and absent from a config that predates it. The
@@ -631,12 +668,76 @@ to fit the response headers. Its default is one 4 or 8 KB memory page;
oversized headers cause nginx to reject the response. SDK clients echo quotes
in `PAYMENT-SIGNATURE`, which can reach about 7.4 KB with six quoted offers.
This approaches nginx's default 8 KB limit for a single request header field,
-set by
-[`large_client_header_buffers`](https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers).
+set by [`large_client_header_buffers`](https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers).
Each cache miss requires a signature per EVM offer. Rate-limit unpaid requests
at the edge; see [Denial of service](security.md#denial-of-service).
+### Public resource URL
+
+Experimental and disabled by default. `publicResourceUrl: true` sets an x402
+challenge's `resource.url` to the configured public endpoint for the request's
+surface. This gives indexers a URL they can request in place of the gateway's
+`resource://agent-commerce/...` identifier.
+
+```yaml
+merchant:
+ publicBaseUrl: https://shop.example
+payments:
+ x402:
+ publicResourceUrl: true
+```
+
+| Request arrives on | `resource.url` |
+| ------------------ | ------------------------------------------- |
+| HTTP | `/api/resources//invoke` |
+| MCP | `` |
+| A2A | `` |
+
+Requests without a URL mapping keep the `resource://` form. MPP challenges
+are unchanged, and a resource served on MPP gets no mapping. Enabling the
+option requires `merchant.publicBaseUrl` to be an http:// or https:// URL;
+otherwise config loading fails with `CONFIG_INVALID`.
+
+The URL parser writes each URL with a lowercase scheme and host and no default
+port. `agent-commerce export mcp-registry` uses the same form for the MCP
+endpoint, which gives the Registry listing and x402 challenges matching URL
+strings.
+
+After the option changes, proofs that echo the previous URL are rejected,
+including proofs for A2A tasks still awaiting payment after a restart. Proofs
+that echo another surface's URL are also rejected. Both cases return
+`invalid_payment_requirements` without settlement; the buyer can request and
+pay a new challenge. See [x402](protocols/x402.md#the-resource-url).
+
+### Bazaar metadata
+
+Experimental and disabled by default. `bazaar.enabled: true` adds Bazaar
+discovery metadata to x402 challenges on HTTP and MCP for resources the
+gateway serves on x402: those whose first enabled rail in `payments` is `x402`.
+Enabling it requires `publicResourceUrl: true`; otherwise config loading fails
+with `CONFIG_INVALID`.
+
+```yaml
+payments:
+ x402:
+ publicResourceUrl: true
+ bazaar:
+ enabled: true
+```
+
+During config loading, omissions from HTTP/MCP metadata produce warnings with
+the resource id, affected surfaces and reason. A resource that lists `x402`
+behind an enabled `mpp` gets a warning that names the rail serving it.
+Omitting metadata leaves payment behavior unchanged.
+[x402](protocols/x402.md#bazaar-discovery-metadata) lists the rules.
+
+Choose a facilitator whose `/supported` response lists `bazaar` among its
+extensions. Verify and settle forward metadata only to these remote
+facilitators. Other facilitators receive the proof without metadata. If a
+facilitator lists the extension but rejects payment because of the metadata,
+HTTP buyers can receive repeated 402 challenges.
+
### `payments.mpp`
MPP accepts the `USDC` currency label on the local chain `eip155:31337`, Base
@@ -827,7 +928,8 @@ none of whose listed rails is enabled · `expose` values outside
`protocols.mcp.enabled` is false (likewise `a2a` and `acp`) ·
enabled A2A with no resource exposed through `a2a` · two enabled
protocol mounts that overlap · a mount that claims a route the gateway already
-serves, including the A2A Agent Card and ACP discovery paths · an ACP checkout
+serves, including the A2A Agent Card and ACP discovery paths · a
+`protocols.mcp.registry` value that breaks the field rules above · an ACP checkout
mapping that is incomplete, names a missing or non-`acp` resource, reuses one
resource for two operations, or maps a paid one · an ACP idempotency retention
below 24 hours · an invalid or zero `payTo`/`asset`/`recipient` · an
diff --git a/docs/contract-surface.txt b/docs/contract-surface.txt
index b1d3943..dbc4685 100644
--- a/docs/contract-surface.txt
+++ b/docs/contract-surface.txt
@@ -23,6 +23,7 @@ interface AdapterHealth {
interface AdapterHealthComponent {
readonly name: string;
readonly status: "pass" | "warn" | "fail";
+ readonly undetermined?: "unreachable";
}
interface AdapterHttpRoute {
@@ -373,6 +374,7 @@ interface PaymentContext {
readonly currency: string;
readonly input?: unknown;
readonly metadata?: Readonly>;
+ readonly protocol?: ProtocolName;
readonly requestId: string;
readonly requestedAt: string;
readonly resource: CommerceResource;
diff --git a/docs/contracts.md b/docs/contracts.md
index 53edf38..bc000ee 100644
--- a/docs/contracts.md
+++ b/docs/contracts.md
@@ -299,6 +299,14 @@ persistence must not fail the commerce flow.
Omitting the override keeps the code's default.
- These fields and methods are experimental and may change in a minor
release. The 3.0.0 migration plan makes `getIdempotencyKey` required.
+- 2.8.0 adds two optional, experimental fields that may change in a minor
+ release. Existing 2.7 providers and adapters need no changes.
+ - `PaymentContext.protocol` identifies the request's protocol. On each
+ `createRequirement` call, the pipeline copies it from
+ `CanonicalRequest.protocol`. Providers can ignore it.
+ - `AdapterHealthComponent.undetermined` uses `'unreachable'` for a probe
+ that received no response. When set, `status` does not describe the
+ target's health. Without the field, `status` retains its 2.7 meaning.
### Protocols and gateway
@@ -449,6 +457,51 @@ persistence must not fail the commerce flow.
as they become idle and resolves after requests and adapters have finished.
In 2.5, adapters stopped first and could close a store still in use by a
request.
+- 2.8.0: x402 health marks an offer's component with `undetermined: 'unreachable'`
+ for recognized transport failures, including refused, reset or timed-out
+ connections, temporary DNS failures and request timeouts. Unresolvable
+ hostnames, TLS or certificate errors, JSON-RPC errors, non-2xx responses and
+ reverts leave the component unmarked. MPP uses the same provider to report its
+ offer's health.
+ - `/.well-known` adds `status` and `undetermined` to a single-offer
+ `payments.x402` block and to `payments.mpp`, and `undetermined` to each
+ offer in `options` and `resourceOptions`.
+ - `doctor` reads them for `Payments (offers)` and the new
+ `Payments (MPP offers)` check.
+- 2.8.0: experimental `X402ProviderOptions.resourceUrls` maps resource ids and
+ request surfaces (`http`, `mcp` or `a2a`) to each challenge's `resource.url`.
+ - `createRequirement` reads the surface from `PaymentContext.protocol`. A
+ context without one, an ACP request, or a surface without an entry keeps
+ the `resource://` form.
+ - With `payments.x402.publicResourceUrl: true`, config normalization fills
+ `GatewayConfig.payments.x402.resourceUrls` for resources whose first
+ enabled rail is x402, with each URL in the URL parser's form. MPP's
+ internal x402 provider does not receive this map.
+ - A provider given the map lists `public-resource-url` in its descriptor's
+ `capabilities`.
+ - Without the option, challenges are unchanged.
+- 2.8.0: experimental `X402ProviderOptions.resourceBazaar` maps resource ids
+ and request surfaces (`http` or `mcp`) to each challenge's `extensions.bazaar`
+ value.
+ - With `payments.x402.bazaar.enabled: true`, config normalization fills
+ `GatewayConfig.payments.x402.resourceBazaar` with metadata that passes
+ the omission rules. MPP's internal x402 provider does not receive it.
+ - When a challenge carries Bazaar metadata, verify and settle send its
+ `resource` and `extensions.bazaar` to a remote facilitator that lists
+ `bazaar` in `/supported`, replacing those fields from the proof. Any other
+ facilitator receives neither.
+ - An HTTP challenge omits the metadata unless its encoded
+ `PAYMENT-REQUIRED` value plus the largest proof reserve among its offer
+ families fits within 8192 bytes.
+ - A provider given the map lists `bazaar` in its descriptor's `capabilities`.
+ - Without the option, challenges and facilitator bodies are unchanged.
+- 2.8.0: experimental `GatewayConfig.protocols.mcp.registry` holds the
+ `name`, `version` and `description` from `protocols.mcp.registry` and is
+ absent when that block is omitted. Config loading validates these fields
+ against the MCP Registry's name, length and version rules.
+ `agent-commerce export mcp-registry` and `doctor --registry` use the metadata.
+ `runGateway` passes `name` and `version` to the MCP adapter as `serverName`
+ and `serverVersion`; an adapter built without them keeps its defaults.
### Authorization and AP2
@@ -1001,7 +1054,16 @@ export interface GatewayConfig {
};
readonly protocols: {
readonly http: { readonly enabled: boolean };
- readonly mcp: { readonly enabled: boolean; readonly mountPath: string };
+ readonly mcp: {
+ readonly enabled: boolean;
+ readonly mountPath: string;
+ // Experimental; present only when `protocols.mcp.registry` is set
+ readonly registry?: {
+ readonly name: string;
+ readonly version: string;
+ readonly description: string;
+ };
+ };
readonly a2a: { readonly enabled: boolean; readonly mountPath: string };
readonly acp: AcpProtocolConfig;
};
@@ -1021,6 +1083,9 @@ export interface GatewayConfig {
readonly paymentFlow?: X402PaymentFlow; // default 'authorization'
readonly resourcePaymentFlows?: Readonly>;
readonly resourceMimeTypes?: Readonly>; // resources that set `mimeType`
+ // Experimental; filled by `publicResourceUrl` and `bazaar.enabled`
+ readonly resourceUrls?: X402ProviderOptions['resourceUrls'];
+ readonly resourceBazaar?: X402ProviderOptions['resourceBazaar'];
readonly facilitator: X402FacilitatorConfig;
readonly allowMainnet?: boolean;
readonly allowUnauthenticatedFacilitator?: boolean;
diff --git a/docs/contributing-adapters.md b/docs/contributing-adapters.md
index ab4733e..fa309ca 100644
--- a/docs/contributing-adapters.md
+++ b/docs/contributing-adapters.md
@@ -31,9 +31,13 @@ A new name crosses the public contract and runtime wiring. After approval:
5. If it has distinct optional dependencies, add the narrow subpath, build
entry, package export, optional peer and the real-package check in
`tests/unit/cli/packaging.test.ts`.
-6. Add its descriptor, discovery and `doctor` output. Update the frozen
- contract and conformance coverage, and add a page under `docs/protocols/`
- that [protocols.md](protocols.md) lists.
+6. Add a support record under `src/support/` and its name to
+ `SUPPORT_RECORD_NAMES` in `scripts/support-record.ts`. Add a descriptor,
+ and discovery and `doctor` output. Update the frozen contract and
+ conformance coverage. Add a page under `docs/protocols/` with the region
+ markers its record needs, list it in [protocols.md](protocols.md), and run
+ `npm run support:write`. `tests/integration/support-record.test.ts` names
+ any region that is missing or out of date.
## Protocol adapters
@@ -95,9 +99,9 @@ validation, authorization, payment, backend execution and receipts.
carriers from headers.
- Keep handler failures inside the adapter and report health through
`health()`.
-- Pin `descriptor.supportedSpec`, list real `capabilities` and `unsupported`
- features, and keep `status: experimental` until conformance coverage supports
- promotion.
+- Pin `descriptor.supportedSpec` and list implemented `capabilities`. Derive
+ `status` and `unsupported` from the adapter's record in `src/support/`.
+ Keep the adapter `experimental` until conformance coverage supports promotion.
### Adapter review checklist
diff --git a/docs/protocols.md b/docs/protocols.md
index e64e7a9..713d85e 100644
--- a/docs/protocols.md
+++ b/docs/protocols.md
@@ -5,20 +5,23 @@ subset. Each protocol's page describes that subset in detail.
## Support matrix
-| Protocol | Status | Revision | Implemented subset |
-| ------------ | ------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
-| **HTTP** | Supported | native | resource routes and rail-specific payment headers |
-| **MCP** | Supported | MCP `2026-07-28` and `2025-11-25` through `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping |
-| **x402** | Supported | x402 v2, `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding |
-| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension |
-| **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations |
-| **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode | closed Checkout Mandate verification before settlement |
-| **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 over HTTP, MCP and A2A |
-| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` |
-| UCP | Planned | - | no implementation |
+
+
+| Protocol | Status | Role | Revision | Implemented subset |
+| ------------ | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
+| **HTTP** | Supported | Transport that carries x402 and MPP payments on each resource's invoke route. | native | resource routes and rail-specific payment headers |
+| **MCP** | Supported | Transport that carries x402 and MPP payments in tool calls. | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping |
+| **x402** | Supported | Payment rail, carried by HTTP, MCP and A2A. | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding |
+| **MPP** | Experimental | Payment rail, carried by HTTP, MCP and A2A. | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A |
+| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension |
+| **ACP** | Experimental | Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment. | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations |
+| **AP2** | Experimental | Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it. | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement |
+| **ERC-8409** | Experimental | x402 feature: EIP-712 signed quotes on the EVM offers of a challenge. | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` |
+
+
Experimental components are disabled unless configured and support only the
-subsets their pages describe. Planned means there is no adapter or endpoint.
+subsets their pages describe. UCP is planned and has no implementation.
AP2 is an authorization method, not a transport or payment rail. It appears in
`authorizationProviders` in gateway discovery and has no AP2-specific mount or
@@ -32,17 +35,68 @@ and providers, including `supportedSpec`, `capabilities`, `unsupported` and
`status`. When enabled, A2A, ACP and AP2 also print their detailed unsupported
lists in `agent-commerce doctor`.
+## Tested combinations
+
+Each row names the test that covers a rail over a surface. E2E rows settle on
+a local Anvil chain. Integration rows mock the facilitator and run no chain.
+Public testnet and mainnet rows are smoke tests that spend funds and run only
+on the wallet holder's machine, never in CI.
+
+
+
+| Rail | Surface | Authorization | Tested at | Test |
+| ---- | ------- | ------------- | --------------------- | ------------------------------------------------ |
+| x402 | HTTP | - | E2E, local chain | `tests/e2e/payment/x402-settlement.e2e.test.ts` |
+| x402 | A2A | - | E2E, local chain | `tests/e2e/payment/x402-settlement.e2e.test.ts` |
+| x402 | HTTP | AP2 | E2E, local chain | `tests/e2e/authorization/ap2-x402.e2e.test.ts` |
+| x402 | MCP | - | E2E, local chain | `tests/e2e/payment/x402-bazaar.e2e.test.ts` |
+| x402 | MCP | - | integration, no chain | `tests/integration/mcp-payment-bindings.test.ts` |
+| x402 | HTTP | - | public testnet | `tests/testnet/x402.smoke.test.ts` |
+| x402 | HTTP | - | mainnet | `tests/mainnet/x402.smoke.test.ts` |
+| MPP | HTTP | - | E2E, local chain | `tests/e2e/payment/mpp-settlement.e2e.test.ts` |
+| MPP | HTTP | AP2 | E2E, local chain | `tests/e2e/authorization/ap2-mpp.e2e.test.ts` |
+| MPP | MCP | - | integration, no chain | `tests/integration/mcp-payment-bindings.test.ts` |
+| MPP | A2A | - | integration, no chain | `tests/integration/mpp-carriers.test.ts` |
+| MPP | HTTP | - | public testnet | `tests/testnet/mpp-base-sepolia.smoke.test.ts` |
+| MPP | HTTP | - | mainnet | `tests/mainnet/mpp-base.smoke.test.ts` |
+
+
+
+## Promotion criteria
+
+A profile moves from experimental to supported when all four criteria hold.
+Each reads fields of the profile's record in `src/support/`:
+
+1. Upstream declares the pinned revision stable (`spec.stable`).
+2. Every MUST-level gap against that revision is closed, or the profile
+ excludes the feature and lists it (`gaps`, `exclusions`).
+3. Conformance evidence exists: the upstream suite where there is one,
+ otherwise our tests against the specification's requirements and examples
+ (`conformance`). Every MUST test that runs passes, and each skipped test is
+ named with its reason. A test that fails only because it contradicts the
+ specification, or assumes an input mode the profile does not declare, is
+ recorded the same way, with the specification section and the upstream
+ report.
+4. Operational docs exist, with crash and replay coverage (`docs`,
+ `combinations`).
+
+"Supported" covers the recorded subset, never the whole specification. HTTP,
+MCP and x402 were supported before 2.8.0 introduced these criteria, and keep
+that status. Upstream does not label x402 v2 stable, and its record states that.
+
## Protocol pages
- [HTTP surface](protocols/http.md): routes, and the payment headers each rail
uses on the invoke route
-- [MCP](protocols/mcp.md): tools, payment over MCP, and exclusions
+- [MCP](protocols/mcp.md): tools, payment over MCP, MCP Registry listings,
+ and exclusions
- [A2A](protocols/a2a.md): invocation and payment, the x402 extension, results,
and exclusions
- [ACP](protocols/acp.md): headers, checkout operations, the payment boundary,
idempotency, errors, discovery, and exclusions
- [x402](protocols/x402.md): the `exact` scheme on EVM, Solana and NEAR,
- several options, payment flows, and mainnet guardrails
+ several options, payment flows, the public resource URL, Bazaar metadata,
+ and mainnet guardrails
- [MPP](protocols/mpp.md): the pinned drafts, the `charge` profile, payment
flow, problem documents, and exclusions
- [AP2](protocols/ap2.md): mandate verification before a paid resource settles
diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md
index 2462668..4d31f54 100644
--- a/docs/protocols/a2a.md
+++ b/docs/protocols/a2a.md
@@ -184,13 +184,55 @@ without an `id` returns `-32600` without running. Each A2A error carries a
`google.rpc.ErrorInfo` in `error.data`, with a reason such as
`VERSION_NOT_SUPPORTED` and the domain `a2a-protocol.org`.
+## Pins
+
+
+
+| Pin | Value |
+| ------------------------ | ------------------------------------------------------------------------------------------------------------ |
+| Pinned revision | v1.0.1; negotiation `1.0`; `JSONRPC` binding |
+| Upstream source | [`a2aproject/A2A@33035925`](https://github.com/a2aproject/A2A/tree/3303592588e388e62e0f69f701af531d2f4e3991) |
+| Declared stable upstream | yes |
+| Upstream wording | "the first stable, production-ready version" (read 2026-11-17) |
+| `@a2a-js/sdk` | `1.3.0`, tests only |
+
+
+
## A2A exclusions
-Unsupported methods are `SendStreamingMessage`, `GetTask`, `ListTasks`,
-`CancelTask`, `SubscribeToTask`, the four task-push-notification-config
-methods and `GetExtendedAgentCard`. The adapter also excludes REST and gRPC
-bindings, SSE, long-running tasks, push delivery, multi-turn continuation,
-authenticated extended cards, A2A authentication and other artifact types.
+The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in
+`unsupported`, and `agent-commerce doctor` prints them when A2A is enabled:
+
+
+
+- `SendStreamingMessage`
+- `GetTask`
+- `ListTasks`
+- `CancelTask`
+- `SubscribeToTask`
+- `CreateTaskPushNotificationConfig`
+- `GetTaskPushNotificationConfig`
+- `ListTaskPushNotificationConfigs`
+- `DeleteTaskPushNotificationConfig`
+- `GetExtendedAgentCard`
+- `HTTP+JSON/REST binding`
+- `gRPC binding`
+- `SSE`
+- `long-running task persistence`
+- `task resumption other than an x402 extension payment`
+- `push notifications`
+- `multi-turn conversational continuation`
+- `text parts`
+- `file and URL parts (including inline bytes)`
+- `multi-part messages`
+- `message roles other than ROLE_USER`
+- `authenticated extended agent cards`
+- `A2A authentication schemes`
+- `artifact types beyond Agent Commerce outcome data`
+- `x402 extension payments across gateway instances`: Instances with separate receipt stores cannot resume each other's tasks.
+
+
+
Only pending x402 payment tasks can be stored and resumed.
The A2A adapter accepts `_payment` but does not verify or settle payments
diff --git a/docs/protocols/acp.md b/docs/protocols/acp.md
index 264e35b..629411c 100644
--- a/docs/protocols/acp.md
+++ b/docs/protocols/acp.md
@@ -222,12 +222,57 @@ Discovery is public while ACP is enabled and uses
locale and intervention metadata appears only when configured. Tokens, backend
URLs, resource ids and database paths are excluded.
+## Pins
+
+
+
+| Pin | Value |
+| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Pinned revision | stable snapshot `2026-04-17`; REST binding |
+| Upstream source | [`agentic-commerce-protocol/agentic-commerce-protocol@6b828681`](https://github.com/agentic-commerce-protocol/agentic-commerce-protocol/tree/6b828681206f1f98a3faba978610ced66770d2ae) |
+| Declared stable upstream | no |
+| Upstream wording | "currently in `beta`" (read 2026-11-17) |
+| `src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json` | vendored from `6b828681` |
+| `tests/fixtures/acp/2026-04-17` | vendored from `6b828681` |
+
+
+
+## Deviations
+
+Each entry names the section of the pinned revision the gateway departs from
+and the tests that hold the behavior.
+
+
+
+- **ACP RFC §6.5**: After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, and another execution could duplicate the order. Tests: `tests/conformance/acp/idempotency.test.ts`, `tests/conformance/acp/errors.test.ts`.
+
+
+
## ACP exclusions
-The adapter excludes carts, feed and standalone orders; delegated payment and
-authentication; the ACP MCP binding; webhooks and outbound delivery; the client
-role; `Signature` and `Timestamp` verification; discounts and the general
-extension framework; seller-backed payment handlers; and other ACP versions.
+The ACP descriptor in `GET /.well-known/agent-commerce` lists these names in
+`unsupported`, and `agent-commerce doctor` prints them when ACP is enabled:
+
+
+
+- `carts service`: The discovery document advertises only the checkout service.
+- `feed service`
+- `standalone orders service`
+- `delegate_payment`
+- `delegate_authentication`
+- `ACP MCP transport binding`
+- `webhooks`: The merchant backend sends ACP order webhooks itself.
+- `outbound merchant-to-agent delivery`
+- `ACP client role`
+- `Signature header verification`: The adapter forwards the header to the merchant unverified.
+- `Timestamp replay-window verification`: The adapter forwards the header to the merchant unverified.
+- `discount extension`
+- `general ACP extension framework`
+- `multiple ACP API versions`
+- `seller-backed payment handler integration`
+
+
+
A `Signature` header does not replace bearer authentication.
No ACP SDK ships. Conformance tests use the vendored official schema and examples.
diff --git a/docs/protocols/ap2.md b/docs/protocols/ap2.md
index c6490cb..22f294d 100644
--- a/docs/protocols/ap2.md
+++ b/docs/protocols/ap2.md
@@ -379,25 +379,50 @@ Whoever creates an AP2 provider must call `close()`. The application
composition root does so after `gateway.close()`; `createGateway()` itself
does not close authorization providers.
+## Pins
+
+
+
+| Pin | Value |
+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Pinned revision | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode |
+| Upstream source | [`google-agentic-commerce/AP2@b4587ac1`](https://github.com/google-agentic-commerce/AP2/tree/b4587ac1d055888a73b4b21750973cffba961793) |
+| Declared stable upstream | no |
+| Upstream wording | "Standardization of the specification will continue within the Agentic Authentication Technical and Payments Technical Working Groups in FIDO" (read 2026-11-17) |
+| `jose` | `6.2.12`, optional peer |
+| `@sd-jwt/core` | `0.20.1`, optional peer |
+| `canonicalize` | `5.0.0`, optional peer |
+| `tests/fixtures/ap2/v0.2.0` | vendored from `b4587ac1` |
+
+
+
## Not implemented
-`src/authorization/ap2/descriptor.ts` is authoritative for the unsupported list
-published through discovery and `doctor`. The broader implementation limits are:
-
-- autonomous mode and open Checkout Mandates (`mandate.checkout.open.1`)
-- Payment Mandates (`mandate.payment.1`)
-- spending-constraint evaluation
-- `cnf`-bound agent keys, delegation chains and key-binding JWTs
-- User Credential delegation through OpenID4VP
-- JWKS, issuer metadata, remote key discovery or remote revocation
-- key rotation without a config change
-- signatures other than ES256 or digests other than SHA-256
-- mandate issuance or signed AP2 Checkout Receipts
-- an AP2 transport adapter or `/.well-known/ap2`
-- AP2 as a payment rail
-- AP2 over ACP
-
-Open mandates are refused because their spending constraints are not evaluated.
+The AP2 descriptor in `GET /.well-known/agent-commerce` lists these names in
+`unsupported`, and `agent-commerce doctor` prints them when AP2 is enabled:
+
+
+
+- `autonomous mode`
+- `open checkout mandates (mandate.checkout.open.1)`: Rejected because the provider does not evaluate spending constraints.
+- `payment mandates (mandate.payment.1)`
+- `spending constraint evaluation`
+- `cnf-bound agent keys`
+- `user credential delegation (OpenID4VP)`
+- `delegation chains and key-binding JWTs`
+- `JWKS and any key discovery by URL (jku, x5u)`: Operators supply all keys in config.
+- `issuer metadata fetching`
+- `remote revocation`
+- `key rotation without a config change`
+- `signature algorithms other than ES256`
+- `digest algorithms other than sha-256`
+- `mandate issuance`
+- `checkout receipts`
+- `AP2 transport adapter or /.well-known/ap2`: HTTP, MCP and A2A carry the mandate in the gateway's own carriers; AP2 v0.2.0 defines none.
+- `AP2 as a payment rail`
+- `AP2 over the ACP checkout adapter`
+
+
## Code map
diff --git a/docs/protocols/mcp.md b/docs/protocols/mcp.md
index 5f031b4..bd21df3 100644
--- a/docs/protocols/mcp.md
+++ b/docs/protocols/mcp.md
@@ -115,12 +115,88 @@ For payment-required and error results, `content[0].text` is a JSON copy of
`structuredContent`; `content[1].text` is a sentence for readers. Unexpected
exception messages and stack traces are omitted.
+## MCP Registry listing
+
+Experimental. The [MCP Registry](https://registry.modelcontextprotocol.io)
+is a public catalog of MCP servers in preview. Use the CLI to export a listing,
+then publish it:
+
+1. Set [`protocols.mcp.registry`](../configuration.md#protocolsmcpregistry)
+ and an HTTPS `merchant.publicBaseUrl`.
+2. Run `agent-commerce export mcp-registry`. It loads and validates the full
+ config as `start` does, so required `${VAR}` placeholders must resolve. It
+ writes `server.json` with the 2025-12-11 `$schema`, your `name`, `description`
+ and `version`, and one `streamable-http` remote at
+ ``.
+ Use `--output` to choose another path and `--force` to replace an existing
+ file. The command writes nothing and names the key to change when MCP is
+ disabled, the registry block is missing, or the URL uses a scheme other than
+ HTTPS or names `localhost`, `127.0.0.1` or a `.localhost` host.
+3. Log in and publish with the registry's `mcp-publisher` CLI. The namespace
+ determines the required ownership proof: `io.github./` needs GitHub
+ authentication; a reverse-DNS namespace such as `com.example/` needs a DNS
+ TXT record or a `/.well-known/mcp-registry-auth` file on `example.com`.
+ The gateway does not serve that file. See the registry's
+ [authentication guide](https://github.com/modelcontextprotocol/registry/blob/115f85225c9fac5281d8a2dc8551cf49b004d2f9/docs/modelcontextprotocol-io/authentication.mdx).
+4. Run `agent-commerce doctor --registry` to compare the published listing
+ with your config.
+
+The listing's version comes from `protocols.mcp.registry.version`, independently
+of the package version. The registry's schema defines it as the server's
+`Implementation.version`. When started with this block, the gateway reports the
+listing's `name` and `version` as `serverInfo` at `initialize`.
+
+The registry recommends semantic versions and uses their ordering to choose
+the latest. Publishing a prerelease such as `1.2.3-1`
+after its release, `1.2.3`, does not make it the latest. If your config names
+that prerelease, `doctor --registry` reports a version difference.
+
+Several server names may list the same remote URL; the URL alone does not
+prove who runs the server. `doctor --registry` looks up the configured name
+only and reports a response with another name as a difference in `name`.
+
+## Pins
+
+
+
+| Pin | Value |
+| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Pinned revision | MCP `2026-07-28` and `2025-11-25` |
+| Upstream source | [`modelcontextprotocol/modelcontextprotocol@05aeb07b`](https://github.com/modelcontextprotocol/modelcontextprotocol/tree/05aeb07b2db0c02adc4813a7c09f208ca8774152) |
+| Declared stable upstream | yes |
+| Upstream wording | "Current: the current protocol version, which is ready for use and may continue to receive backwards compatible changes" (read 2026-11-17) |
+| `@modelcontextprotocol/server` | `2.3.0`, optional peer |
+| `@modelcontextprotocol/client` | `2.3.0`, tests only |
+| `@modelcontextprotocol/sdk` | `1.32.0`, tests only |
+
+
+
## MCP exclusions
-The adapter does not implement MCP resources, prompts, sampling, completions,
-elicitation, roots, logging, tasks or tool-list-change notifications. It has
-no MCP authorization, sessions, subscriptions, pagination or HTTP+SSE transport.
-The gateway, rather than the MCP adapter, enforces Host and Origin checks.
+The MCP descriptor in `GET /.well-known/agent-commerce` lists these names in
+`unsupported`:
+
+
+
+- `resources`
+- `prompts`
+- `sampling`
+- `completions`
+- `elicitation`
+- `roots`
+- `logging`
+- `notifications/tools/list_changed`
+- `tasks`
+- `dns-rebinding-protection`: The adapter relies on the gateway's `onRequest` hook to validate Host and Origin for the MCP mount.
+- `authorization`
+- `sessions`
+- `subscriptions`
+- `pagination`
+- `HTTP+SSE transport`
+- `MPP payment-required as JSON-RPC error -32042`: mppx reads challenges from the tool result's `_meta`.
+- `MPP verification failure as JSON-RPC error -32043`: mppx reads refusals from the tool result's `_meta`.
+
+
The MCP adapter maps payment carriers and results. It does not verify or
settle payments or call merchant backends.
diff --git a/docs/protocols/mpp.md b/docs/protocols/mpp.md
index 1b06a19..283d1d4 100644
--- a/docs/protocols/mpp.md
+++ b/docs/protocols/mpp.md
@@ -4,11 +4,11 @@
The gateway targets `draft-httpauth-payment-01`,
`draft-payment-intent-charge-00`, and `draft-evm-charge-00` at
-`tempoxyz/mpp-specs@806fdb8`. It pins the pre-1.0 `mppx@0.13.1` as an
-optional peer. For EIP-3009, the gateway follows `mppx`: it hashes
-`JSON.stringify([id, realm])` with keccak256 to derive the nonce. The EVM
-draft instead hashes `abi.encodePacked(id, realm)`. Credentials using the
-draft nonce, including those produced by `mppx` 0.12 or earlier, fail
+`tempoxyz/mpp-specs@806fdb8`. It uses the pre-1.0 `mppx`, an optional peer
+pinned to the version under [Pins](#pins). For EIP-3009, the gateway follows
+`mppx`: it hashes `JSON.stringify([id, realm])` with keccak256 to derive the
+nonce. The EVM draft instead hashes `abi.encodePacked(id, realm)`. Credentials
+using the draft nonce, including those produced by `mppx` 0.12 or earlier, fail
verification with `wrong_nonce`.
Later drafts or `mppx` releases may change the wire format again, so MPP
@@ -61,10 +61,6 @@ issuing challenges over plain HTTP.
Base mainnet deployments must satisfy the
[mainnet guardrails](../configuration.md#mainnet-guardrails).
-Unsupported variants are listed in `src/payments/mpp/descriptor.ts`: non-EVM
-methods, Permit2/transaction/hash credentials, splits, subscriptions, EVM
-sessions and the discovery extension.
-
## Idempotency-Key
Experimental and disabled by default. On a resource with
@@ -102,3 +98,50 @@ another payer returns 422 `Unprocessable Content`, following section 2.7 of
usable stored response.
[http.md](http.md) lists the redelivery headers.
+
+## Pins
+
+
+
+| Pin | Value |
+| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Pinned revision | drafts at `tempoxyz/mpp-specs@806fdb8` |
+| Upstream source | [`tempoxyz/mpp-specs@806fdb8b`](https://github.com/tempoxyz/mpp-specs/tree/806fdb8b8c92cda5c84b8660558921b6bbeef7e0) |
+| Declared stable upstream | no |
+| Upstream wording | "Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time." (read 2026-11-17) |
+| `mppx` | `0.13.1`, optional peer |
+
+
+
+## Deviations
+
+Each entry names the section of the pinned revision the gateway departs from
+and the tests that hold the behavior.
+
+
+
+- **draft-evm-charge-00**: The EIP-3009 nonce is keccak256 of `JSON.stringify([id, realm])`, as `mppx` 0.13 derives it, not of `abi.encodePacked(id, realm)`; a credential using the draft's nonce fails with `wrong_nonce`. Tests: `tests/unit/payments-mpp/provider.test.ts`.
+- **draft-payment-transport-mcp-00**: Over MCP, payment errors are tool results with `isError` and the challenges in `_meta`, not the JSON-RPC errors the draft maps them to (-32042, -32043, -32602 and -32603). Tests: `tests/integration/mcp-payment-bindings.test.ts`.
+- **draft-httpauth-payment-01 §11.4**: An unpaid request that gets a 402 also stores a `resource.requested` event beside the challenge. Tests: `tests/unit/core/execution/pipeline.test.ts`.
+- **draft-httpauth-payment-01 §4.2; draft-evm-charge-00**: A credential whose attempt is reserved or settlement-uncertain gets 409 without a fresh challenge, because a second challenge could lead to a second payment. Tests: `tests/integration/mpp-carriers.test.ts`.
+- **draft-payment-intent-charge-00**: With `paymentFlow: authorization`, the backend runs before the transfer, which the charge intent counts as partial access before payment. The default, `upfront`, settles first. Tests: `tests/e2e/payment/mpp-settlement.e2e.test.ts`.
+
+
+
+## MPP exclusions
+
+The MPP descriptor in `GET /.well-known/agent-commerce` lists these names in
+`unsupported`:
+
+
+
+- `methods other than evm`
+- `credential=permit2`: The profile accepts only the EIP-3009 authorization credential.
+- `credential=transaction`
+- `credential=hash`
+- `splits`: The draft allows splits only with `permit2` credentials.
+- `intent=subscription`
+- `evm sessions`: A separate EVM draft, not an option of charge.
+- `discovery extension`
+
+
diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md
index 16f7aee..823b4b6 100644
--- a/docs/protocols/x402.md
+++ b/docs/protocols/x402.md
@@ -66,16 +66,18 @@ sent. An absent `extra.paymentFlow` means `authorization`. A proof's `resource.u
must equal the challenge's when present. A mismatch is `invalid_payment_requirements`,
refused before the facilitator is called. `maxTimeoutSeconds` and `extra` keys
added by the client are not compared. The facilitator receives the payload
-without `resource`, since its `resource://` URL is the gateway's own identifier,
-and without `extensions`: verification and settlement do not use echoed
+without the proof's `resource` and `extensions`, after the gateway has checked
+the URL in any echoed `resource` against the challenge. A challenge with
+[Bazaar metadata](#bazaar-discovery-metadata) supplies the forwarded discovery
+fields. Verification and settlement do not use echoed
[quotes](#erc-8409-signed-quotes), and a Permit2 gas-sponsoring extension would
activate unsupported SDK facilitator behavior.
-With [several options](../configuration.md#several-options), the challenge uses
-`resource://agent-commerce/resources/`. The comparison above selects the
-proof's offer; zero or multiple matches yield `invalid_payment_requirements`.
-A resource with [its own offers](../configuration.md#a-resources-own-offers)
-accepts only proofs matching that list; resources may share offers.
+With [several options](../configuration.md#several-options), the comparison
+above selects the proof's offer; zero or multiple matches yield
+`invalid_payment_requirements`. A resource with
+[its own offers](../configuration.md#a-resources-own-offers) accepts only
+proofs matching that list; resources may share offers.
x402 v1 is not accepted. A payload declaring an `x402Version` other than 2 is
refused as `invalid_x402_version` on every carrier. A request carrying only the
@@ -119,6 +121,124 @@ other types. Local mode requires Anvil on `eip155:31337`; all public networks
require remote mode. Mainnet also requires the guardrails in
[configuration.md](../configuration.md#mainnet-guardrails).
+## The resource URL
+
+By default, `resource.url` is a gateway identifier. A single offer uses
+`resource://agent-commerce///resources/`; multiple offers
+share `resource://agent-commerce/resources/`. The `` and ``
+segments are percent-encoded.
+
+[`publicResourceUrl`](../configuration.md#public-resource-url) is experimental
+and disabled by default. When enabled, the URL names the configured HTTP
+invoke route, MCP mount or A2A mount for the request's surface. Every offer of
+that resource shares the URL on that surface; `accepted` still selects the offer.
+The echo comparison above rejects these proofs before calling the facilitator,
+and neither reaches settlement:
+
+- a proof that echoes the previous URL after the option changes;
+- a proof that echoes another surface's URL.
+
+The buyer can request and pay a new challenge. These checks provide no security
+boundary: `resource.url` is unsigned, and a client may omit it.
+
+Enabling this option adds `public-resource-url` to the x402 descriptor's
+`capabilities` in `GET /.well-known/agent-commerce`.
+
+## Bazaar discovery metadata
+
+Experimental and disabled by default. With
+[`bazaar.enabled`](../configuration.md#bazaar-metadata), x402 challenges on HTTP
+and MCP carry `extensions.bazaar` metadata for a facilitator's catalog.
+Other surfaces carry no Bazaar metadata. A resource whose first enabled rail
+is MPP receives an MPP challenge and no metadata; config loading warns when
+such a resource also lists `x402`. Enabling Bazaar adds `bazaar` to the x402
+descriptor's `capabilities` in `GET /.well-known/agent-commerce`.
+
+| Surface | `info.input` | `info.output` |
+| ------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
+| HTTP | `{ type: 'http', method: 'POST', bodyType: 'json', body: }` | `{ type: 'json', example }` when the resource's `mimeType` is JSON or unset and both output schema and example pass local checks; otherwise none |
+| MCP | `{ type: 'mcp', toolName: , description, inputSchema, example }` | none |
+
+`schema` describes `info` using JSON Schema 2020-12; the HTTP form puts the
+resource's input schema at `body`. The MCP `inputSchema` matches the one
+`tools/list` returns before adding `_payment` and `_authorization`. Each
+required property's example uses its first `examples` entry, then its `default`
+or first `enum` value, otherwise a value for its type.
+
+The builder does not copy backend URLs or headers. Descriptions, schemas and
+example values are public metadata; credentials embedded in them are not
+redacted.
+
+The gateway validates input before pricing. On HTTP, an example that fails the
+input schema returns 400 instead of a payment challenge. To keep discovery
+probes usable, config loading omits metadata and warns when:
+
+- its description (or name when no description is set) exceeds the gateway's
+ limit of 500 UTF-16 code units;
+- its input schema uses a keyword the gateway does not enforce. Enforced are
+ `type`, `properties`, `required`, `additionalProperties`, `enum` and a
+ single-schema `items`, each where the node's type admits it, plus the
+ annotations `title`, `description`, `example`, `examples`, `default`,
+ `$comment`, `deprecated`, `readOnly` and `writeOnly`;
+- its input schema has an empty `enum` or gives a keyword a value JSON Schema
+ 2020-12 does not allow, such as a repeated `required` name, a repeated `type`
+ or a `description` that is not a string. The x402 SDK's validator rejects
+ extensions with these schema values;
+- the example fails the input schema or the backend request shape;
+- a surface's extension exceeds 4096 bytes; only that surface is omitted.
+
+A schema warning names the keyword and its path, such as
+`input.properties.city uses "pattern"`.
+
+An HTTP challenge omits Bazaar unless its base64 `PAYMENT-REQUIRED` value plus
+a proof reserve fits within 8192 bytes. SDK clients repeat `extensions` beside
+the signed payload in `PAYMENT-SIGNATURE`; nginx's default request header field
+limit is 8 KiB. The reserve is 1024 bytes for EVM offers, 1280 for NEAR and 2304
+for Solana. A resource with several offers uses the largest reserve. It also
+leaves room for the `error` field added to a challenge after a refused proof.
+Contract wallet signatures may exceed the EVM allowance. A `warn` log names
+each resource that exceeds the budget, once per provider instance. MCP carries
+the challenge in the result body, where this header budget does not apply.
+Omitting metadata leaves payment behavior unchanged.
+
+On verify and settle, a remote facilitator that lists `bazaar` in the
+`extensions` of its `/supported` response (x402 v2, section 7.3) receives the
+challenge's `resource` and `extensions.bazaar`, replacing the proof's values.
+No other extension is forwarded. A facilitator whose response does not list
+`bazaar` receives neither field. This avoids sending unsupported fields that
+could cause it to reject the buyer's payment. The challenge still carries the
+metadata, and a `warn` log names the facilitator once per provider instance.
+The `/supported` response is cached for a minute. If the read fails or takes
+longer than one second, that verify or settle call proceeds without metadata.
+The in-process facilitator keeps no catalog and receives no metadata.
+
+A facilitator can report metadata processing outcomes in the
+`EXTENSION-RESPONSES` header of a verify or settle response. For
+`bazaar.status: "rejected"`, the gateway logs a `warn` with the resource id and
+up to 200 characters of the reason, once per resource and provider instance.
+This metadata outcome does not change the payment result. The pinned x402 SDK
+also prints selected status, reason and code fields from each outcome to stdout.
+
+### Getting listed
+
+The gateway supplies metadata; the facilitator decides what to index.
+Coinbase's CDP facilitator
+[documents](https://docs.cdp.coinbase.com/x402/seller/get-discovered) the
+following rules (checked 2026-11-18):
+
+- An endpoint becomes eligible for indexing after CDP settles a payment whose
+ payload includes both `resource` and `extensions.bazaar`, the fields the
+ gateway forwards.
+- Indexing probes send HTTP endpoints the example input, which must produce a
+ 402 challenge. MCP probes call tools with `info.input.example`; tools without
+ an example or an x402 payment challenge cannot be indexed.
+- Resources are removed after 30 days without a settlement. Endpoints that stop
+ returning 402 are eventually removed too.
+
+The offline E2E suite verifies settlement with these forwarded fields on a local
+chain through a test facilitator. It does not verify indexing by an external
+facilitator.
+
## Payment identifier
Experimental and disabled by default. A resource with
@@ -268,10 +388,21 @@ ERC-8409 requires transport bindings to define the following:
the payment deadline with `validUntil`. Quote expiry does not cancel a
submitted payment.
-Not implemented: payer-bound quotes; contract issuers (ERC-1271, ERC-6492,
-EIP-7702 delegates); quote consumption, single-use enforcement or revocation;
-client nonces; quotes for MPP, Solana or NEAR; signed receipts and x402's
-`offer-receipt` extension; remote signers and KMS; per-resource toggles.
+The x402 descriptor lists these quote exclusions in `unsupported` whether or
+not quotes are enabled:
+
+
+
+- `payer-bound quotes`
+- `contract quote issuers (ERC-1271, ERC-6492, EIP-7702 delegates)`
+- `quote consumption, single-use enforcement or revocation`
+- `quote client nonces`
+- `quotes for MPP, Solana or NEAR`
+- `signed receipts and the x402 offer-receipt extension`
+- `remote quote signers and KMS`
+- `per-resource quote toggles`
+
+
## Support matrix
@@ -291,3 +422,41 @@ README lists their transactions.
Every public-network x402 payment was signed by the x402 SDK's own client for
its family. Other wallets and clients have not been tested.
+
+## Pins
+
+
+
+| Pin | Value |
+| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| Pinned revision | x402 v2 |
+| Upstream source | [`x402-foundation/x402@51a0664c`](https://github.com/x402-foundation/x402/tree/51a0664c2b7826e3cb02595481eb6848a1b11815) |
+| Declared stable upstream | not stated |
+| Upstream wording | "Protocol Version: 2" (read 2026-11-17) |
+| ERC-8409 pinned revision | draft `SergeevDmitry/ERCs@0ee33230` |
+| ERC-8409 upstream source | [`SergeevDmitry/ERCs@0ee33230`](https://github.com/SergeevDmitry/ERCs/tree/0ee33230ca9f9f41a714382552a47cd860465ca7) |
+| ERC-8409 declared stable upstream | no |
+| ERC-8409 upstream wording | "status: Draft" (read 2026-11-17) |
+| `@x402/core` | `2.30.0`, optional peer |
+| `@x402/evm` | `2.30.0`, optional peer |
+| `@x402/svm` | `2.30.0`, optional peer |
+| `@x402/near` | `2.30.0`, optional peer |
+| `@x402/mcp` | `2.30.0`, tests only |
+
+
+
+## x402 exclusions
+
+The x402 descriptor in `GET /.well-known/agent-commerce` lists these names in
+`unsupported`, followed by the
+[ERC-8409 quote exclusions](#erc-8409-signed-quotes):
+
+
+
+- `permit2 gas sponsoring extensions`
+- `upto scheme`
+- `batch-settlement scheme`
+- `auth-capture scheme`
+- `x402 v1`: A payload declaring an `x402Version` other than 2 is refused as `invalid_x402_version` on every carrier.
+
+
diff --git a/docs/security.md b/docs/security.md
index c8f65e5..28e0e71 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -333,6 +333,18 @@ real funds.
| amount differs from the price in either direction | `invalid_exact_evm_payload_authorization_value_mismatch` before settlement | `tests/e2e/payment/x402-settlement.e2e.test.ts` |
| **an x402 proof whose `accepted` differs from the offer, or whose `resource.url` differs from the challenge's** | `invalid_payment_requirements` before the facilitator is called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` |
| **multi-offer x402 proof whose `accepted` matches zero or multiple offers** | `invalid_payment_requirements`; no offer is selected and the facilitator is not called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` |
+| **an x402 proof under `publicResourceUrl`, whose offers share one `resource.url`** | offer selection still uses `accepted`, as with `resource://`; the URL form does not change the replay key | `tests/unit/payments-x402/public-resource-url.test.ts` |
+| **an x402 proof echoing a challenge issued before `publicResourceUrl` changed, or another surface's challenge** | `invalid_payment_requirements` before calling the facilitator; no settlement, including for an A2A task awaiting payment across a restart | `tests/unit/payments-x402/public-resource-url.test.ts`, `tests/integration/x402-public-url.test.ts`, `tests/integration/a2a-x402-extension.test.ts` |
+| **a buyer echoing altered Bazaar metadata or `resource` fields to poison a facilitator's catalog** | replaces the proof's values with the issued challenge's `resource` and `extensions.bazaar` before forwarding | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/integration/x402-bazaar.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` |
+| **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` |
+| **Bazaar metadata echoed from another surface, with several offers** | offer selection still uses `accepted`; the facilitator receives the challenge's own metadata | `tests/unit/payments-x402/bazaar-challenge.test.ts` |
+| **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` |
+| **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header or the buyer's `PAYMENT-SIGNATURE` echo, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if its encoded value plus the proof reserve exceeds 8192 bytes (1024 for EVM offers, 1280 for NEAR, 2304 for Solana; the largest applies). The reserve also allows for the `error` field after a refused proof. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` ("fits the SDK client echo of the largest kept challenge in an 8192-byte header", "leaves it out of an HTTP challenge one byte over, and logs that once per resource") |
+| **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` |
+| **an input schema the gateway accepts and a facilitator cannot compile, silently dropping the listing** | config loading omits metadata for malformed keyword values detected by the JSON Schema 2020-12 checks or an empty `enum`; warnings name the keyword and its path | `tests/unit/core/execution/validation.test.ts`, `tests/unit/payments-x402/bazaar.test.ts` ("leaves out a resource whose input schema has ..., which upstream validation refuses") |
+| **a facilitator that does not implement Bazaar refusing a payment over the forwarded fields, and the buyer blamed for it** | verify and settle forward `resource` and `extensions.bazaar` only to a remote facilitator that lists `bazaar` in `/supported`; when that read fails or takes over one second, the call sends neither | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar metadata and the facilitator /supported list"), `tests/integration/x402-bazaar.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` |
+| **a facilitator rejecting a Bazaar listing unnoticed, or adding unbounded reason text to the gateway log** | the gateway logs a `rejected` outcome in `EXTENSION-RESPONSES` at `warn` once per resource and provider instance; it redacts URLs in the reason to scheme and host before truncating it to 200 characters. This metadata outcome does not change the payment result | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar outcome from the facilitator") |
+| **a resource served on MPP described in config as an x402 listing** | public URLs and Bazaar metadata are built only for resources whose first enabled rail is x402; a resource that lists `x402` behind an enabled `mpp` gets a warning naming the serving rail | `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` |
| **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` |
| **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` |
| **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same |
@@ -341,9 +353,9 @@ real funds.
| **a Permit2 payment from a buyer without a Permit2 allowance** | 412 with `error: permit2_allowance_required` in a fresh `PAYMENT-REQUIRED`; `permit2_simulation_failed` and 402 on a chain without Multicall3; balances unchanged | `tests/e2e/payment/x402-permit2.e2e.test.ts` |
| **a proof of the other transfer method, or one carrying both an EIP-3009 and a Permit2 authorization** | `unsupported_scheme` before the facilitator is called, which would settle the Permit2 one | `tests/unit/payments-x402/provider-remote-facilitator.test.ts`, `tests/unit/payments-x402/provider.test.ts` |
| **an EIP-3009 authorization whose value, time bounds or nonce are not in canonical form** | `invalid_payload` before the facilitator is called: amounts and times must be decimal, the nonce 32 bytes of hex | `tests/unit/payments-x402/provider.test.ts` |
-| **a gas-sponsoring extension in a Permit2 payload** | not forwarded: the facilitator receives no `extensions` | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` |
+| **a gas-sponsoring extension in a Permit2 payload** | not forwarded: the facilitator receives none of the proof's `extensions` | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` |
| **an ERC-8409 quote altered after signing, or signed by another key** | a buyer that verifies the signature against the published issuer rejects it | `tests/unit/payments-x402/quote.test.ts`, `tests/integration/x402-quotes.test.ts` |
-| **an altered ERC-8409 quote echoed in a payment** | ignored: verification and settlement use the offer and payer authorization; the facilitator receives no `extensions` | `tests/integration/x402-quotes.test.ts` |
+| **an altered ERC-8409 quote echoed in a payment** | ignored: verification and settlement use the offer and payer authorization; the facilitator receives none of the proof's `extensions` | `tests/integration/x402-quotes.test.ts` |
| **a leaked quote signing key** | its holder can sign quotes as the merchant. Keep the key unfunded. Rotation changes the published issuer after a restart; `doctor` detects a gateway still using the old key | `tests/integration/x402-quotes.test.ts`, `tests/unit/cli/doctor.test.ts` |
| **unpaid requests that vary the input to force quote signing** | each cache miss requires a signature per EVM offer; repeated input reuses a cached quote while a full payment window remains | `tests/unit/payments-x402/quote.test.ts` |
| **a quote signing key that controls an EVM `payTo`, or a well-known Anvil key outside the local chain** | `CONFIG_INVALID` during provider construction; the message omits the key | `tests/unit/payments-x402/quote.test.ts` |
@@ -573,6 +585,14 @@ real funds.
| **the payment proof header as a bearer credential** | with matching input and any required mandate, `PAYMENT-SIGNATURE` retrieves the stored response until retention ends. Keep it out of proxy, APM and access logs; the gateway's logger redacts it | `tests/integration/payment-retries.test.ts` ("redelivers an exact resend, marked as a replay, without a second charge"), `tests/unit/gateway/logger.test.ts` ("redacts every wire header that carries a credential or a proof") |
| **a retention window outside 1 to 8760 hours** | config load refuses it, and a pipeline built without config throws `CONFIG_INVALID` before any payment work | `tests/unit/config/schema.test.ts` ("refuses a retention of %s hours as too long", "refuses a retention of %s", "accepts the longest retention, one year"), `tests/unit/core/execution/pipeline-retry.test.ts` ("refuses a retention of %s hours before any provider call", "accepts a retention of one year") |
| **an A2A in-flight refusal that tells the client to resend on the consumed task** | the failed task reports `retryable: false` with no `retryAfterSeconds`; the client starts a new task with the same payment `id` | `tests/unit/protocols-a2a/payment-resume.test.ts` ("does not tell the client to retry an in-flight payment id on the consumed task") |
+| **`doctor` reporting a misconfigured RPC or facilitator as unreachable** | marks an offer `unreachable` for recognized transport failures, including refused or reset connections, temporary DNS failures and timeouts. Unresolvable hostnames, TLS and certificate errors, JSON-RPC errors, non-2xx responses, reverts, unparseable bodies, missing peers and unrecognized errors fail without this marker | `tests/unit/core/no-answer.test.ts` ("is false for %s"), `tests/unit/payments-x402/provider-health-mocked.test.ts` ("leaves the %s unmarked after %s"), `tests/integration/doctor-certainty.test.ts` ("%s: %s FAILs unmarked when %s") |
+| **`doctor` reporting a gateway that answered as unreachable** | marks `Gateway` `unreachable` for recognized transport failures, including refused or reset connections and timeouts. Unresolvable hostnames, ports rejected by fetch, non-2xx `/health` responses and Host refusals fail unmarked; checks that need the discovery document are `skipped`. Responses with unusable document content leave those checks unmarked | `tests/unit/cli/doctor-certainty.test.ts` ("when %s", "says a gateway that answered non-2xx is unhealthy, not unreachable"), `tests/integration/doctor-certainty.test.ts` ("leaves Gateway unmarked, and says why, when fetch refuses the port") |
+| **the `doctor` Secrets check printing a value or a default** | reports placeholder names in text and JSON, never variable values or defaults | `tests/unit/cli/doctor-certainty.test.ts` ("FAILs naming every missing variable, and prints no value or default"), `tests/unit/config/env.test.ts` ("returns names only: no value and no default") |
+| **an MCP Registry answer injecting text into `doctor` output** | `doctor --registry` names differing fields and uses fixed messages for known lifecycle statuses, without echoing arbitrary answer values or request error messages in text or JSON | `tests/unit/cli/doctor-registry.test.ts` ("prints no value from a hostile answer, in text or JSON", "leaves a TLS failure unmarked and does not print its message") |
+| **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest?include_deleted=true` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") |
+| **another server name listing the gateway's URL, taken for the merchant's listing** | `doctor --registry` looks up the configured name only and reports a response with another name as a difference in `name` | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "reports a listing under another name") |
+| **a support record citing a test or doc file that does not exist** | the drift check in `npm test` fails and names the record and the missing path | `tests/integration/support-record.test.ts` ("names the place of %s") |
+| **a generated support table or list edited by hand in the README or docs** | the drift check fails and names the file and region; `npm run support:write` restores the region from the records | `tests/integration/support-record.test.ts` ("names the place of %s", "--write restores a hand-edited region and refuses a file with missing markers") |
A facilitator verdict is a returned result. The SDK throws when a remote
`/verify` answers with a non-2xx status; the binding turns that throw back into
diff --git a/package-lock.json b/package-lock.json
index ca0c2e1..c00b7d2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -45,6 +45,7 @@
"@vitest/coverage-v8": "4.1.12",
"@x402/core": "2.30.0",
"@x402/evm": "2.30.0",
+ "@x402/extensions": "2.30.0",
"@x402/mcp": "2.30.0",
"@x402/near": "2.30.0",
"@x402/svm": "2.30.0",
@@ -2211,6 +2212,39 @@
"node": ">=20"
}
},
+ "node_modules/@signinwithethereum/siwe": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe/-/siwe-4.2.1.tgz",
+ "integrity": "sha512-CQEQhCIgN9blil1YpaGR+wvGPdsBVK6zed5DBu03s1IdbSO3kA/n7Zp+SAkZGiHy3HY6OJm1Su0/Bd33vKK6nQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@signinwithethereum/siwe-parser": "^4.2.1"
+ },
+ "peerDependencies": {
+ "ethers": "^5.7.0 || ^6.13.0",
+ "viem": "^2.7.0"
+ },
+ "peerDependenciesMeta": {
+ "ethers": {
+ "optional": true
+ },
+ "viem": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@signinwithethereum/siwe-parser": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe-parser/-/siwe-parser-4.2.1.tgz",
+ "integrity": "sha512-GAdwNiBaRpUMTiFfPrbQ3e/RBhPbEhRRN1sZmDMLgLEZuKqKwO7V0ksVzCerE9l8HFKTNw5R/q3kPDCWJRz4zA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@noble/hashes": "^1.7.0",
+ "apg-js": "^4.4.0"
+ }
+ },
"node_modules/@solana-program/compute-budget": {
"version": "0.18.1",
"resolved": "https://registry.npmjs.org/@solana-program/compute-budget/-/compute-budget-0.18.1.tgz",
@@ -3703,6 +3737,34 @@
"zod": "^4.6.6"
}
},
+ "node_modules/@x402/extensions": {
+ "version": "2.30.0",
+ "resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.30.0.tgz",
+ "integrity": "sha512-Lqu8hYkFAIhzarWa8V1272tyolFAW7WjHrxQ7we5P0fEZ8oMXOq1hna2X0FXQetZoOFzBDwSWBBMsrqE8ZzvcQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@noble/curves": "^1.9.0",
+ "@scure/base": "^1.2.6",
+ "@signinwithethereum/siwe": "^4.1.0",
+ "@x402/core": "~2.30.0",
+ "ajv": "^8.18.0",
+ "jose": "^5.9.6",
+ "tweetnacl": "^1.0.3",
+ "viem": "^2.48.11",
+ "zod": "^4.6.6"
+ }
+ },
+ "node_modules/@x402/extensions/node_modules/jose": {
+ "version": "5.10.0",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz",
+ "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/@x402/mcp": {
"version": "2.30.0",
"resolved": "https://registry.npmjs.org/@x402/mcp/-/mcp-2.30.0.tgz",
@@ -3859,6 +3921,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/apg-js": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/apg-js/-/apg-js-4.4.0.tgz",
+ "integrity": "sha512-fefmXFknJmtgtNEXfPwZKYkMFX4Fyeyz+fNF6JWp87biGOPslJbCBVU158zvKRZfHBKnJDy8CMM40oLFGkXT8Q==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -7129,6 +7198,13 @@
"fsevents": "~2.3.3"
}
},
+ "node_modules/tweetnacl": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
+ "dev": true,
+ "license": "Unlicense"
+ },
"node_modules/type-fest": {
"version": "5.9.0",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.9.0.tgz",
diff --git a/package.json b/package.json
index 1752aae..c303aba 100644
--- a/package.json
+++ b/package.json
@@ -90,6 +90,7 @@
"test:mainnet": "vitest run --config vitest.mainnet.config.ts",
"check:contract": "node scripts/contract-surface.mjs",
"check:metadata": "node scripts/check-package-metadata.mjs",
+ "support:write": "tsx scripts/support-record.ts --write",
"verify": "npm run check:contract && npm run lint && npm run typecheck && npm test",
"agent-commerce": "tsx src/cli/index.ts",
"doctor": "tsx src/cli/index.ts doctor",
@@ -189,6 +190,7 @@
"@vitest/coverage-v8": "4.1.12",
"@x402/core": "2.30.0",
"@x402/evm": "2.30.0",
+ "@x402/extensions": "2.30.0",
"@x402/mcp": "2.30.0",
"@x402/near": "2.30.0",
"@x402/svm": "2.30.0",
diff --git a/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md b/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md
index 80e0d51..061fb01 100644
--- a/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md
+++ b/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md
@@ -77,12 +77,21 @@ before retrying; the gateway does not refund the payment automatically.
otherwise it is 0, even with warnings. For L2, also require a passing `Gateway`
check and report warnings.
-| Check | Not passing means |
-| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `Config` | `validate` would fail; fix that first |
-| `Gateway` | `FAIL`: `/health` is unreachable or returns a non-2xx status. Check the URL derived from `server.host` and `server.port`, or pass `--gateway `. `WARN`: `/health` passed but `/ready` did not; inspect `/ready` for store, adapter or provider failures |
-| `Backend` | No HTTP response from some or all distinct configured URLs. Probes use GET without backend headers or a body, substitute `demo-check` for path parameters and accept any HTTP status as reachable. Check the API and `MERCHANT_API_BASE_URL`; a PASS does not verify the configured operation |
-| `Protocols` | The gateway's `/.well-known/agent-commerce` is unreachable |
-| `Payments`, `Payments (MPP)` | The running gateway's live offers or MPP setting differ from the config, usually because it runs an older config. Restart it |
-| `Payments (offers)` | `FAIL`: an offer's health check fails; `WARN`: one is degraded. Causes include an unreachable RPC or facilitator, or a missing Solana, NEAR or CDP peer. Inspect `/ready`; the gateway logs each reason at debug level |
-| `Storage` | `WARN`: no receipts file at `storage.receipts.path` yet, or the running gateway uses another path. `FAIL`: the file cannot be opened |
+A check that cannot reach a verdict carries `undetermined`: `unreachable`
+for a recognized transport failure, or `skipped` when a prerequisite fails.
+For an `unreachable` `Gateway` or `Backend`, check the service, its address and
+network access. An unmarked failure naming `ENOTFOUND`, a certificate or
+`bad port` calls for checking DNS, TLS configuration and the URL. For a
+`skipped` check, fix the failing `Config` or `Gateway` first. Text output
+appends `[not determined: ]`.
+
+| Check | Not passing means |
+| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `Config` | `validate` would fail; fix that first |
+| `Secrets` | `FAIL`: a `${VAR}` placeholder in the config is unset; the detail lists all missing names, never values. Set them in the environment or in a file passed with `--env-file` |
+| `Gateway` | `FAIL`: `/health` could not be checked or returned a non-2xx status. The `unreachable` marker identifies recognized transport failures. Check the URL derived from `server.host` and `server.port`, or pass `--gateway `. `WARN`: `/health` passed but `/ready` did not; inspect `/ready` for store, adapter or provider failures |
+| `Backend` | No HTTP response from some or all distinct configured URLs. Probes use GET without backend headers or a body, substitute `demo-check` for path parameters and accept any HTTP status as reachable. Check the API and `MERCHANT_API_BASE_URL`; a PASS does not verify the configured operation |
+| `Protocols` | The gateway's `/.well-known/agent-commerce` gave no answer or a non-2xx status |
+| `Payments`, `Payments (MPP)` | The running gateway's live offers or MPP setting differ from the config, usually because it runs an older config. Restart it |
+| `Payments (offers)`, `Payments (MPP offers)` | `FAIL`: an offer's health check fails; `WARN`: one is degraded. `unreachable` means every failing or degraded offer has a recognized RPC or facilitator transport failure. Unmarked failures can indicate a bad response, a hostname that does not resolve, a TLS error, or a missing Solana, NEAR or CDP peer. Inspect `/ready`; the gateway logs each reason at debug level |
+| `Storage` | `WARN`: no receipts file at `storage.receipts.path` yet, or the running gateway uses another path. `FAIL`: the file cannot be opened |
diff --git a/scripts/support-record.ts b/scripts/support-record.ts
new file mode 100644
index 0000000..23fee4d
--- /dev/null
+++ b/scripts/support-record.ts
@@ -0,0 +1,650 @@
+/**
+ * Validate the support records under `src/support/`, one per shipped profile,
+ * and render the docs regions generated from them. Each record states the
+ * revision, subset, exclusions, deviations and evidence its status covers.
+ * Descriptors and `doctor` trust these files at runtime. This schema runs in
+ * tests and tooling and is excluded from the published package.
+ *
+ * npm run support:write rewrite every generated region from the records
+ *
+ * `tests/integration/support-record.test.ts` fails on any drift and names the
+ * file, the region and the record.
+ */
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { z } from 'zod';
+
+// Also the order every generated table lists the profiles in
+export const SUPPORT_RECORD_NAMES = ['http', 'mcp', 'x402', 'mpp', 'a2a', 'acp', 'ap2'] as const;
+
+export const REPO_ROOT = join(import.meta.dirname, '..');
+
+const text = z.string().min(1);
+
+const SpecSchema = z.strictObject({
+ // Revision identifiers for comparison with code
+ revisions: z.array(text).min(1),
+ // Display text for the pinned revision
+ display: text,
+ source: z.strictObject({ repo: text, commit: z.string().regex(/^[0-9a-f]{40}$/) }),
+ // Whether upstream calls the pinned revision stable; null when unspecified
+ stable: z.boolean().nullable(),
+ // Upstream's own words on the revision's status
+ statement: text,
+ // The date `statement` was read
+ checked: z.iso.date(),
+});
+
+const SupportRecordSchema = z
+ .strictObject({
+ name: z.enum(SUPPORT_RECORD_NAMES),
+ kind: z.enum(['protocol', 'payment', 'authorization']),
+ title: text,
+ status: z.enum(['supported', 'experimental']),
+ // The profile's role as a transport, payment rail or authorization method
+ role: text,
+ subset: text,
+ spec: SpecSchema.optional(),
+ // Package names; version pins live in package.json
+ packages: z.array(z.strictObject({ name: text, use: z.enum(['runtime', 'test']) })),
+ // Vendored schemas and fixtures
+ artifacts: z.array(z.strictObject({ path: text, revision: text })),
+ // Descriptor capabilities, each with its own status
+ features: z.array(
+ z.strictObject({
+ name: text,
+ status: z.enum(['supported', 'experimental', 'partial']),
+ // A feature with its own spec gets its own matrix row, under `title`
+ spec: SpecSchema.optional(),
+ title: text.optional(),
+ role: text.optional(),
+ subset: text.optional(),
+ }),
+ ),
+ // `name` is the string the descriptor publishes in `unsupported`
+ exclusions: z.array(
+ z.strictObject({ name: text, note: text.optional(), feature: text.optional() }),
+ ),
+ deviations: z.array(
+ z.strictObject({
+ summary: text,
+ // The specification and section the behavior departs from
+ spec: text,
+ upstream: text.optional(),
+ tests: z.array(text).min(1),
+ }),
+ ),
+ // Payment records: the surface, rail and authorization covered by the evidence
+ combinations: z
+ .array(
+ z.strictObject({
+ surface: z.enum(['http', 'mcp', 'a2a']),
+ method: z.enum(['x402', 'mpp']),
+ authorization: z.literal('ap2').optional(),
+ level: z.enum(['e2e', 'integration', 'testnet', 'mainnet']),
+ evidence: text,
+ }),
+ )
+ .optional(),
+ conformance: z
+ .strictObject({
+ suite: text,
+ tests: z.array(text).min(1),
+ skipped: z.array(
+ z.strictObject({
+ test: text,
+ reason: text,
+ spec: text.optional(),
+ upstream: text.optional(),
+ }),
+ ),
+ })
+ .optional(),
+ // Known MUST-level gaps against the pinned revision
+ gaps: z.array(
+ z.strictObject({ requirement: text, state: z.enum(['open', 'closed', 'excluded']) }),
+ ),
+ docs: z.array(text).min(1),
+ })
+ .superRefine((record, ctx) => {
+ const duplicates = (names: readonly string[]) =>
+ names.filter((name, index) => names.indexOf(name) !== index);
+ const features = record.features.map((feature) => feature.name);
+ for (const name of duplicates(features)) {
+ ctx.addIssue({ code: 'custom', path: ['features'], message: `duplicate feature "${name}"` });
+ }
+ for (const name of duplicates(record.exclusions.map((exclusion) => exclusion.name))) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['exclusions'],
+ message: `duplicate exclusion "${name}"`,
+ });
+ }
+ for (const exclusion of record.exclusions) {
+ if (exclusion.feature !== undefined && !features.includes(exclusion.feature)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['exclusions'],
+ message: `exclusion "${exclusion.name}" names unknown feature "${exclusion.feature}"`,
+ });
+ }
+ }
+ for (const feature of record.features) {
+ const row = [feature.title, feature.role, feature.subset];
+ if ((feature.spec !== undefined) !== row.every((field) => field !== undefined)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['features'],
+ message: `feature "${feature.name}" needs title, role and subset exactly when it has a spec`,
+ });
+ }
+ }
+ if (record.combinations !== undefined && record.kind !== 'payment') {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['combinations'],
+ message: 'only a payment record lists tested combinations',
+ });
+ }
+ });
+
+export type SupportRecord = z.infer;
+export type SupportRecordName = (typeof SUPPORT_RECORD_NAMES)[number];
+
+export function supportRecordPath(name: SupportRecordName): string {
+ return join(REPO_ROOT, 'src/support', `${name}.json`);
+}
+
+/** Read and validate a record; schema errors include the file path and validation details */
+export function readSupportRecord(name: SupportRecordName): SupportRecord {
+ const path = supportRecordPath(name);
+ const parsed = SupportRecordSchema.safeParse(JSON.parse(readFileSync(path, 'utf8')));
+ if (!parsed.success) {
+ throw new Error(`src/support/${name}.json: ${z.prettifyError(parsed.error)}`);
+ }
+ if (parsed.data.name !== name) {
+ throw new Error(`src/support/${name}.json: name is "${parsed.data.name}", not "${name}"`);
+ }
+ return parsed.data;
+}
+
+/** Evidence and documentation paths to check for existence, each once */
+export function citedPaths(record: SupportRecord): string[] {
+ return [
+ ...new Set([
+ ...record.artifacts.map((artifact) => artifact.path),
+ ...(record.combinations ?? []).map((combination) => combination.evidence),
+ ...(record.conformance?.tests ?? []),
+ ...(record.conformance?.skipped ?? []).map((skipped) => skipped.test),
+ ...record.deviations.flatMap((deviation) => deviation.tests),
+ ...record.docs,
+ ]),
+ ];
+}
+
+export interface PackageManifest {
+ readonly dependencies?: Readonly>;
+ readonly devDependencies?: Readonly>;
+ readonly peerDependencies?: Readonly>;
+}
+
+/** Everything the drift check reads, injectable for tests that mutate a copy */
+export interface SupportTree {
+ readonly records: readonly SupportRecord[];
+ readonly manifest: PackageManifest;
+ /** Undefined when the file does not exist */
+ readonly read: (path: string) => string | undefined;
+ readonly exists: (path: string) => boolean;
+}
+
+export function readSupportTree(): SupportTree {
+ return {
+ records: SUPPORT_RECORD_NAMES.map(readSupportRecord),
+ manifest: JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')) as PackageManifest,
+ read: (path) => {
+ const full = join(REPO_ROOT, path);
+ return existsSync(full) ? readFileSync(full, 'utf8') : undefined;
+ },
+ exists: (path) => existsSync(join(REPO_ROOT, path)),
+ };
+}
+
+// Rendering
+
+const STATUS_WORD = { supported: 'Supported', experimental: 'Experimental', partial: 'Partial' };
+
+// Supported badges keep each project's color; experimental ones share one
+const BADGE_COLOR: Readonly> = { mcp: '6b4fbb', x402: '0052ff' };
+const SUPPORTED_BADGE = '2ea44f';
+const EXPERIMENTAL_BADGE = 'f0a30a';
+
+const SURFACE_TITLE = { http: 'HTTP', mcp: 'MCP', a2a: 'A2A' };
+const LEVEL_TITLE = {
+ e2e: 'E2E, local chain',
+ integration: 'integration, no chain',
+ testnet: 'public testnet',
+ mainnet: 'mainnet',
+};
+
+// A Markdown table with every column padded to its widest cell
+function table(header: readonly string[], body: readonly (readonly string[])[]): string {
+ const rows = body.map((row) => row.map((cell) => cell.replaceAll('|', '\\|')));
+ const widths = header.map((cell, column) =>
+ Math.max(3, cell.length, ...rows.map((row) => (row[column] ?? '').length)),
+ );
+ const line = (cells: readonly string[]) =>
+ `| ${cells.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(' | ')} |`;
+ return [line(header), line(widths.map((width) => '-'.repeat(width))), ...rows.map(line)].join(
+ '\n',
+ );
+}
+
+// A Markdown block between region markers, set off by blank lines
+const block = (text: string) => `\n${text}\n\n`;
+
+type Spec = NonNullable;
+type Package = SupportRecord['packages'][number];
+
+function packageVersion(manifest: PackageManifest, pkg: Package): string | undefined {
+ return pkg.use === 'test'
+ ? manifest.devDependencies?.[pkg.name]
+ : (manifest.peerDependencies?.[pkg.name] ?? manifest.dependencies?.[pkg.name]);
+}
+
+const pinned = (manifest: PackageManifest, pkg: Package) =>
+ `\`${pkg.name}@${packageVersion(manifest, pkg) ?? 'missing'}\``;
+
+function revisionCell(record: SupportRecord, manifest: PackageManifest): string {
+ const runtime = record.packages.filter((pkg) => pkg.use === 'runtime');
+ const packages = runtime.map((pkg) => pinned(manifest, pkg)).join(', ');
+ const display = record.spec?.display ?? 'native';
+ return packages === '' ? display : `${display}; ${packages}`;
+}
+
+interface MatrixRow {
+ readonly title: string;
+ readonly status: string;
+ readonly role: string;
+ readonly revision: string;
+ readonly subset: string;
+}
+
+// One row per record, then one per feature that has its own spec
+function matrixRows(records: readonly SupportRecord[], manifest: PackageManifest): MatrixRow[] {
+ return [
+ ...records.map((record) => ({
+ title: record.title,
+ status: STATUS_WORD[record.status],
+ role: record.role,
+ revision: revisionCell(record, manifest),
+ subset: record.subset,
+ })),
+ ...records.flatMap((record) =>
+ record.features.flatMap((feature) =>
+ feature.spec === undefined
+ ? []
+ : [
+ {
+ title: feature.title ?? feature.name,
+ status: STATUS_WORD[feature.status],
+ role: feature.role ?? '',
+ revision: feature.spec.display,
+ subset: feature.subset ?? '',
+ },
+ ],
+ ),
+ ),
+ ];
+}
+
+function badges(records: readonly SupportRecord[]): string {
+ return records
+ .filter((record) => record.spec !== undefined)
+ .map((record) => {
+ const color =
+ record.status === 'experimental'
+ ? EXPERIMENTAL_BADGE
+ : (BADGE_COLOR[record.name] ?? SUPPORTED_BADGE);
+ const label = record.title.replaceAll('-', '--');
+ return `
\n`;
+ })
+ .join('');
+}
+
+function specRows(spec: Spec, prefix: string): string[][] {
+ const commit = spec.source.commit;
+ const stable = spec.stable === null ? 'not stated' : spec.stable ? 'yes' : 'no';
+ return [
+ [`${prefix}pinned revision`, spec.display],
+ [
+ `${prefix}upstream source`,
+ `[\`${spec.source.repo}@${commit.slice(0, 8)}\`](https://github.com/${spec.source.repo}/tree/${commit})`,
+ ],
+ [`${prefix}declared stable upstream`, stable],
+ [`${prefix}upstream wording`, `"${spec.statement}" (read ${spec.checked})`],
+ ];
+}
+
+function pins(record: SupportRecord, manifest: PackageManifest): string {
+ const use = (pkg: Package) => {
+ if (pkg.use === 'test') return 'tests only';
+ return manifest.peerDependencies?.[pkg.name] !== undefined ? 'optional peer' : 'dependency';
+ };
+ const rows = [
+ ...(record.spec === undefined ? [] : specRows(record.spec, '')),
+ ...record.features.flatMap((feature) =>
+ feature.spec === undefined ? [] : specRows(feature.spec, `${feature.title} `),
+ ),
+ ...record.packages.map((pkg) => [
+ `\`${pkg.name}\``,
+ `\`${packageVersion(manifest, pkg) ?? 'missing'}\`, ${use(pkg)}`,
+ ]),
+ ...record.artifacts.map((artifact) => [
+ `\`${artifact.path}\``,
+ `vendored from \`${artifact.revision.slice(0, 8)}\``,
+ ]),
+ ];
+ // Capitalize the first word of each label that is not a package or a path
+ const label = (cell: string) =>
+ cell.startsWith('`') ? cell : `${cell.charAt(0).toUpperCase()}${cell.slice(1)}`;
+ return table(
+ ['Pin', 'Value'],
+ rows.map(([name = '', value = '']) => [label(name), value]),
+ );
+}
+
+function exclusionList(exclusions: SupportRecord['exclusions']): string {
+ return exclusions
+ .map(
+ (exclusion) =>
+ `- \`${exclusion.name}\`${exclusion.note === undefined ? '' : `: ${exclusion.note}`}`,
+ )
+ .join('\n');
+}
+
+function deviationList(record: SupportRecord): string {
+ return record.deviations
+ .map((deviation) => {
+ const tests = deviation.tests.map((test) => `\`${test}\``).join(', ');
+ const upstream =
+ deviation.upstream === undefined ? '' : ` Reported upstream: ${deviation.upstream}.`;
+ return `- **${deviation.spec}**: ${deviation.summary}${upstream} Tests: ${tests}.`;
+ })
+ .join('\n');
+}
+
+function combinations(records: readonly SupportRecord[]): string {
+ const rows = records.flatMap((record) =>
+ (record.combinations ?? []).map((combination) => [
+ record.title,
+ SURFACE_TITLE[combination.surface],
+ combination.authorization === undefined ? '-' : 'AP2',
+ LEVEL_TITLE[combination.level],
+ `\`${combination.evidence}\``,
+ ]),
+ );
+ return table(['Rail', 'Surface', 'Authorization', 'Tested at', 'Test'], rows);
+}
+
+export interface RenderedRegion {
+ readonly body: string;
+ /** What the region is generated from, named in a drift report */
+ readonly source: string;
+}
+
+/** Every generated region, by repository path and region id */
+export function renderRegions(
+ records: readonly SupportRecord[],
+ manifest: PackageManifest,
+): Map> {
+ const all = 'src/support/*.json and package.json';
+ const matrix = matrixRows(records, manifest);
+ const regions = new Map>([
+ [
+ 'README.md',
+ new Map([
+ ['badges', { body: badges(records), source: 'src/support/*.json' }],
+ [
+ 'matrix',
+ {
+ body: block(
+ table(
+ ['Protocol', 'Status', 'Pinned revision', 'Implemented subset'],
+ matrix.map((row) => [`**${row.title}**`, row.status, row.revision, row.subset]),
+ ),
+ ),
+ source: all,
+ },
+ ],
+ ]),
+ ],
+ [
+ 'docs/protocols.md',
+ new Map([
+ [
+ 'matrix',
+ {
+ body: block(
+ table(
+ ['Protocol', 'Status', 'Role', 'Revision', 'Implemented subset'],
+ matrix.map((row) => [
+ `**${row.title}**`,
+ row.status,
+ row.role,
+ row.revision,
+ row.subset,
+ ]),
+ ),
+ ),
+ source: all,
+ },
+ ],
+ ['combinations', { body: block(combinations(records)), source: 'src/support/*.json' }],
+ ]),
+ ],
+ ]);
+ for (const record of records) {
+ const source = `src/support/${record.name}.json`;
+ const page = new Map();
+ if (record.spec !== undefined || record.packages.length > 0 || record.artifacts.length > 0) {
+ page.set('pins', {
+ body: block(pins(record, manifest)),
+ source: `${source} and package.json`,
+ });
+ }
+ const untagged = record.exclusions.filter((exclusion) => exclusion.feature === undefined);
+ if (untagged.length > 0) {
+ page.set('exclusions', { body: block(exclusionList(untagged)), source });
+ }
+ for (const feature of new Set(record.exclusions.flatMap((e) => e.feature ?? []))) {
+ const tagged = record.exclusions.filter((exclusion) => exclusion.feature === feature);
+ page.set(`exclusions:${feature}`, { body: block(exclusionList(tagged)), source });
+ }
+ if (record.deviations.length > 0) {
+ page.set('deviations', { body: block(deviationList(record)), source });
+ }
+ if (page.size > 0) regions.set(`docs/protocols/${record.name}.md`, page);
+ }
+ return regions;
+}
+
+// Regions in a file
+
+const REGION =
+ /^([ \t]*)\n([\s\S]*?)^[ \t]*/gm;
+
+interface FoundRegion {
+ readonly id: string;
+ readonly body: string;
+}
+
+function findRegions(content: string): FoundRegion[] {
+ return [...content.matchAll(REGION)].map((match) => ({
+ id: match[2] ?? '',
+ body: match[3] ?? '',
+ }));
+}
+
+function replaceRegions(content: string, rendered: ReadonlyMap): string {
+ return content.replace(REGION, (whole, indent: string, id: string) => {
+ const region = rendered.get(id);
+ if (region === undefined) return whole;
+ return `${indent}\n${region.body}${indent}`;
+ });
+}
+
+// The drift check
+
+const titleNamed = (text: string, title: string) =>
+ new RegExp(`(^|[^\\w-])${title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w-])`).test(text);
+
+// Hand-written sentences that name the experimental profiles
+const STATUS_SENTENCES = [
+ {
+ path: 'README.md',
+ place: 'Versioning sentence',
+ find: (content: string) => /### Versioning\n\n([\s\S]*?)\n\n/.exec(content)?.[1],
+ },
+ {
+ path: 'plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md',
+ place: '"exist but are experimental" sentence',
+ find: (content: string) => /[^.]*exist but are experimental[^.]*\./.exec(content)?.[0],
+ },
+];
+
+// x402 route table rows, by the start of the route, and the feature each row states
+const X402_ROUTES: readonly [string, string][] = [
+ ['EIP-3009 ', 'eip-3009'],
+ ['Permit2 ', 'permit2'],
+ ['Solana', 'exact-svm'],
+ ['NEAR', 'exact-near'],
+];
+
+function handWrittenProblems(tree: SupportTree): string[] {
+ const problems: string[] = [];
+ const experimental = tree.records.filter((record) => record.status === 'experimental');
+ for (const sentence of STATUS_SENTENCES) {
+ const text = sentence.find(tree.read(sentence.path) ?? '');
+ if (text === undefined) {
+ problems.push(`${sentence.path}: ${sentence.place} not found`);
+ continue;
+ }
+ for (const record of tree.records) {
+ const named = titleNamed(text, record.title);
+ if (named !== experimental.includes(record)) {
+ problems.push(
+ `${sentence.path}: the ${sentence.place} ${named ? 'names' : 'omits'} ${record.title}, which src/support/${record.name}.json records as ${record.status}`,
+ );
+ }
+ }
+ }
+ for (const record of tree.records) {
+ const path = `docs/protocols/${record.name}.md`;
+ const marked = (tree.read(path) ?? '').includes('**Experimental.**');
+ if (marked !== (record.status === 'experimental')) {
+ problems.push(
+ `${path}: ${marked ? 'says' : 'does not say'} **Experimental.**, but src/support/${record.name}.json records ${record.status}`,
+ );
+ }
+ }
+ const x402 = tree.records.find((record) => record.name === 'x402');
+ const routes = /## Support matrix\n[\s\S]*?\n(\|[\s\S]*?)\n\n/.exec(
+ tree.read('docs/protocols/x402.md') ?? '',
+ )?.[1];
+ for (const [prefix, featureName] of X402_ROUTES) {
+ const feature = x402?.features.find((candidate) => candidate.name === featureName);
+ const rows = (routes ?? '')
+ .split('\n')
+ .map((line) => line.split('|').map((cell) => cell.trim()))
+ .filter((cells) => cells[1]?.startsWith(prefix));
+ if (rows.length === 0) {
+ problems.push(`docs/protocols/x402.md: no support matrix row starts with "${prefix.trim()}"`);
+ }
+ for (const cells of rows) {
+ if (cells[2] !== feature?.status) {
+ problems.push(
+ `docs/protocols/x402.md: the "${cells[1]}" row says ${cells[2]}, but src/support/x402.json records ${featureName} as ${feature?.status}`,
+ );
+ }
+ }
+ }
+ return problems;
+}
+
+/** Every disagreement between the records, package.json and the docs, each naming its place */
+export function supportProblems(tree: SupportTree): string[] {
+ const problems: string[] = [];
+ const { manifest } = tree;
+ for (const record of tree.records) {
+ const source = `src/support/${record.name}.json`;
+ for (const pkg of record.packages) {
+ const runtime = manifest.peerDependencies?.[pkg.name] ?? manifest.dependencies?.[pkg.name];
+ const declared =
+ pkg.use === 'runtime'
+ ? runtime !== undefined
+ : manifest.devDependencies?.[pkg.name] !== undefined && runtime === undefined;
+ if (!declared) {
+ problems.push(
+ `${source}: package ${pkg.name} (${pkg.use}) is not in package.json ${pkg.use === 'runtime' ? 'dependencies or peerDependencies' : 'devDependencies alone'}`,
+ );
+ }
+ }
+ for (const path of citedPaths(record)) {
+ if (!tree.exists(path)) problems.push(`${source}: cites ${path}, which does not exist`);
+ }
+ }
+ for (const [path, regions] of renderRegions(tree.records, manifest)) {
+ const content = tree.read(path);
+ if (content === undefined) {
+ problems.push(`${path}: missing, but support regions are generated into it`);
+ continue;
+ }
+ const found = findRegions(content);
+ for (const [id, region] of regions) {
+ const matches = found.filter((candidate) => candidate.id === id);
+ if (matches.length !== 1) {
+ problems.push(`${path}: region "${id}" appears ${matches.length} times, not once`);
+ } else if (matches[0]?.body !== region.body) {
+ problems.push(
+ `${path}: region "${id}" differs from ${region.source}; run npm run support:write`,
+ );
+ }
+ }
+ for (const region of found) {
+ if (!regions.has(region.id)) problems.push(`${path}: unknown region "${region.id}"`);
+ }
+ }
+ return [...problems, ...handWrittenProblems(tree)];
+}
+
+/** The new content of each file whose generated regions are out of date */
+export function regionUpdates(tree: SupportTree): Map {
+ const updates = new Map();
+ for (const [path, regions] of renderRegions(tree.records, tree.manifest)) {
+ const content = tree.read(path);
+ if (content === undefined) throw new Error(`${path}: missing`);
+ const ids = new Set(findRegions(content).map((region) => region.id));
+ const absent = [...regions.keys()].filter((id) => !ids.has(id));
+ if (absent.length > 0) {
+ throw new Error(`${path}: add the markers for region(s) ${absent.join(', ')} first`);
+ }
+ const next = replaceRegions(content, regions);
+ if (next !== content) updates.set(path, next);
+ }
+ return updates;
+}
+
+if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ if (!process.argv.includes('--write')) {
+ console.error('usage: tsx scripts/support-record.ts --write');
+ process.exit(2);
+ }
+ const updates = regionUpdates(readSupportTree());
+ for (const [path, content] of updates) writeFileSync(join(REPO_ROOT, path), content);
+ console.log(
+ updates.size === 0
+ ? 'support regions: unchanged'
+ : `support regions: rewrote ${[...updates.keys()].join(', ')}`,
+ );
+}
diff --git a/src/authorization/ap2/descriptor.ts b/src/authorization/ap2/descriptor.ts
index 31f78a9..414e0ef 100644
--- a/src/authorization/ap2/descriptor.ts
+++ b/src/authorization/ap2/descriptor.ts
@@ -1,10 +1,8 @@
-/**
- * Adapter self-description.
- *
- * Imports nothing but core types and the pins, so `doctor` can report AP2
- * without pulling `jose` or `@sd-jwt/core` into the CLI bundle.
- */
+// AP2 pins and support metadata for diagnostics, without loading the optional
+// `jose` or `@sd-jwt/core` peers
import type { AdapterDescriptor } from '../../core';
+import record from '../../support/ap2.json' with { type: 'json' };
+import { descriptorStatus, exclusionNames } from '../../support/claims';
import {
AP2_CHECKOUT_MANDATE_VCT,
AP2_CHECKOUT_PROFILE,
@@ -29,32 +27,10 @@ export const AP2_CAPABILITIES: readonly string[] = [
];
/**
- * Major AP2 features this provider does not support, published in its
- * descriptor and printed by `doctor`, so no client assumes full protocol
- * support
+ * Unsupported AP2 features from the support record, published in the descriptor
+ * and printed by `doctor` to show the limits of protocol support
*/
-export const AP2_UNSUPPORTED: readonly string[] = [
- // Mandate kinds. Open mandates are refused: see AP2_CHECKOUT_MANDATE_VCT
- 'autonomous mode',
- 'open checkout mandates (mandate.checkout.open.1)',
- 'payment mandates (mandate.payment.1)',
- 'spending constraint evaluation',
- 'cnf-bound agent keys',
- // Delegation models other than a trusted agent provider
- 'user credential delegation (OpenID4VP)',
- 'delegation chains and key-binding JWTs',
- // Key handling. Every key is written into config by an operator
- 'JWKS and any key discovery by URL (jku, x5u)',
- 'issuer metadata fetching',
- 'key rotation without a config change',
- // Algorithms
- 'signature algorithms other than ES256',
- 'digest algorithms other than sha-256',
- // Roles this gateway does not play
- 'mandate issuance',
- 'checkout receipts',
- 'AP2 over the ACP checkout adapter',
-];
+export const AP2_UNSUPPORTED: readonly string[] = exclusionNames(record);
export function buildAp2Descriptor(implementationVersion: string): AdapterDescriptor {
return {
@@ -63,7 +39,7 @@ export function buildAp2Descriptor(implementationVersion: string): AdapterDescri
implementationVersion,
supportedSpec: `ap2/v${AP2_SPEC_VERSION} mode=direct`,
capabilities: AP2_CAPABILITIES,
- status: 'experimental',
+ status: descriptorStatus(record),
unsupported: AP2_UNSUPPORTED,
};
}
diff --git a/src/cli/commands/doctor/ap2.ts b/src/cli/commands/doctor/ap2.ts
index edf3821..810c1b2 100644
--- a/src/cli/commands/doctor/ap2.ts
+++ b/src/cli/commands/doctor/ap2.ts
@@ -1,16 +1,17 @@
// AP2 checks: settings, trust lists, the replay store and the gated resources
-// Constants and a descriptor only: the AP2 provider would pull the optional
-// peers `jose`, `@sd-jwt/core` and `canonicalize` into the CLI bundle
+// Read AP2 constants and support metadata directly to keep the optional peers
+// `jose`, `@sd-jwt/core` and `canonicalize` out of the static CLI imports
import {
AP2_CHECKOUT_MANDATE_VCT,
AP2_CHECKOUT_PROFILE,
AP2_SPEC_VERSION,
} from '../../../authorization/ap2/constants';
-import { AP2_UNSUPPORTED } from '../../../authorization/ap2/descriptor';
+import ap2Record from '../../../support/ap2.json' with { type: 'json' };
+import { exclusionNames } from '../../../support/claims';
import type { GatewayConfig } from '../../lib/config-client';
import { type LegacyState, legacyStoreCheck } from './storage';
-import type { DoctorCheck } from './types';
+import { type DoctorCheck, SKIPPED_CONFIG_INVALID } from './types';
// Issuer ids and how many keys each carries. Never a key
function describeIssuers(
@@ -32,14 +33,14 @@ export function ap2Checks(config: GatewayConfig | undefined, legacy: LegacyState
// issuer ids and key counts appear.
const ap2 = config?.authorization?.ap2;
if (config === undefined) {
- checks.push({ name: 'AP2', status: 'WARN', detail: 'skipped: config invalid' });
+ checks.push({ name: 'AP2', status: 'WARN', ...SKIPPED_CONFIG_INVALID });
} else if (ap2 === undefined || !ap2.enabled) {
checks.push({ name: 'AP2', status: 'INFO', detail: 'disabled' });
} else {
checks.push({
name: 'AP2',
status: 'PASS',
- detail: `experimental · spec ${AP2_SPEC_VERSION} · mode ${ap2.mode} · ${AP2_CHECKOUT_MANDATE_VCT} · profile ${AP2_CHECKOUT_PROFILE} · clock skew ${ap2.clockSkewSeconds}s · mandate aud ${ap2.requireMandateAudience === true ? 'required' : 'optional'} · mandate exp ${ap2.requireMandateExpiry === true ? 'required' : 'optional'}`,
+ detail: `${ap2Record.status} · spec ${AP2_SPEC_VERSION} · mode ${ap2.mode} · ${AP2_CHECKOUT_MANDATE_VCT} · profile ${AP2_CHECKOUT_PROFILE} · clock skew ${ap2.clockSkewSeconds}s · mandate aud ${ap2.requireMandateAudience === true ? 'required' : 'optional'} · mandate exp ${ap2.requireMandateExpiry === true ? 'required' : 'optional'}`,
});
// Two lists, reported separately: signing the merchant's checkout
@@ -77,7 +78,7 @@ export function ap2Checks(config: GatewayConfig | undefined, legacy: LegacyState
checks.push({
name: 'AP2 unsupported',
status: 'INFO',
- detail: AP2_UNSUPPORTED.join(', '),
+ detail: exclusionNames(ap2Record).join(', '),
});
}
return checks;
diff --git a/src/cli/commands/doctor/index.ts b/src/cli/commands/doctor/index.ts
index bf1a479..166d08f 100644
--- a/src/cli/commands/doctor/index.ts
+++ b/src/cli/commands/doctor/index.ts
@@ -5,7 +5,11 @@ import {
createSqliteReceiptStore,
openSqliteReceiptStoreReadOnly,
} from '../../../storage/receipts';
-import { type GatewayConfig, loadConfigDynamic } from '../../lib/config-client';
+import {
+ type GatewayConfig,
+ loadConfigDynamic,
+ readConfigFileDynamic,
+} from '../../lib/config-client';
import { fetchJson } from '../../lib/http';
import {
fillEnvFromLocalChainManifest,
@@ -17,8 +21,19 @@ import { readVersionReport } from '../../lib/versions';
import { ap2Checks } from './ap2';
import { paymentChecks } from './payments';
import { protocolChecks } from './protocols';
+import { registryCheck } from './registry';
+import { secretsCheck } from './secrets';
import { storageChecks } from './storage';
-import type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types';
+import {
+ type CheckStatus,
+ type DoctorCheck,
+ type DoctorDeps,
+ type DoctorOptions,
+ type DoctorReport,
+ SKIPPED_CONFIG_INVALID,
+ type Undetermined,
+ undeterminedField,
+} from './types';
const CHECK_TIMEOUT_MS = 1500;
@@ -51,7 +66,7 @@ function substitutePathParams(url: string): string {
return filled;
}
-/** `agent-commerce doctor [--config] [--gateway] [--json]` */
+/** `agent-commerce doctor [--config] [--gateway] [--json] [--registry]` */
export async function runDoctor(
options: DoctorOptions,
deps: DoctorDeps = {},
@@ -101,22 +116,39 @@ export async function runDoctor(
});
}
+ // Skip Secrets when an injected loader has no reader; the default could read
+ // a different config
+ const readConfigFile =
+ deps.readConfigFile ?? (deps.loadConfig === undefined ? readConfigFileDynamic : undefined);
+ if (readConfigFile !== undefined) {
+ checks.push(await secretsCheck(readConfigFile, options.configPath, env));
+ }
+
const gatewayUrl = deriveGatewayUrl(options.gatewayUrl, config);
- // 2. Gateway
+ // 2. Gateway. Status 0 means the request threw; `noAnswer` identifies a known
+ // transport failure. Hostname and TLS errors remain unmarked.
const health = await fetchJson(fetchImpl, `${gatewayUrl}/health`, CHECK_TIMEOUT_MS);
let gatewayUp = false;
+ // Why the checks that read the well-known document have no live data
+ let liveCause: Undetermined | undefined;
if (!health.ok) {
+ liveCause = health.noAnswer ? 'unreachable' : 'skipped';
checks.push({
name: 'Gateway',
status: 'FAIL',
- detail: `unreachable at ${gatewayUrl} (${health.error ?? `HTTP ${health.status}`})`,
+ detail:
+ health.status === 0
+ ? `unreachable at ${gatewayUrl} (${health.error ?? 'no answer'})`
+ : `unhealthy at ${gatewayUrl} (HTTP ${health.status})`,
+ ...undeterminedField(health.noAnswer ? 'unreachable' : undefined),
});
} else {
const ready = await fetchJson(fetchImpl, `${gatewayUrl}/ready`, CHECK_TIMEOUT_MS);
// Doctor sends no Origin header, so a 403 from /ready means the Host was
// rejected. GET /health skips the Host check used by other routes.
if (ready.status === 403) {
+ liveCause = 'skipped';
checks.push({
name: 'Gateway',
status: 'FAIL',
@@ -131,6 +163,7 @@ export async function runDoctor(
name: 'Gateway',
status: 'WARN',
detail: `healthy but not ready at ${gatewayUrl} (${ready.error ?? `HTTP ${ready.status}`})`,
+ ...undeterminedField(ready.noAnswer ? 'unreachable' : undefined),
},
);
}
@@ -138,7 +171,7 @@ export async function runDoctor(
// 3. Backend(s)
if (config === undefined) {
- checks.push({ name: 'Backend', status: 'WARN', detail: 'skipped: config invalid' });
+ checks.push({ name: 'Backend', status: 'WARN', ...SKIPPED_CONFIG_INVALID });
} else if (config.resources.length === 0) {
checks.push({ name: 'Backend', status: 'INFO', detail: 'no resources configured' });
} else {
@@ -147,13 +180,19 @@ export async function runDoctor(
const results = await Promise.all(
urls.map((url) => fetchJson(fetchImpl, url, CHECK_TIMEOUT_MS)),
);
- const reachable = results.filter((r) => r.status !== 0).length;
+ // Any HTTP response establishes reachability. Mark unreachable only when all
+ // requests that threw have recognized transport failures.
+ const unreached = results.filter((r) => r.status === 0);
+ const reachable = urls.length - unreached.length;
const status: CheckStatus =
reachable === urls.length ? 'PASS' : reachable === 0 ? 'FAIL' : 'WARN';
checks.push({
name: 'Backend',
status,
detail: `${reachable}/${urls.length} backend host(s) reachable`,
+ ...undeterminedField(
+ unreached.length > 0 && unreached.every((r) => r.noAnswer) ? 'unreachable' : undefined,
+ ),
});
}
@@ -165,14 +204,23 @@ export async function runDoctor(
CHECK_TIMEOUT_MS,
)
: undefined;
+ // Clear the marker after any document response, even if its content is unusable
+ if (wellKnown !== undefined) liveCause = wellKnown.noAnswer ? 'unreachable' : undefined;
// 5-7. Protocols, AP2, payments and storage. Read import records first so
// protocol and AP2 checks can report the status of deprecated store keys.
const storage = await storageChecks(config, createStore);
- checks.push(...protocolChecks(config, wellKnown, storage.legacy));
+ checks.push(...protocolChecks(config, wellKnown, storage.legacy, liveCause));
checks.push(...ap2Checks(config, storage.legacy));
checks.push(
- ...(await paymentChecks(config, wellKnown, gatewayUrl, chainDeploy, deps.loadViemAccounts)),
+ ...(await paymentChecks(
+ config,
+ wellKnown,
+ gatewayUrl,
+ chainDeploy,
+ deps.loadViemAccounts,
+ liveCause,
+ )),
);
checks.push(...storage.checks);
@@ -188,10 +236,14 @@ export async function runDoctor(
checks.push({
name: 'Protocol versions',
status: 'INFO',
- detail: `gateway unreachable; local pins: ${local.pinned.map((p) => `${p.name}@${p.version}`).join(', ')}`,
+ detail: `${liveCause === 'unreachable' ? 'gateway unreachable' : 'gateway versions unavailable'}; local pins: ${local.pinned.map((p) => `${p.name}@${p.version}`).join(', ')}`,
+ ...undeterminedField(liveCause),
});
}
+ // 9. MCP Registry, only on request: it calls a third party
+ if (options.registry === true) checks.push(await registryCheck(config, fetchImpl));
+
const scored = checks.filter((c) => c.status !== 'INFO');
const passed = scored.filter((c) => c.status === 'PASS').length;
const exitCode = checks.some((c) => c.status === 'FAIL') ? 1 : 0;
@@ -200,4 +252,11 @@ export async function runDoctor(
}
export { printDoctorReport } from './report';
-export type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types';
+export type {
+ CheckStatus,
+ DoctorCheck,
+ DoctorDeps,
+ DoctorOptions,
+ DoctorReport,
+ Undetermined,
+} from './types';
diff --git a/src/cli/commands/doctor/payments.ts b/src/cli/commands/doctor/payments.ts
index 51ce656..e452d29 100644
--- a/src/cli/commands/doctor/payments.ts
+++ b/src/cli/commands/doctor/payments.ts
@@ -18,10 +18,20 @@ import {
resolveDeploymentMode,
} from '../../../payments/x402/networks';
import { X402_DEFAULT_PAYMENT_FLOW } from '../../../payments/x402/payment-flow';
+import { featureStatus } from '../../../support/claims';
+import x402Record from '../../../support/x402.json' with { type: 'json' };
import type { GatewayConfig } from '../../lib/config-client';
import { PLACEHOLDER_ASSET_ADDRESS } from '../../lib/init-config';
import { maskMiddle } from '../../lib/mask';
-import type { DoctorCheck, WellKnownResult } from './types';
+import {
+ type DoctorCheck,
+ SKIPPED_CONFIG_INVALID,
+ type Undetermined,
+ undeterminedField,
+ type WellKnownResult,
+} from './types';
+
+const QUOTE_STATUS = featureStatus(x402Record, 'erc-8409-quotes');
// The rail's settlement order and how many resources override it
function describePaymentFlow(
@@ -47,6 +57,8 @@ interface RailOffer {
readonly assetTransferMethod?: string;
/** The live offer's health status, when the gateway publishes it */
readonly status?: string;
+ // Set when the gateway reports the offer's probe as unreachable
+ readonly undetermined?: 'unreachable';
}
// A rail's terms, as configured or as the running gateway publishes them
@@ -63,7 +75,7 @@ interface RailTerms {
type LiveRailResult = RailTerms | 'disabled' | undefined;
function readOffer(rec: Record, rail: 'x402' | 'mpp'): RailOffer | undefined {
- const { asset, network, assetDecimals, assetTransferMethod, status } = rec;
+ const { asset, network, assetDecimals, assetTransferMethod, status, undetermined } = rec;
const payTo = rec[rail === 'mpp' ? 'recipient' : 'payTo'];
if (typeof asset !== 'string' || typeof network !== 'string' || typeof payTo !== 'string') {
return undefined;
@@ -75,6 +87,7 @@ function readOffer(rec: Record, rail: 'x402' | 'mpp'): RailOffe
...(typeof assetDecimals === 'number' ? { assetDecimals } : {}),
...(typeof assetTransferMethod === 'string' ? { assetTransferMethod } : {}),
...(typeof status === 'string' ? { status } : {}),
+ ...(undetermined === 'unreachable' ? { undetermined } : {}),
};
}
@@ -288,6 +301,7 @@ function railOffer(option: {
function offerHealthCheck(
live: RailTerms,
named: (network: string) => string,
+ name: string,
): DoctorCheck | undefined {
const all = [...live.offers, ...Object.values(live.resourceOffers ?? {}).flat()];
const offers = [
@@ -308,7 +322,7 @@ function offerHealthCheck(
.join('; ');
if (failing.length === 0 && degraded.length === 0) {
return {
- name: 'Payments (offers)',
+ name,
status: 'PASS',
detail: `${reported.length} offer(s) pass their health checks`,
};
@@ -317,10 +331,13 @@ function offerHealthCheck(
...(failing.length > 0 ? [`failing: ${describe(failing)}`] : []),
...(degraded.length > 0 ? [`degraded: ${describe(degraded)}`] : []),
];
+ // Keep the aggregate unmarked if any failing or degraded offer is unmarked
+ const unanswered = [...failing, ...degraded].every((offer) => offer.undetermined !== undefined);
return {
- name: 'Payments (offers)',
+ name,
status: failing.length > 0 ? 'FAIL' : 'WARN',
detail: `${problems.join('; ')}. The gateway logs each reason at debug level`,
+ ...undeterminedField(unanswered ? 'unreachable' : undefined),
};
}
@@ -380,6 +397,7 @@ function quoteCheck(
body: Record | undefined,
gatewayUrl: string,
stale: string,
+ liveCause: Undetermined | undefined,
): DoctorCheck | undefined {
const name = 'Payments (quotes)';
if (enabled && local === 'invalid') {
@@ -399,7 +417,8 @@ function quoteCheck(
? {
name,
status: 'INFO',
- detail: `ERC-8409 quotes enabled (experimental)${localIssuer !== undefined ? `, issuer=${localIssuer} from the local key` : ''}; the gateway's issuer could not be read`,
+ detail: `ERC-8409 quotes enabled (${QUOTE_STATUS})${localIssuer !== undefined ? `, issuer=${localIssuer} from the local key` : ''}; the gateway's issuer could not be read`,
+ ...undeterminedField(liveCause),
}
: undefined;
}
@@ -431,7 +450,7 @@ function quoteCheck(
return {
name,
status: 'PASS',
- detail: `ERC-8409 quotes (experimental) - issuer=${issuer}${local === undefined ? ' as the gateway publishes it (viem could not be loaded to check it against the local key)' : ''}, requestScheme=${quote.requestScheme}, extension=${quote.extension}`,
+ detail: `ERC-8409 quotes (${QUOTE_STATUS}) - issuer=${issuer}${local === undefined ? ' as the gateway publishes it (viem could not be loaded to check it against the local key)' : ''}, requestScheme=${quote.requestScheme}, extension=${quote.extension}`,
};
}
@@ -443,13 +462,17 @@ export async function paymentChecks(
chainDeploy = false,
// Load this optional peer only when local x402 quote signing is enabled
loadAccounts: LoadViemAccounts = () => import('viem/accounts'),
+ // Why the well-known document was not obtained; absent after a response
+ liveCause?: Undetermined,
): Promise {
const checks: DoctorCheck[] = [];
// Suggest the repository deployment script only when the caller found it
const stale = `; the gateway may be running against an older deployment - restart it${chainDeploy ? ' or re-run chain:deploy' : ''}`;
// 6. Payments
const x402 = config?.payments.x402;
- if (x402 === undefined || !x402.enabled) {
+ if (config === undefined) {
+ checks.push({ name: 'Payments', status: 'INFO', ...SKIPPED_CONFIG_INVALID });
+ } else if (x402 === undefined || !x402.enabled) {
checks.push({ name: 'Payments', status: 'INFO', detail: 'x402 not configured' });
} else {
const options = x402.options ?? [x402];
@@ -497,6 +520,7 @@ export async function paymentChecks(
name: 'Payments',
status: 'INFO',
detail: `${summary} (gateway's live settlement config could not be verified)`,
+ ...undeterminedField(liveCause),
});
} else {
const configured: RailTerms = {
@@ -519,7 +543,7 @@ export async function paymentChecks(
? { name: 'Payments', status: 'PASS', detail: summary }
: { name: 'Payments', status: 'FAIL', detail: `${mismatch}${stale}` },
);
- const offerHealth = offerHealthCheck(live, named);
+ const offerHealth = offerHealthCheck(live, named, 'Payments (offers)');
if (offerHealth !== undefined) checks.push(offerHealth);
}
const quotes = quoteCheck(
@@ -531,6 +555,7 @@ export async function paymentChecks(
wellKnown?.ok ? wellKnown.body : undefined,
gatewayUrl,
stale,
+ liveCause,
);
if (quotes !== undefined) checks.push(quotes);
if (mode === 'mainnet') {
@@ -546,7 +571,9 @@ export async function paymentChecks(
}
}
const mpp = config?.payments.mpp;
- if (mpp === undefined || !mpp.enabled) {
+ if (config === undefined) {
+ checks.push({ name: 'Payments (MPP)', status: 'INFO', ...SKIPPED_CONFIG_INVALID });
+ } else if (mpp === undefined || !mpp.enabled) {
checks.push({ name: 'Payments (MPP)', status: 'INFO', detail: 'MPP not configured' });
} else {
const { mode, where, via } = describeSettlement(mpp.network, mpp.facilitator);
@@ -582,6 +609,7 @@ export async function paymentChecks(
name: 'Payments (MPP)',
status: 'INFO',
detail: `${summary} (live MPP settlement config unavailable for comparison)`,
+ ...undeterminedField(liveCause),
});
} else {
const mismatch = findRailMismatch(configured, live, 'recipient');
@@ -590,6 +618,12 @@ export async function paymentChecks(
? { name: 'Payments (MPP)', status: 'PASS', detail: summary }
: { name: 'Payments (MPP)', status: 'FAIL', detail: `${mismatch}${stale}` },
);
+ const offerHealth = offerHealthCheck(
+ live,
+ (network) => `${findX402Network(network)?.displayName ?? 'unknown network'} (${network})`,
+ 'Payments (MPP offers)',
+ );
+ if (offerHealth !== undefined) checks.push(offerHealth);
}
if (mode === 'mainnet') {
checks.push(
diff --git a/src/cli/commands/doctor/protocols.ts b/src/cli/commands/doctor/protocols.ts
index 790ba6d..6f533e0 100644
--- a/src/cli/commands/doctor/protocols.ts
+++ b/src/cli/commands/doctor/protocols.ts
@@ -1,22 +1,30 @@
// Protocol checks: what is enabled, and the A2A and ACP specifics
-// Narrow modules, not the protocol barrels: the CLI must pull in no protocol SDK
+// Read protocol constants and support metadata directly to keep protocol SDKs
+// out of the static CLI imports
import {
A2A_AGENT_CARD_PATH,
A2A_PROTOCOL_BINDING,
A2A_PROTOCOL_VERSION,
A2A_SPEC_VERSION,
} from '../../../protocols/a2a/constants';
-import { A2A_UNSUPPORTED } from '../../../protocols/a2a/descriptor';
import {
ACP_API_VERSION,
ACP_SPEC_VERSION,
ACP_WELL_KNOWN_PATH,
} from '../../../protocols/acp/constants';
-import { ACP_UNSUPPORTED } from '../../../protocols/acp/descriptor';
+import a2aRecord from '../../../support/a2a.json' with { type: 'json' };
+import acpRecord from '../../../support/acp.json' with { type: 'json' };
+import { exclusionNames } from '../../../support/claims';
import type { GatewayConfig } from '../../lib/config-client';
import { type LegacyState, legacyStoreCheck } from './storage';
-import type { DoctorCheck, WellKnownResult } from './types';
+import {
+ type DoctorCheck,
+ SKIPPED_CONFIG_INVALID,
+ type Undetermined,
+ undeterminedField,
+ type WellKnownResult,
+} from './types';
/**
* The resource mapped to each checkout operation, re-checked against the rules
@@ -62,13 +70,23 @@ export function protocolChecks(
config: GatewayConfig | undefined,
wellKnown: WellKnownResult | undefined,
legacy: LegacyState,
+ // Why the well-known document was not obtained; absent after a response
+ liveCause?: Undetermined,
): DoctorCheck[] {
const checks: DoctorCheck[] = [];
// 5. Protocols
if (config === undefined) {
- checks.push({ name: 'Protocols', status: 'WARN', detail: 'skipped: config invalid' });
+ checks.push({ name: 'Protocols', status: 'WARN', ...SKIPPED_CONFIG_INVALID });
} else if (wellKnown === undefined || !wellKnown.ok) {
- checks.push({ name: 'Protocols', status: 'FAIL', detail: 'well-known document unreachable' });
+ checks.push({
+ name: 'Protocols',
+ status: 'FAIL',
+ detail:
+ wellKnown === undefined || wellKnown.status === 0
+ ? 'well-known document unreachable'
+ : `well-known document unavailable (HTTP ${wellKnown.status})`,
+ ...undeterminedField(liveCause),
+ });
} else {
const mcpMountPath = config.protocols.mcp.enabled ? config.protocols.mcp.mountPath : undefined;
const a2aMountPath = config.protocols.a2a.enabled ? config.protocols.a2a.mountPath : undefined;
@@ -82,21 +100,21 @@ export function protocolChecks(
// 5b. A2A specifics, from the pins rather than the live gateway. The spec
// revision and the negotiation version look alike, so each is named.
if (config === undefined) {
- checks.push({ name: 'A2A', status: 'WARN', detail: 'skipped: config invalid' });
+ checks.push({ name: 'A2A', status: 'WARN', ...SKIPPED_CONFIG_INVALID });
} else if (!config.protocols.a2a.enabled) {
checks.push({ name: 'A2A', status: 'INFO', detail: 'disabled' });
} else {
checks.push({
name: 'A2A',
status: 'PASS',
- detail: `experimental · spec ${A2A_SPEC_VERSION} · protocol ${A2A_PROTOCOL_VERSION} · binding ${A2A_PROTOCOL_BINDING} · mount ${config.protocols.a2a.mountPath} · card ${A2A_AGENT_CARD_PATH}`,
+ detail: `${a2aRecord.status} · spec ${A2A_SPEC_VERSION} · protocol ${A2A_PROTOCOL_VERSION} · binding ${A2A_PROTOCOL_BINDING} · mount ${config.protocols.a2a.mountPath} · card ${A2A_AGENT_CARD_PATH}`,
});
// Listed in full, as are ACP's and AP2's below: a count does not tell an
// operator whether the one feature their client needs is missing
checks.push({
name: 'A2A unsupported',
status: 'INFO',
- detail: A2A_UNSUPPORTED.join(', '),
+ detail: exclusionNames(a2aRecord).join(', '),
});
}
@@ -104,7 +122,7 @@ export function protocolChecks(
// the bearer token, the idempotency path and the operation mapping. This
// report prints the path and the mapping, never the token.
if (config === undefined) {
- checks.push({ name: 'ACP', status: 'WARN', detail: 'skipped: config invalid' });
+ checks.push({ name: 'ACP', status: 'WARN', ...SKIPPED_CONFIG_INVALID });
} else if (!config.protocols.acp.enabled) {
checks.push({ name: 'ACP', status: 'INFO', detail: 'disabled' });
} else {
@@ -112,7 +130,7 @@ export function protocolChecks(
checks.push({
name: 'ACP',
status: 'PASS',
- detail: `experimental · spec ${ACP_SPEC_VERSION} · API-Version ${ACP_API_VERSION} · service checkout · mount ${acp.mountPath} · discovery ${ACP_WELL_KNOWN_PATH}`,
+ detail: `${acpRecord.status} · spec ${ACP_SPEC_VERSION} · API-Version ${ACP_API_VERSION} · service checkout · mount ${acp.mountPath} · discovery ${ACP_WELL_KNOWN_PATH}`,
});
// Whether a token is configured and its length, never the token. Config
@@ -138,7 +156,7 @@ export function protocolChecks(
checks.push({
name: 'ACP unsupported',
status: 'INFO',
- detail: ACP_UNSUPPORTED.join(', '),
+ detail: exclusionNames(acpRecord).join(', '),
});
}
return checks;
diff --git a/src/cli/commands/doctor/registry.ts b/src/cli/commands/doctor/registry.ts
new file mode 100644
index 0000000..0522fb8
--- /dev/null
+++ b/src/cli/commands/doctor/registry.ts
@@ -0,0 +1,104 @@
+// MCP Registry: the live listing of `protocols.mcp.registry.name`, checked with --registry
+import { isRecord } from '../../../core/is-record';
+import type { GatewayConfig } from '../../lib/config-client';
+import { type FetchLike, fetchJson } from '../../lib/http';
+import { type ServerJson, serverJson } from '../../lib/mcp-registry';
+import { type DoctorCheck, SKIPPED_CONFIG_INVALID } from './types';
+
+/** The registry `doctor --registry` reads */
+export const MCP_REGISTRY_URL = 'https://registry.modelcontextprotocol.io';
+
+const NAME = 'MCP Registry';
+// Allow more time for the public registry than for gateway checks
+const REGISTRY_TIMEOUT_MS = 5000;
+const OFFICIAL_META = 'io.modelcontextprotocol.registry/official';
+
+/**
+ * Compares the configured name's latest listing with `export mcp-registry`
+ * output. The request sends only the name. Listing and request problems produce
+ * WARN because they do not establish deployment health. Treat the answer as
+ * untrusted: report differing field names and known lifecycle statuses without
+ * echoing arbitrary registry values or request error messages.
+ */
+export async function registryCheck(
+ config: GatewayConfig | undefined,
+ fetchImpl: FetchLike,
+): Promise {
+ if (config === undefined) return { name: NAME, status: 'WARN', ...SKIPPED_CONFIG_INVALID };
+ if (config.protocols.mcp.registry === undefined) {
+ return { name: NAME, status: 'INFO', detail: 'protocols.mcp.registry not configured' };
+ }
+ const built = serverJson(config);
+ if ('problems' in built) {
+ return {
+ name: NAME,
+ status: 'WARN',
+ detail: built.problems.map((problem) => `${problem.key} ${problem.message}`).join('; '),
+ };
+ }
+ const local = built.document;
+ // The registry answers 404 for a deleted listing unless asked to include it
+ const answer = await fetchJson(
+ fetchImpl,
+ `${MCP_REGISTRY_URL}/v0.1/servers/${encodeURIComponent(local.name)}/versions/latest?include_deleted=true`,
+ REGISTRY_TIMEOUT_MS,
+ );
+ // An error message can carry text from the far end, such as certificate names
+ if (answer.status === 0) {
+ return answer.noAnswer === true
+ ? {
+ name: NAME,
+ status: 'WARN',
+ detail: 'no answer from the registry',
+ undetermined: 'unreachable',
+ }
+ : { name: NAME, status: 'WARN', detail: 'the registry request failed' };
+ }
+ if (answer.status === 404) {
+ return { name: NAME, status: 'WARN', detail: `${local.name} is not listed` };
+ }
+ if (!answer.ok || !isRecord(answer.body) || !isRecord(answer.body['server'])) {
+ return {
+ name: NAME,
+ status: 'WARN',
+ detail: answer.ok
+ ? 'the registry answer is not a server listing'
+ : `the registry answered HTTP ${answer.status}`,
+ };
+ }
+
+ const problems = [
+ ...lifecycle(answer.body['_meta']),
+ ...differences(answer.body['server'], local),
+ ];
+ return problems.length === 0
+ ? {
+ name: NAME,
+ status: 'PASS',
+ detail: `${local.name} ${local.version} is listed as configured`,
+ }
+ : { name: NAME, status: 'WARN', detail: `${local.name}: ${problems.join('; ')}` };
+}
+
+// Only the registry's known status words reach the output
+function lifecycle(meta: unknown): string[] {
+ const official = isRecord(meta) ? meta[OFFICIAL_META] : undefined;
+ const status = isRecord(official) ? official['status'] : undefined;
+ if (status === 'active') return [];
+ if (status === 'deprecated' || status === 'deleted') return [`listing is ${status}`];
+ return ['listing has no known status'];
+}
+
+function differences(listed: Record, local: ServerJson): string[] {
+ const fields = (['name', 'version', 'description'] as const).filter(
+ (field) => listed[field] !== local[field],
+ );
+ const remotes = listed['remotes'];
+ const remote = Array.isArray(remotes) && remotes.length === 1 ? remotes[0] : undefined;
+ const sameRemote =
+ isRecord(remote) &&
+ remote['type'] === local.remotes[0].type &&
+ remote['url'] === local.remotes[0].url;
+ const differing = sameRemote ? fields : [...fields, 'remotes'];
+ return differing.length > 0 ? [`listing differs from config in ${differing.join(', ')}`] : [];
+}
diff --git a/src/cli/commands/doctor/report.ts b/src/cli/commands/doctor/report.ts
index f192026..879878c 100644
--- a/src/cli/commands/doctor/report.ts
+++ b/src/cli/commands/doctor/report.ts
@@ -23,7 +23,8 @@ export function printDoctorReport(report: DoctorReport, io: Io, json: boolean):
}
for (const check of report.checks) {
const label = statusColor(check.status, check.status.padEnd(5));
- io.stdout(`${label} ${check.name.padEnd(20)} ${check.detail}`);
+ const mark = check.undetermined !== undefined ? ` [not determined: ${check.undetermined}]` : '';
+ io.stdout(`${label} ${check.name.padEnd(20)} ${check.detail}${mark}`);
}
io.stdout('');
io.stdout(`Score: ${report.score.passed}/${report.score.total} checks passed`);
diff --git a/src/cli/commands/doctor/secrets.ts b/src/cli/commands/doctor/secrets.ts
new file mode 100644
index 0000000..d2e9c3b
--- /dev/null
+++ b/src/cli/commands/doctor/secrets.ts
@@ -0,0 +1,42 @@
+// Secrets: every `${VAR}` placeholder in the raw config, by name and never by value
+
+import { listEnvPlaceholders } from '../../../config/env';
+import type { ConfigFileReader } from '../../lib/config-client';
+import type { DoctorCheck } from './types';
+
+/**
+ * List all missing config variables; config loading stops at the first.
+ * Return names only, since values and defaults may contain credentials.
+ */
+export async function secretsCheck(
+ read: ConfigFileReader,
+ path: string | undefined,
+ env: NodeJS.ProcessEnv,
+): Promise {
+ let raw: unknown;
+ try {
+ raw = await read({ ...(path !== undefined ? { path } : {}), env });
+ } catch {
+ // The Config check reports why
+ return {
+ name: 'Secrets',
+ status: 'WARN',
+ detail: 'skipped: config file unreadable',
+ undetermined: 'skipped',
+ };
+ }
+ const { missing, set, defaulted } = listEnvPlaceholders(raw, env);
+ const groups = [
+ ...(missing.length > 0 ? [`${missing.length} missing (${missing.join(', ')})`] : []),
+ ...(set.length > 0 ? [`${set.length} set (${set.join(', ')})`] : []),
+ ...(defaulted.length > 0 ? [`${defaulted.length} defaulted (${defaulted.join(', ')})`] : []),
+ ];
+ if (groups.length === 0) {
+ return { name: 'Secrets', status: 'INFO', detail: 'config reads no environment variable' };
+ }
+ return {
+ name: 'Secrets',
+ status: missing.length > 0 ? 'FAIL' : 'PASS',
+ detail: groups.join('; '),
+ };
+}
diff --git a/src/cli/commands/doctor/storage.ts b/src/cli/commands/doctor/storage.ts
index 65f5855..2a4bde3 100644
--- a/src/cli/commands/doctor/storage.ts
+++ b/src/cli/commands/doctor/storage.ts
@@ -10,7 +10,12 @@ import {
type SqliteReceiptStoreSummary,
} from '../../../storage/receipts';
import type { GatewayConfig } from '../../lib/config-client';
-import type { CheckStatus, DoctorCheck, DoctorStore } from './types';
+import {
+ type CheckStatus,
+ type DoctorCheck,
+ type DoctorStore,
+ SKIPPED_CONFIG_INVALID,
+} from './types';
// Whether an existing file is writable, without creating one
function isWritableFile(path: string): boolean {
@@ -141,7 +146,7 @@ export async function storageChecks(
// 7. Storage
if (config === undefined) {
return {
- checks: [{ name: 'Storage', status: 'WARN', detail: 'skipped: config invalid' }],
+ checks: [{ name: 'Storage', status: 'WARN', ...SKIPPED_CONFIG_INVALID }],
legacy: undefined,
};
}
diff --git a/src/cli/commands/doctor/types.ts b/src/cli/commands/doctor/types.ts
index dee5636..e609604 100644
--- a/src/cli/commands/doctor/types.ts
+++ b/src/cli/commands/doctor/types.ts
@@ -1,17 +1,26 @@
// The report doctor builds, and what a caller can inject
import type { ReceiptStore } from '../../../core';
import type { SqliteReceiptStore } from '../../../storage/receipts';
-import type { ConfigLoader } from '../../lib/config-client';
+import type { ConfigFileReader, ConfigLoader } from '../../lib/config-client';
import type { FetchJsonResult, FetchLike } from '../../lib/http';
import type { ManifestEnvFill } from '../../lib/manifest-env';
import type { LoadViemAccounts } from './payments';
export type CheckStatus = 'PASS' | 'WARN' | 'FAIL' | 'INFO';
+/**
+ * Why a check could not reach a verdict: `unreachable` for a recognized
+ * transport failure, or `skipped` for a failed prerequisite. The marker does
+ * not affect the check's status, the score or the exit code.
+ */
+export type Undetermined = 'unreachable' | 'skipped';
+
export interface DoctorCheck {
readonly name: string;
readonly status: CheckStatus;
readonly detail: string;
+ /** Absent on a result that is a verdict */
+ readonly undetermined?: Undetermined;
}
export interface DoctorReport {
@@ -23,6 +32,8 @@ export interface DoctorReport {
export interface DoctorOptions {
readonly configPath?: string;
readonly gatewayUrl?: string;
+ /** Experimental. Adds a Registry check; queries the public registry when config yields a listing */
+ readonly registry?: boolean;
}
/** A receipt store for doctor to read; `summary` adds the journal and import checks */
@@ -31,6 +42,12 @@ export type DoctorStore = ReceiptStore & { readonly summary?: SqliteReceiptStore
export interface DoctorDeps {
readonly fetchImpl?: FetchLike;
readonly loadConfig?: ConfigLoader;
+ /**
+ * Reads raw config for the Secrets check. The default reader is used only
+ * when neither this reader nor `loadConfig` is injected; an injected loader
+ * without a reader skips the check.
+ */
+ readonly readConfigFile?: ConfigFileReader;
readonly createStore?: (path: string) => DoctorStore;
readonly fillEnvFromManifest?: (env: NodeJS.ProcessEnv) => ManifestEnvFill;
readonly hasChainDeployScript?: () => boolean;
@@ -38,3 +55,16 @@ export interface DoctorDeps {
}
export type WellKnownResult = FetchJsonResult>;
+
+/** Returns `{ undetermined }` when a reason is given, otherwise an empty object */
+export function undeterminedField(reason: Undetermined | undefined): {
+ readonly undetermined?: Undetermined;
+} {
+ return reason !== undefined ? { undetermined: reason } : {};
+}
+
+/** The fields of a check that did not run because config failed to load */
+export const SKIPPED_CONFIG_INVALID = {
+ detail: 'skipped: config invalid',
+ undetermined: 'skipped',
+} as const;
diff --git a/src/cli/commands/export-mcp-registry.ts b/src/cli/commands/export-mcp-registry.ts
new file mode 100644
index 0000000..e2190f4
--- /dev/null
+++ b/src/cli/commands/export-mcp-registry.ts
@@ -0,0 +1,58 @@
+// `agent-commerce export mcp-registry`: write `server.json` for the MCP Registry from config
+import { existsSync } from 'node:fs';
+import { type ConfigLoader, type GatewayConfig, loadConfigDynamic } from '../lib/config-client';
+import type { Io } from '../lib/io';
+import { serverJson } from '../lib/mcp-registry';
+import { writeAtomically } from '../lib/write-file';
+import { formatConfigError } from './validate';
+
+export interface ExportMcpRegistryOptions {
+ readonly configPath?: string;
+ readonly output: string;
+ readonly force?: boolean;
+}
+
+export interface ExportMcpRegistryDeps {
+ readonly loadConfig?: ConfigLoader;
+}
+
+/** Exports a listing after config loading and listing checks succeed */
+export async function runExportMcpRegistry(
+ options: ExportMcpRegistryOptions,
+ io: Io,
+ deps: ExportMcpRegistryDeps = {},
+): Promise {
+ const { output } = options;
+ if (existsSync(output) && options.force !== true) {
+ io.stderr(`FAIL ${output} already exists. Re-run with --force to overwrite.`);
+ return 1;
+ }
+
+ let config: GatewayConfig;
+ try {
+ config = await (deps.loadConfig ?? loadConfigDynamic)(
+ options.configPath !== undefined ? { path: options.configPath } : {},
+ );
+ } catch (error) {
+ io.stderr(formatConfigError(error, false, false));
+ return 1;
+ }
+
+ const result = serverJson(config);
+ if ('problems' in result) {
+ for (const problem of result.problems) io.stderr(`FAIL ${problem.key} ${problem.message}`);
+ return 1;
+ }
+
+ try {
+ await writeAtomically(output, `${JSON.stringify(result.document, null, 2)}\n`);
+ } catch (error) {
+ io.stderr(
+ `FAIL ${output} could not be written: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ return 1;
+ }
+ io.stdout(`Wrote ${output} for ${result.document.name} ${result.document.version}.`);
+ io.stdout('Publish it with mcp-publisher after verifying the namespace.');
+ return 0;
+}
diff --git a/src/cli/commands/import-openapi.ts b/src/cli/commands/import-openapi.ts
index 93d2f43..cbde7eb 100644
--- a/src/cli/commands/import-openapi.ts
+++ b/src/cli/commands/import-openapi.ts
@@ -6,8 +6,7 @@
* `--output config.yaml --force` replaces that file rather than merging.
*/
import { existsSync } from 'node:fs';
-import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
-import { basename, dirname, extname, resolve } from 'node:path';
+import { basename, extname } from 'node:path';
import { PROTOCOL_NAMES } from '../../core';
import {
buildResourceDrafts,
@@ -17,6 +16,7 @@ import {
renderResourcesYaml,
} from '../../openapi';
import type { Io } from '../lib/io';
+import { writeAtomically } from '../lib/write-file';
export interface ImportOpenApiOptions {
readonly source: string;
@@ -103,7 +103,7 @@ export async function runImportOpenApi(
const wrote = failures.length === 0;
if (wrote) {
try {
- await writeAtomically(outputPath, renderResourcesYaml(result), deps);
+ await (deps.writeFile ?? writeAtomically)(outputPath, renderResourcesYaml(result));
} catch (error) {
io.stderr(`FAIL ${outputPath} could not be written: ${describe(error)}`);
return 1;
@@ -164,30 +164,6 @@ function buildPolicy(options: ImportOpenApiOptions): ImportPolicy | string {
return policy;
}
-async function writeAtomically(
- outputPath: string,
- content: string,
- deps: ImportOpenApiDeps,
-): Promise {
- if (deps.writeFile !== undefined) {
- await deps.writeFile(outputPath, content);
- return;
- }
- // Temp sibling then rename: a crash or a full disk must not leave a
- // half-written file where a complete one used to be
- const target = resolve(outputPath);
- const temporary = `${target}.${process.pid}.tmp`;
- try {
- // Like `init --output`: a missing output directory is created, not an error
- await mkdir(dirname(target), { recursive: true });
- await writeFile(temporary, content, 'utf8');
- await rename(temporary, target);
- } catch (error) {
- await rm(temporary, { force: true });
- throw error;
- }
-}
-
function printSummary(
result: ImportResult,
context: { outputPath: string; wrote: boolean; policy: ImportPolicy },
diff --git a/src/cli/lib/config-client.ts b/src/cli/lib/config-client.ts
index 9030882..aa2ff9e 100644
--- a/src/cli/lib/config-client.ts
+++ b/src/cli/lib/config-client.ts
@@ -16,6 +16,9 @@ export interface LoadConfigOptions {
export type ConfigLoader = (options?: LoadConfigOptions) => Promise;
+/** Reads the loader's raw config before environment substitution and validation */
+export type ConfigFileReader = (options?: LoadConfigOptions) => Promise;
+
/** Validates an already-built raw config object, without touching the disk */
export type ConfigParser = (raw: unknown, env?: NodeJS.ProcessEnv) => Promise;
@@ -34,6 +37,10 @@ export async function loadConfigDynamic(options: LoadConfigOptions = {}): Promis
return (await importConfig()).loadConfig(options);
}
+export async function readConfigFileDynamic(options: LoadConfigOptions = {}): Promise {
+ return (await importConfig()).readConfigFile(options);
+}
+
/** Validates a raw config object in memory; `init` uses it to validate before writing */
export async function parseConfigDynamic(
raw: unknown,
diff --git a/src/cli/lib/http.ts b/src/cli/lib/http.ts
index 6b23ff5..584f6bb 100644
--- a/src/cli/lib/http.ts
+++ b/src/cli/lib/http.ts
@@ -1,3 +1,5 @@
+import { gotNoAnswer } from '../../core/no-answer';
+
/**
* Fetch with a timeout, for `doctor`. `fetchImpl` is injected so tests can
* pass a fake `fetch` and never touch the network.
@@ -6,9 +8,12 @@ export type FetchLike = typeof fetch;
export interface FetchJsonResult {
readonly ok: boolean;
+ /** The HTTP status, or 0 when the request threw */
readonly status: number;
readonly body?: T;
readonly error?: string;
+ /** Present when `gotNoAnswer` recognizes a transport failure */
+ readonly noAnswer?: true;
}
export async function fetchJson(
@@ -30,7 +35,16 @@ export async function fetchJson(
return {
ok: false,
status: 0,
- error: err instanceof Error ? err.message : 'unknown fetch error',
+ error: errorText(err),
+ ...(gotNoAnswer(err) ? { noAnswer: true as const } : {}),
};
}
}
+
+// Include a nested cause's message to explain undici's generic "fetch failed"
+function errorText(err: unknown): string {
+ if (!(err instanceof Error)) return 'unknown fetch error';
+ let root = err;
+ for (let depth = 0; depth < 10 && root.cause instanceof Error; depth++) root = root.cause;
+ return root === err ? err.message : `${err.message}: ${root.message}`;
+}
diff --git a/src/cli/lib/mcp-registry.ts b/src/cli/lib/mcp-registry.ts
new file mode 100644
index 0000000..8ab844c
--- /dev/null
+++ b/src/cli/lib/mcp-registry.ts
@@ -0,0 +1,86 @@
+// The MCP Registry listing (`server.json`) for a gateway, built from config alone
+import { publicEndpointUrl } from '../../protocols/http';
+import type { GatewayConfig } from './config-client';
+
+/** The `server.json` schema revision the listing follows */
+export const SERVER_JSON_SCHEMA =
+ 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json';
+
+export interface ServerJson {
+ readonly $schema: typeof SERVER_JSON_SCHEMA;
+ readonly name: string;
+ readonly description: string;
+ readonly version: string;
+ readonly remotes: readonly [{ readonly type: 'streamable-http'; readonly url: string }];
+}
+
+/** Why a listing cannot be written, naming the config key to change */
+export interface RegistryProblem {
+ readonly key: string;
+ readonly message: string;
+}
+
+/**
+ * Builds a listing from validated `config`, or returns the problems found.
+ * Requires MCP to be enabled and registry metadata to be present. The remote
+ * URL joins `merchant.publicBaseUrl` and the MCP mount through
+ * `publicEndpointUrl`, matching the form of an x402 challenge's `resource.url`.
+ * It must use HTTPS and must not name `localhost`, `127.0.0.1` or `*.localhost`.
+ * The name and version come from `protocols.mcp.registry`; `runGateway` also
+ * uses them for MCP `serverInfo`.
+ */
+export function serverJson(
+ config: GatewayConfig,
+): { readonly document: ServerJson } | { readonly problems: readonly RegistryProblem[] } {
+ const { mcp } = config.protocols;
+ const problems: RegistryProblem[] = [];
+ if (!mcp.enabled) {
+ problems.push({
+ key: 'protocols.mcp.enabled',
+ message: 'is false: the listing would name a server that does not run',
+ });
+ }
+ if (mcp.registry === undefined) {
+ problems.push({
+ key: 'protocols.mcp.registry',
+ message: 'is not set: it holds the listing name, version and description',
+ });
+ }
+ const url = remoteUrl(config.merchant.publicBaseUrl, mcp.mountPath);
+ if ('problem' in url) problems.push({ key: 'merchant.publicBaseUrl', message: url.problem });
+
+ if (mcp.registry === undefined || 'problem' in url || problems.length > 0) {
+ return { problems };
+ }
+ return {
+ document: {
+ $schema: SERVER_JSON_SCHEMA,
+ name: mcp.registry.name,
+ description: mcp.registry.description,
+ version: mcp.registry.version,
+ remotes: [{ type: 'streamable-http', url: url.url }],
+ },
+ };
+}
+
+// Check the remote URL against the registry's `IsValidRemoteURL` rules
+function remoteUrl(
+ publicBaseUrl: string,
+ mountPath: string,
+): { readonly url: string } | { readonly problem: string } {
+ let url: string;
+ try {
+ url = publicEndpointUrl(publicBaseUrl, mountPath);
+ } catch {
+ return { problem: 'is not a URL' };
+ }
+ const parsed = new URL(url);
+ if (parsed.protocol !== 'https:') {
+ return { problem: 'must be an https:// URL: the MCP Registry refuses others' };
+ }
+ const host = parsed.hostname;
+ if (host === 'localhost' || host === '127.0.0.1' || host.endsWith('.localhost')) {
+ return { problem: `names ${host}, which the MCP Registry refuses` };
+ }
+ return { url };
+}
diff --git a/src/cli/lib/write-file.ts b/src/cli/lib/write-file.ts
new file mode 100644
index 0000000..e66b716
--- /dev/null
+++ b/src/cli/lib/write-file.ts
@@ -0,0 +1,20 @@
+import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+
+/**
+ * Writes `content` to a temporary sibling, then renames it over `outputPath`.
+ * The destination is replaced only after the write succeeds; a failed write
+ * leaves an existing file intact. Creates missing output directories.
+ */
+export async function writeAtomically(outputPath: string, content: string): Promise {
+ const target = resolve(outputPath);
+ const temporary = `${target}.${process.pid}.tmp`;
+ try {
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(temporary, content, 'utf8');
+ await rename(temporary, target);
+ } catch (error) {
+ await rm(temporary, { force: true });
+ throw error;
+ }
+}
diff --git a/src/cli/program.ts b/src/cli/program.ts
index b15f201..c06326b 100644
--- a/src/cli/program.ts
+++ b/src/cli/program.ts
@@ -4,6 +4,7 @@ import { PROTOCOL_NAMES } from '../core';
import { runBackupCommand } from './commands/backup';
import { runDemo } from './commands/demo';
import { printDoctorReport, runDoctor } from './commands/doctor';
+import { runExportMcpRegistry } from './commands/export-mcp-registry';
import { runImportOpenApi } from './commands/import-openapi';
import { runInit } from './commands/init';
import { runReconcileCommand } from './commands/reconcile';
@@ -28,7 +29,7 @@ export function buildProgram(io: Io = processIo): Command {
program
.name('agent-commerce')
.description(
- 'CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, backup, demo.',
+ 'CLI for the Agent Commerce Gateway: init, import, export, validate, start, doctor, reconcile, backup, demo.',
)
// `--version` prints the CLI version only; the `version` subcommand also
// lists the pinned protocol/SDK versions. Both read `readVersionReport()`,
@@ -106,14 +107,22 @@ export function buildProgram(io: Io = processIo): Command {
'gateway base URL (default: derived from config, else http://localhost:8080)',
)
.option('--json', 'emit machine-readable JSON instead of a formatted report', false)
- .action(async (opts: { config?: string; gateway?: string; json?: boolean }) => {
- const report = await runDoctor({
- ...(opts.config !== undefined ? { configPath: opts.config } : {}),
- ...(opts.gateway !== undefined ? { gatewayUrl: opts.gateway } : {}),
- });
- printDoctorReport(report, io, opts.json === true);
- process.exitCode = report.exitCode;
- });
+ .option(
+ '--registry',
+ 'also compare the MCP Registry listing named in protocols.mcp.registry with config (calls registry.modelcontextprotocol.io)',
+ false,
+ )
+ .action(
+ async (opts: { config?: string; gateway?: string; json?: boolean; registry: boolean }) => {
+ const report = await runDoctor({
+ ...(opts.config !== undefined ? { configPath: opts.config } : {}),
+ ...(opts.gateway !== undefined ? { gatewayUrl: opts.gateway } : {}),
+ registry: opts.registry,
+ });
+ printDoctorReport(report, io, opts.json === true);
+ process.exitCode = report.exitCode;
+ },
+ );
program
.command('reconcile')
@@ -287,6 +296,31 @@ export function buildProgram(io: Io = processIo): Command {
},
);
+ // Group catalog exports under `export`, mirroring `import`
+ const exportCommand = program
+ .command('export')
+ .description('Generate catalog listings for the gateway from config.');
+
+ exportCommand
+ .command('mcp-registry')
+ .description(
+ 'Write server.json for the MCP Registry from protocols.mcp.registry (experimental).',
+ )
+ .option('--config ', `path to ${DEFAULT_CONFIG_FILENAME}`)
+ .option('--env-file ', ENV_FILE_HELP)
+ .option('--output ', 'output path', 'server.json')
+ .option('--force', 'overwrite an existing output file', false)
+ .action(async (opts: { config?: string; output: string; force: boolean }) => {
+ process.exitCode = await runExportMcpRegistry(
+ {
+ ...(opts.config !== undefined ? { configPath: opts.config } : {}),
+ output: opts.output,
+ force: opts.force,
+ },
+ io,
+ );
+ });
+
program
.command('demo')
.description(
diff --git a/src/config/env.ts b/src/config/env.ts
index ed6cde7..9728a49 100644
--- a/src/config/env.ts
+++ b/src/config/env.ts
@@ -47,6 +47,50 @@ export function substituteEnv(value: unknown, env: NodeJS.ProcessEnv, path = '$'
return value;
}
+/** Sorted placeholder names from raw config, grouped by how they resolve in the environment */
+export interface EnvPlaceholders {
+ /** `${VAR}` with `VAR` unset; config loading stops at the first missing variable */
+ readonly missing: readonly string[];
+ /** `${VAR:-default}` with `VAR` unset or empty */
+ readonly defaulted: readonly string[];
+ readonly set: readonly string[];
+}
+
+/**
+ * Collect recognized placeholder names without validating template syntax;
+ * config loading reports unsupported templates. Each name appears once, using
+ * the most severe state: missing, then defaulted, then set. Return names only,
+ * never values or defaults.
+ */
+export function listEnvPlaceholders(raw: unknown, env: NodeJS.ProcessEnv): EnvPlaceholders {
+ // 0 set, 1 defaulted, 2 missing: a higher number is worse
+ const worst = new Map();
+ const visit = (value: unknown): void => {
+ if (typeof value === 'string') {
+ for (const [, name = '', hasDefault] of value.matchAll(PLACEHOLDER_PATTERN)) {
+ const envValue = env[name];
+ const state =
+ hasDefault !== undefined
+ ? envValue === undefined || envValue === ''
+ ? 1
+ : 0
+ : envValue === undefined
+ ? 2
+ : 0;
+ worst.set(name, Math.max(state, worst.get(name) ?? 0));
+ }
+ } else if (Array.isArray(value)) {
+ value.forEach(visit);
+ } else if (isRecord(value)) {
+ Object.values(value).forEach(visit);
+ }
+ };
+ visit(raw);
+ const names = [...worst.keys()].sort();
+ const named = (state: number) => names.filter((name) => worst.get(name) === state);
+ return { missing: named(2), defaulted: named(1), set: named(0) };
+}
+
function substituteString(value: string, env: NodeJS.ProcessEnv, path: string): string {
assertTemplateIsSupported(value, path);
return substituteOnce(value, env, path);
diff --git a/src/config/index.ts b/src/config/index.ts
index da4bf04..622595a 100644
--- a/src/config/index.ts
+++ b/src/config/index.ts
@@ -1,7 +1,8 @@
// `config.yaml` schema, loader and environment substitution
-export { substituteEnv } from './env';
+export type { EnvPlaceholders } from './env';
+export { listEnvPlaceholders, substituteEnv } from './env';
export type { LoadConfigOptions } from './load';
-export { loadConfig } from './load';
+export { loadConfig, readConfigFile } from './load';
export type { GatewayConfig } from './schema';
export { parseConfig } from './schema';
diff --git a/src/config/load.ts b/src/config/load.ts
index fc773b1..90019df 100644
--- a/src/config/load.ts
+++ b/src/config/load.ts
@@ -18,6 +18,14 @@ export interface LoadConfigOptions {
}
export async function loadConfig(options: LoadConfigOptions = {}): Promise {
+ return parseConfig(await readConfigFile(options), options.env ?? process.env);
+}
+
+/**
+ * Read the same file as `loadConfig`, returning parsed YAML before environment
+ * substitution and config validation. File and YAML errors match `loadConfig`.
+ */
+export async function readConfigFile(options: LoadConfigOptions = {}): Promise {
const env = options.env ?? process.env;
const cwd = options.cwd ?? process.cwd();
const configPath = resolveConfigPath(options.path, env, cwd);
@@ -32,9 +40,8 @@ export async function loadConfig(options: LoadConfigOptions = {}): Promise
+ new RegExp(source.replaceAll(String.raw`\s`, String.raw`[\t\n\f\r ]`));
+const RANGES = [
+ // `comparatorRangeRe`, `hyphenRangeRe`, `orRangeRe`
+ String.raw`^\s*(?:\^|~|>=|<=|>|<|=)\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*$`,
+ String.raw`^\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s-\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*$`,
+ String.raw`^\s*(?:v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*)(?:\|\|\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*)+$`,
+].map(re2);
+// `dottedVersionLikeRe`
+const DOTTED_VERSION_LIKE = re2(
+ String.raw`^\s*(?:v?\d+|x|X|\*)(?:\.(?:\d+|x|X|\*)){1,2}(?:-[0-9A-Za-z.-]+)?\s*$`,
+);
+
+// Match `looksLikeVersionRange`: a dotted version containing `x`, `X` or `*`
+// counts as a range, even in the prerelease part of `1.0.0-next.1`
+function looksLikeVersionRange(version: string): boolean {
+ // Go's strings.TrimSpace trims Unicode White_Space
+ const trimmed = version.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, '');
+ if (trimmed === '') return false;
+ if (RANGES.some((range) => range.test(trimmed))) return true;
+ return DOTTED_VERSION_LIKE.test(trimmed) && /[xX*]/.test(trimmed);
+}
+
+// Lengths in code points, as JSON Schema and the registry count them
+const codePoints = (min: number, max: number) =>
+ z.string().refine(
+ (value) => {
+ const length = [...value].length;
+ return length >= min && length <= max;
+ },
+ { message: `must be ${min} to ${max} characters` },
+ );
+
+export const McpRegistrySchema = z
+ .object({
+ name: z.string().max(200).regex(SERVER_NAME, {
+ message:
+ 'must be a namespace and a name joined by one "/", such as io.github.acme/weather. Each side has at least 2 characters and starts and ends with a letter or digit; the namespace may also hold "." and "-", the name ".", "_" and "-".',
+ }),
+ version: codePoints(1, 255)
+ .refine((value) => value !== 'latest', {
+ message: 'must not be "latest", which the MCP Registry reserves',
+ })
+ .refine((value) => !looksLikeVersionRange(value), {
+ message:
+ 'must name one version, not a range such as ^1.2.3, 1.x or 1.0 - 2.0. The MCP Registry also reads a dotted version holding x, X or * anywhere, such as 1.0.0-next.1, as a range.',
+ }),
+ description: codePoints(1, 100),
+ })
+ .strict();
diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts
index 87a89bd..0cacdae 100644
--- a/src/config/schema/normalize.ts
+++ b/src/config/schema/normalize.ts
@@ -1,10 +1,13 @@
// The business-rule pass: coerces leaves and checks cross-references across sections
+import type { CommerceResource } from '../../core';
import { CommerceError } from '../../core';
+import { bazaarMetadata } from '../../payments/x402/provider/bazaar';
+import { publicEndpointUrl } from '../../protocols/http';
import { normalizeAcp, validateAcpCheckoutMapping } from './acp';
import { normalizeAp2, validateLegacyStoresIsolated } from './ap2';
import { normalizeMpp } from './mpp';
import { isHttpUrl, type RawConfig, SUPPORTED_CONFIG_VERSION } from './raw';
-import { normalizeResource } from './resources';
+import { normalizeResource, servingRailOf } from './resources';
import type { GatewayConfig, NormalizedProtocols } from './types';
import { toBoolean, toNumber } from './values';
import { normalizeX402 } from './x402';
@@ -18,6 +21,7 @@ export function normalize(raw: RawConfig): GatewayConfig {
mcp: {
enabled: toBoolean(raw.protocols.mcp.enabled, 'protocols.mcp.enabled'),
mountPath: raw.protocols.mcp.mountPath,
+ ...(raw.protocols.mcp.registry !== undefined ? { registry: raw.protocols.mcp.registry } : {}),
},
a2a: {
enabled: toBoolean(raw.protocols.a2a?.enabled ?? false, 'protocols.a2a.enabled'),
@@ -59,12 +63,28 @@ export function normalize(raw: RawConfig): GatewayConfig {
return mimeType !== undefined ? [[resource.id, mimeType]] : [];
}),
);
+ // Build URL mappings and metadata for resources whose serving rail is x402
+ const rails = { x402: x402?.enabled === true, mpp: mpp?.enabled === true };
+ const railOf = (resource: CommerceResource) => servingRailOf(resource.paymentMethods, rails);
+ const onX402 = resources.filter((resource) => railOf(resource) === 'x402');
+ const publicUrl = raw.payments.x402?.publicResourceUrl;
+ const resourceUrls =
+ publicUrl !== undefined && toBoolean(publicUrl, 'payments.x402.publicResourceUrl')
+ ? publicResourceUrls(raw.merchant.publicBaseUrl, protocols, onX402)
+ : undefined;
+ const bazaarRaw = raw.payments.x402?.bazaar;
+ const resourceBazaar =
+ bazaarRaw !== undefined && toBoolean(bazaarRaw.enabled, 'payments.x402.bazaar.enabled')
+ ? bazaarExtensions(resourceUrls, resources, mimeTypes, railOf)
+ : undefined;
const x402WithFlows =
x402 !== undefined
? {
...x402,
...flowOverrides('x402'),
...(Object.keys(mimeTypes).length > 0 ? { resourceMimeTypes: mimeTypes } : {}),
+ ...(resourceUrls !== undefined ? { resourceUrls } : {}),
+ ...(resourceBazaar !== undefined ? { resourceBazaar } : {}),
}
: x402;
const mppWithFlows = mpp !== undefined ? { ...mpp, ...flowOverrides('mpp') } : mpp;
@@ -110,6 +130,78 @@ export function normalize(raw: RawConfig): GatewayConfig {
};
}
+// Build Bazaar metadata for public URLs and report omitted resources or surfaces
+// during config loading. Omitting metadata leaves payment behavior unchanged.
+function bazaarExtensions(
+ resourceUrls: Record>> | undefined,
+ resources: readonly CommerceResource[],
+ mimeTypes: Readonly>,
+ railOf: (resource: CommerceResource) => string | undefined,
+): NonNullable['resourceBazaar'] {
+ if (resourceUrls === undefined) {
+ throw new CommerceError(
+ 'CONFIG_INVALID',
+ 'payments.x402.bazaar.enabled requires payments.x402.publicResourceUrl: true',
+ { details: { path: 'payments.x402.bazaar.enabled' } },
+ );
+ }
+ return Object.fromEntries(
+ resources.flatMap((resource) => {
+ const urls = resourceUrls[resource.id];
+ if (urls === undefined) {
+ const rail = railOf(resource);
+ if (resource.paymentMethods.includes('x402') && rail !== undefined) {
+ console.warn(
+ `[agent-commerce] resource "${resource.id}" gets no Bazaar metadata: the gateway serves it on ${rail}, the first enabled rail in its payments, which issues no x402 challenge. Payment is unaffected.`,
+ );
+ }
+ return [];
+ }
+ const surfaces = (['http', 'mcp'] as const).filter((surface) => urls[surface] !== undefined);
+ const { extensions, omitted } = bazaarMetadata(resource, surfaces, mimeTypes[resource.id]);
+ for (const { surfaces: left, reason } of omitted) {
+ console.warn(
+ `[agent-commerce] resource "${resource.id}" gets no Bazaar metadata on ${left.join(' and ')}: ${reason}. Payment is unaffected.`,
+ );
+ }
+ return Object.keys(extensions).length > 0 ? [[resource.id, extensions]] : [];
+ }),
+ );
+}
+
+// Build public endpoint URLs for the surfaces exposing resources served on
+// x402, which indexers can request, unlike `resource://` identifiers
+function publicResourceUrls(
+ publicBaseUrl: string,
+ protocols: NormalizedProtocols,
+ resources: readonly CommerceResource[],
+): Record>> {
+ if (!isHttpUrl(publicBaseUrl)) {
+ throw new CommerceError(
+ 'CONFIG_INVALID',
+ `payments.x402.publicResourceUrl needs merchant.publicBaseUrl to be an http:// or https:// URL, not ${JSON.stringify(publicBaseUrl)}`,
+ { details: { path: 'merchant.publicBaseUrl' } },
+ );
+ }
+ const path = (surface: 'http' | 'mcp' | 'a2a', id: string) =>
+ surface === 'http'
+ ? `/api/resources/${encodeURIComponent(id)}/invoke`
+ : protocols[surface].mountPath;
+ return Object.fromEntries(
+ resources.map((resource) => [
+ resource.id,
+ Object.fromEntries(
+ (['http', 'mcp', 'a2a'] as const)
+ .filter((surface) => resource.exposedVia.includes(surface))
+ .map((surface) => [
+ surface,
+ publicEndpointUrl(publicBaseUrl, path(surface, resource.id)),
+ ]),
+ ),
+ ]),
+ );
+}
+
// Two enabled mounts may not overlap: each registers a `${mountPath}/*`
// wildcard, so a shared prefix lets one adapter answer for the other. Disabled
// protocols mount nothing and are not compared.
diff --git a/src/config/schema/raw.ts b/src/config/schema/raw.ts
index 9a5a918..090e93c 100644
--- a/src/config/schema/raw.ts
+++ b/src/config/schema/raw.ts
@@ -2,6 +2,7 @@
import { z } from 'zod';
import { X402_PAYMENT_FLOWS } from '../../payments/x402/payment-flow';
import { ACP_WELL_KNOWN_PATH } from '../../protocols/acp/constants';
+import { McpRegistrySchema } from './mcp-registry';
export const SUPPORTED_CONFIG_VERSION = 1;
@@ -163,6 +164,9 @@ const ProtocolsSchema = z
.object({
enabled: BooleanOrString,
mountPath: MountPathSchema,
+ // Experimental metadata for `export mcp-registry` and `doctor --registry`.
+ // Validated at config load; unused by the MCP adapter.
+ registry: McpRegistrySchema.optional(),
})
.strict(),
// Optional; A2A is off unless configured
@@ -353,6 +357,10 @@ const X402Schema = z
allowMainnet: BooleanOrString.optional(),
// Accepts credential-free facilitator access on mainnet. Never defaulted
allowUnauthenticatedFacilitator: BooleanOrString.optional(),
+ // Experimental: use the configured public endpoint in x402 challenges
+ publicResourceUrl: BooleanOrString.optional(),
+ // Experimental Bazaar discovery metadata; enabling it requires publicResourceUrl
+ bazaar: z.object({ enabled: BooleanOrString }).strict().optional(),
// Experimental ERC-8409 quotes; signing a quote transfers no funds
quote: z
.object({
diff --git a/src/config/schema/resource-schema.ts b/src/config/schema/resource-schema.ts
index 9fb5701..3c12387 100644
--- a/src/config/schema/resource-schema.ts
+++ b/src/config/schema/resource-schema.ts
@@ -1,6 +1,7 @@
// A resource's input schema: the default closed object and the keywords the validator supports
import { CommerceError } from '../../core';
import { isObjectSchemaNode } from '../../core/execution';
+import { ENFORCED_SCHEMA_KEYWORDS } from '../../core/execution/validation';
import { isRecord } from '../../core/is-record';
/**
@@ -61,31 +62,6 @@ export const EMPTY_CLOSED_OBJECT_SCHEMA: Record = {
additionalProperties: false,
};
-// Keywords core's validator ignores (see `execution/validation.ts` for the
-// enforced subset). Config warns at load, since an operator who writes
-// `pattern` cannot otherwise tell that it is not enforced.
-const UNSUPPORTED_SCHEMA_KEYWORDS = [
- 'pattern',
- 'minLength',
- 'maxLength',
- 'format',
- 'minimum',
- 'maximum',
- 'exclusiveMinimum',
- 'exclusiveMaximum',
- 'multipleOf',
- 'oneOf',
- 'anyOf',
- 'allOf',
- 'not',
- '$ref',
- 'const',
- 'patternProperties',
- 'minItems',
- 'maxItems',
- 'uniqueItems',
-];
-
// `type` set to something that rules out "object". No `type` at all does not
// exclude it: the validator treats `properties`/`required` alone as an object
// schema.
@@ -108,8 +84,10 @@ export function validateResourceSchemaKeywords(
path: string,
schema: Record,
): void {
- for (const keyword of UNSUPPORTED_SCHEMA_KEYWORDS) {
- if (Object.hasOwn(schema, keyword)) {
+ // Warn about keywords outside core's supported list to tell operators that
+ // constraints such as `pattern` are not enforced
+ for (const keyword of Object.keys(schema)) {
+ if (!ENFORCED_SCHEMA_KEYWORDS.has(keyword)) {
console.warn(
`[agent-commerce] resource "${id}" ${path} uses JSON Schema keyword "${keyword}", which this gateway does not enforce (see src/core/execution/validation.ts for the supported subset). Remove it or treat it as documentation only.`,
);
diff --git a/src/config/schema/resources.ts b/src/config/schema/resources.ts
index 1fce779..9de6146 100644
--- a/src/config/schema/resources.ts
+++ b/src/config/schema/resources.ts
@@ -237,12 +237,10 @@ export function normalizeResource(
);
}
- // The gateway serves a resource on the first rail it lists that is enabled
- const servingRail = paymentMethods.find(
- (method) =>
- (method === 'x402' && x402?.config.enabled === true) ||
- (method === 'mpp' && mpp?.enabled === true),
- );
+ const servingRail = servingRailOf(paymentMethods, {
+ x402: x402?.config.enabled === true,
+ mpp: mpp?.enabled === true,
+ });
const idempotency = normalizeResourceIdempotency(id, entry, paymentMethods, servingRail);
const pricing: Pricing =
@@ -285,6 +283,16 @@ export function normalizeResource(
};
}
+/** The resource's first enabled payment rail, which the gateway uses to serve it */
+export function servingRailOf(
+ paymentMethods: readonly string[],
+ enabled: { readonly x402: boolean; readonly mpp: boolean },
+): string | undefined {
+ return paymentMethods.find(
+ (method) => (method === 'x402' && enabled.x402) || (method === 'mpp' && enabled.mpp),
+ );
+}
+
function normalizeResourceIdempotency(
id: string,
entry: RawResourceEntry,
diff --git a/src/config/schema/types.ts b/src/config/schema/types.ts
index 92c00a3..7eb36ae 100644
--- a/src/config/schema/types.ts
+++ b/src/config/schema/types.ts
@@ -5,6 +5,7 @@ import type { MppNetwork } from '../../payments/mpp/constants';
import type { X402FacilitatorConfig } from '../../payments/x402/guardrails';
import type { CustomNetworks } from '../../payments/x402/networks';
import type { X402PaymentFlow } from '../../payments/x402/payment-flow';
+import type { X402ProviderOptions } from '../../payments/x402/provider/types';
import type { AcpCheckoutOperation } from '../../protocols/acp/constants';
/** Optional ACP discovery metadata. Absent fields are omitted from the document */
@@ -67,7 +68,7 @@ export interface GatewayConfig {
readonly storage: { readonly receipts: { readonly driver: 'sqlite'; readonly path: string } };
readonly protocols: {
readonly http: { readonly enabled: boolean };
- readonly mcp: { readonly enabled: boolean; readonly mountPath: string };
+ readonly mcp: McpProtocolConfig;
readonly a2a: { readonly enabled: boolean; readonly mountPath: string };
readonly acp: AcpProtocolConfig;
};
@@ -93,6 +94,18 @@ export interface GatewayConfig {
readonly resourcePaymentFlows?: Readonly>;
/** Resources that set `mimeType`, by resource id; others declare `application/json` */
readonly resourceMimeTypes?: Readonly>;
+ /**
+ * Experimental. With `publicResourceUrl: true`, config normalization maps
+ * each x402 resource's exposed HTTP, MCP and A2A surfaces to its invoke
+ * route or protocol mount under `merchant.publicBaseUrl`.
+ */
+ readonly resourceUrls?: NonNullable;
+ /**
+ * Experimental. With `bazaar.enabled: true`, config normalization fills
+ * this map for HTTP and MCP entries in `resourceUrls` that pass the
+ * metadata checks
+ */
+ readonly resourceBazaar?: NonNullable;
readonly facilitator: X402FacilitatorConfig;
readonly allowMainnet?: boolean;
readonly allowUnauthenticatedFacilitator?: boolean;
@@ -138,9 +151,24 @@ export interface GatewayConfig {
readonly authorization?: { readonly ap2: Ap2AuthorizationConfig };
}
+/** `protocols.mcp` after normalization */
+export interface McpProtocolConfig {
+ readonly enabled: boolean;
+ readonly mountPath: string;
+ /**
+ * Experimental listing fields for `agent-commerce export mcp-registry` and
+ * `doctor --registry`; the MCP adapter does not use them
+ */
+ readonly registry?: {
+ readonly name: string;
+ readonly version: string;
+ readonly description: string;
+ };
+}
+
export interface NormalizedProtocols {
readonly http: { readonly enabled: boolean };
- readonly mcp: { readonly enabled: boolean; readonly mountPath: string };
+ readonly mcp: McpProtocolConfig;
readonly a2a: { readonly enabled: boolean; readonly mountPath: string };
readonly acp: AcpProtocolConfig;
}
diff --git a/src/core/domain/common.ts b/src/core/domain/common.ts
index 995feba..9f00aad 100644
--- a/src/core/domain/common.ts
+++ b/src/core/domain/common.ts
@@ -78,6 +78,11 @@ export interface AdapterHealth {
export interface AdapterHealthComponent {
readonly name: string;
readonly status: 'pass' | 'warn' | 'fail';
+ /**
+ * Marks a probe that received no response; `status` does not describe the
+ * target's health in this case. Experimental: may change in a minor release.
+ */
+ readonly undetermined?: 'unreachable';
}
/** Describes an adapter's supported surface for diagnostics */
diff --git a/src/core/domain/payment.ts b/src/core/domain/payment.ts
index e94097e..12fe195 100644
--- a/src/core/domain/payment.ts
+++ b/src/core/domain/payment.ts
@@ -11,6 +11,7 @@ import type {
DecimalAmount,
IsoTimestamp,
PaymentMethodName,
+ ProtocolName,
} from './common';
import type { PaymentAttempt } from './receipt';
import type { CommerceResource } from './resource';
@@ -122,6 +123,11 @@ export interface PaymentContext {
* challenge to the input but must not send it to a third party.
*/
readonly input?: unknown;
+ /**
+ * The request's protocol, set by the pipeline on each createRequirement call.
+ * Experimental: may change in a minor release.
+ */
+ readonly protocol?: ProtocolName;
readonly metadata?: Readonly>;
}
diff --git a/src/core/execution/pipeline/admission.ts b/src/core/execution/pipeline/admission.ts
index cb4aea7..daf88d9 100644
--- a/src/core/execution/pipeline/admission.ts
+++ b/src/core/execution/pipeline/admission.ts
@@ -92,6 +92,7 @@ export function createPaymentAdmission(
currency: pricing.currency,
requestedAt: options.clock.nowIso(),
input: validInput,
+ protocol: request.protocol,
// Transport facts a rail may bind into its challenge, such as a body digest
...(request.metadata !== undefined ? { metadata: request.metadata } : {}),
});
diff --git a/src/core/execution/schema-example.ts b/src/core/execution/schema-example.ts
new file mode 100644
index 0000000..e5128ce
--- /dev/null
+++ b/src/core/execution/schema-example.ts
@@ -0,0 +1,89 @@
+// Example values and the published object form of a resource's input schema,
+// shared by the adapters and payment metadata that describe a resource
+import type { JsonSchema } from '../domain/common';
+import { AUTHORIZATION_INPUT_FIELD, PAYMENT_INPUT_FIELD } from '../domain/wire';
+import { isRecord } from '../is-record';
+
+/**
+ * Build a sample using the first schema example, then its default or first
+ * enum value, otherwise a value for the declared type. Generated objects use
+ * required properties only; explicit examples, defaults and enum values are
+ * returned unchanged. Other constraints may require different input.
+ */
+export function exampleValue(schema: unknown, name: string): unknown {
+ if (!isRecord(schema)) return `<${name}>`;
+ const examples = schema['examples'];
+ if (Array.isArray(examples) && examples.length > 0) return examples[0];
+ if (schema['default'] !== undefined) return schema['default'];
+ const allowed = schema['enum'];
+ if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];
+ const declared = schema['type'];
+ const type: unknown = Array.isArray(declared) ? declared[0] : declared;
+ switch (type) {
+ case 'object':
+ return exampleObject(schema);
+ case 'array':
+ return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : [];
+ case 'number':
+ case 'integer':
+ return 0;
+ case 'boolean':
+ return false;
+ case 'null':
+ return null;
+ default:
+ return `<${name}>`;
+ }
+}
+
+/** An object holding an example of each required property, without the reserved fields */
+export function exampleObject(schema: Record): Record {
+ const properties = isRecord(schema['properties']) ? schema['properties'] : {};
+ const required = Array.isArray(schema['required']) ? schema['required'] : [];
+ const example: Record = {};
+ for (const key of required) {
+ // The reserved fields carry proofs, which no example can hold
+ if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)
+ continue;
+ example[key] = exampleValue(properties[key], key);
+ }
+ return example;
+}
+
+/** A resource input schema in object form, before discovery surfaces add reserved fields */
+export interface PublishedInputSchema {
+ readonly [keyword: string]: unknown;
+ readonly type: 'object';
+ readonly properties: Readonly>>;
+ readonly required?: readonly string[];
+}
+
+/**
+ * Normalize a resource input schema for publication before a surface adds
+ * reserved fields. Set `type` to `'object'`, keep object-valued `properties`
+ * and string entries in `required`, and preserve other keywords.
+ */
+export function publishedInputSchema(schema: JsonSchema | undefined): PublishedInputSchema {
+ const base = isRecord(schema) ? schema : {};
+ const properties = isRecord(base['properties'])
+ ? Object.fromEntries(
+ Object.entries(base['properties']).filter(
+ (entry): entry is [string, Record] => isRecord(entry[1]),
+ ),
+ )
+ : {};
+ const required = Array.isArray(base['required'])
+ ? base['required'].filter((v): v is string => typeof v === 'string')
+ : [];
+ const extra = Object.fromEntries(
+ Object.entries(base).filter(
+ ([key]) => key !== 'type' && key !== 'properties' && key !== 'required',
+ ),
+ );
+ return {
+ ...extra,
+ type: 'object',
+ properties,
+ ...(required.length > 0 ? { required } : {}),
+ };
+}
diff --git a/src/core/execution/validation.ts b/src/core/execution/validation.ts
index 0185ac8..b6926b8 100644
--- a/src/core/execution/validation.ts
+++ b/src/core/execution/validation.ts
@@ -11,12 +11,12 @@
* order)
* - `items` (one schema applied to every array element, no tuple form)
*
- * Not enforced: `minLength`, `maxLength`, `pattern`, `format`, `minimum`,
- * `maximum`, `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`,
- * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`,
- * `maxItems`, `uniqueItems`, tuple-form `items`, and a `type` naming anything
- * outside the list above. Config warns at load when a schema uses one of these
- * keywords or a tuple `items`.
+ * Not enforced: every other constraint, among them `minLength`, `maxLength`,
+ * `pattern`, `format`, `minimum`, `maximum`, `multipleOf`, `oneOf`, `anyOf`,
+ * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`, `maxItems`
+ * and `uniqueItems`, tuple-form `items`, and a `type` naming anything outside
+ * the list above. Config warns at load when a schema uses a keyword outside
+ * `ENFORCED_SCHEMA_KEYWORDS` or a tuple `items`.
*/
import { isDeepStrictEqual } from 'node:util';
import type { JsonSchema } from '../domain/common';
@@ -43,6 +43,107 @@ const SUPPORTED_TYPES = new Set([
'null',
]);
+/**
+ * Keywords enforced by `validateNode`, plus annotations that do not constrain
+ * input. Includes the singular OpenAPI `example` carried by `import openapi`.
+ * Config warns about input schema keywords outside this set.
+ */
+export const ENFORCED_SCHEMA_KEYWORDS: ReadonlySet = new Set([
+ 'type',
+ 'properties',
+ 'required',
+ 'additionalProperties',
+ 'enum',
+ 'items',
+ 'title',
+ 'description',
+ 'example',
+ 'examples',
+ 'default',
+ '$comment',
+ 'deprecated',
+ 'readOnly',
+ 'writeOnly',
+]);
+
+// The value forms JSON Schema 2020-12 allows for the annotations above
+const ANNOTATION_FORMS: readonly (readonly [string, string, (value: unknown) => boolean])[] = [
+ ['title', 'a string', (value) => typeof value === 'string'],
+ ['description', 'a string', (value) => typeof value === 'string'],
+ ['$comment', 'a string', (value) => typeof value === 'string'],
+ ['examples', 'a list', Array.isArray],
+ ['deprecated', 'a boolean', (value) => typeof value === 'boolean'],
+ ['readOnly', 'a boolean', (value) => typeof value === 'boolean'],
+ ['writeOnly', 'a boolean', (value) => typeof value === 'boolean'],
+];
+
+const isDistinctStrings = (value: unknown): value is string[] =>
+ Array.isArray(value) &&
+ value.every((entry) => typeof entry === 'string') &&
+ new Set(value).size === value.length;
+
+/**
+ * Find the first unsupported or malformed part of a schema: a keyword outside
+ * `ENFORCED_SCHEMA_KEYWORDS`, a subschema that is not an object, `items` or
+ * `additionalProperties` that this validator would not apply under the node's
+ * type, or an invalid keyword value. Check keyword forms against JSON Schema
+ * 2020-12 and reject empty `enum` arrays, which Ajv also refuses to compile.
+ * Return `undefined` when these checks pass.
+ */
+export function unenforcedSchemaPart(schema: unknown, path = '$'): FieldError | undefined {
+ if (!isRecord(schema)) return { path, message: 'is not a schema object' };
+ const unknown = Object.keys(schema).find((key) => !ENFORCED_SCHEMA_KEYWORDS.has(key));
+ if (unknown !== undefined) {
+ return { path, message: `uses "${unknown}", which the gateway does not enforce` };
+ }
+ const malformed = (keyword: string, form: string): FieldError => ({
+ path,
+ message: `has a "${keyword}" that is not ${form}`,
+ });
+ const { type, properties, required, additionalProperties, items } = schema;
+ const types = typeof type === 'string' ? [type] : type === undefined ? [] : type;
+ if (
+ !isDistinctStrings(types) ||
+ (Array.isArray(type) && type.length === 0) ||
+ !types.every((entry) => SUPPORTED_TYPES.has(entry))
+ ) {
+ return malformed('type', 'a supported type or a list of distinct ones');
+ }
+ if (required !== undefined && !isDistinctStrings(required)) {
+ return malformed('required', 'a list of distinct strings');
+ }
+ const allowed = schema['enum'];
+ if (allowed !== undefined && (!Array.isArray(allowed) || allowed.length === 0)) {
+ return malformed('enum', 'a list with at least one value');
+ }
+ for (const [keyword, form, accepts] of ANNOTATION_FORMS) {
+ if (schema[keyword] !== undefined && !accepts(schema[keyword])) return malformed(keyword, form);
+ }
+ if (properties !== undefined) {
+ if (!isRecord(properties)) return malformed('properties', 'an object');
+ for (const [key, sub] of Object.entries(properties)) {
+ const part = unenforcedSchemaPart(sub, `${path}.properties.${key}`);
+ if (part !== undefined) return part;
+ }
+ }
+ // `validateNode` applies these two only when the node's type admits them
+ if (additionalProperties !== undefined) {
+ if (!isObjectSchemaNode(schema)) {
+ return { path, message: 'declares "additionalProperties" but is not an object schema' };
+ }
+ if (typeof additionalProperties !== 'boolean') {
+ const part = unenforcedSchemaPart(additionalProperties, `${path}.additionalProperties`);
+ if (part !== undefined) return part;
+ }
+ }
+ if (items === undefined) return undefined;
+ if (!types.includes('array')) {
+ return { path, message: 'declares "items" but its type does not include "array"' };
+ }
+ // A tuple `items` (an array of schemas) is not enforced
+ return unenforcedSchemaPart(items, `${path}.items`);
+}
+
/** Wrap a resource `inputSchema` in a reusable validator function */
export function compileJsonSchema(schema: JsonSchema | undefined): Validator {
return (input: unknown): ValidationResult => {
diff --git a/src/core/no-answer.ts b/src/core/no-answer.ts
new file mode 100644
index 0000000..9752cf8
--- /dev/null
+++ b/src/core/no-answer.ts
@@ -0,0 +1,35 @@
+// Classify transport failures for health checks and `doctor` diagnostics
+
+// Node and undici transport errors classified as unreachable. Configuration
+// failures such as ENOTFOUND, TLS/certificate errors and rejected ports stay
+// unmarked.
+const NO_ANSWER_CODES = new Set([
+ 'ECONNREFUSED',
+ 'ECONNRESET',
+ 'ETIMEDOUT',
+ 'EHOSTUNREACH',
+ 'ENETUNREACH',
+ 'EAI_AGAIN',
+ 'UND_ERR_CONNECT_TIMEOUT',
+ 'UND_ERR_HEADERS_TIMEOUT',
+ 'UND_ERR_BODY_TIMEOUT',
+]);
+
+/**
+ * Identify known transport failures for health checks and `doctor`. Search a
+ * bounded cause chain for the codes above, `TimeoutError` (used by
+ * `AbortSignal.timeout` and viem), or a name in `timeoutNames`. Return false
+ * for unrecognized errors, which keeps configuration failures from counting
+ * as outages.
+ */
+export function gotNoAnswer(err: unknown, timeoutNames: readonly string[] = []): boolean {
+ let cause = err;
+ // The bound stops a cause cycle
+ for (let depth = 0; depth < 10 && cause instanceof Error; depth++) {
+ if (cause.name === 'TimeoutError' || timeoutNames.includes(cause.name)) return true;
+ const { code } = cause as { code?: unknown };
+ if (typeof code === 'string' && NO_ANSWER_CODES.has(code)) return true;
+ cause = cause.cause;
+ }
+ return false;
+}
diff --git a/src/gateway/payment-providers.ts b/src/gateway/payment-providers.ts
index afcc1d7..90df703 100644
--- a/src/gateway/payment-providers.ts
+++ b/src/gateway/payment-providers.ts
@@ -59,6 +59,8 @@ export async function createConfiguredPaymentProviders(
...(x402.resourceMimeTypes !== undefined
? { resourceMimeTypes: x402.resourceMimeTypes }
: {}),
+ ...(x402.resourceUrls !== undefined ? { resourceUrls: x402.resourceUrls } : {}),
+ ...(x402.resourceBazaar !== undefined ? { resourceBazaar: x402.resourceBazaar } : {}),
facilitator: x402.facilitator,
...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),
...(x402.allowUnauthenticatedFacilitator !== undefined
diff --git a/src/gateway/run.ts b/src/gateway/run.ts
index 4c2cbf3..ccfc479 100644
--- a/src/gateway/run.ts
+++ b/src/gateway/run.ts
@@ -104,7 +104,16 @@ export async function runGateway(options: RunGatewayOptions = {}): Promise
const protocolAdapters: ProtocolAdapter[] = [];
if (mcpModule !== undefined) {
- protocolAdapters.push(mcpModule.createMcpAdapter({ mountPath: mcp.mountPath }));
+ // The registry's `server.json` defines `version` as `Implementation.version`:
+ // a listed server reports the listing's name and version at `initialize`
+ protocolAdapters.push(
+ mcpModule.createMcpAdapter({
+ mountPath: mcp.mountPath,
+ ...(mcp.registry !== undefined
+ ? { serverName: mcp.registry.name, serverVersion: mcp.registry.version }
+ : {}),
+ }),
+ );
}
if (config.protocols.a2a.enabled) {
protocolAdapters.push(
diff --git a/src/gateway/well-known.ts b/src/gateway/well-known.ts
index 965c1e8..233a969 100644
--- a/src/gateway/well-known.ts
+++ b/src/gateway/well-known.ts
@@ -29,6 +29,8 @@ import {
import { x402OfferName } from '../payments/x402/options';
import { X402_DEFAULT_PAYMENT_FLOW, type X402PaymentFlow } from '../payments/x402/payment-flow';
import type { X402PaymentProvider } from '../payments/x402/provider/types';
+import { type FeatureStatus, featureStatus } from '../support/claims';
+import x402Record from '../support/x402.json' with { type: 'json' };
import { PACKAGE_VERSION } from '../version';
import type { ProbedAdapter, ProbedProvider } from './readiness';
@@ -36,6 +38,8 @@ import type { ProbedAdapter, ProbedProvider } from './readiness';
// negotiates against, which changes only when that contract does
const GATEWAY_SUPPORTED_SPEC = 'agent-commerce/v1.0.0';
+const QUOTE_STATUS = featureStatus(x402Record, 'erc-8409-quotes');
+
/**
* The protocol block as published, not as configured.
*
@@ -91,7 +95,7 @@ export interface WellKnownDocument {
readonly resourceOptions?: Readonly>;
/** Absent unless the x402 provider signs ERC-8409 quotes */
readonly quote?: WellKnownX402Quote;
- };
+ } & OfferHealth;
/** Public settlement fields; excludes the challenge secret and facilitator credentials */
readonly mpp?: {
readonly enabled: boolean;
@@ -107,12 +111,23 @@ export interface WellKnownDocument {
readonly paymentFlow: X402PaymentFlow;
/** Resources that set their own flow, by id; absent when none does */
readonly resourcePaymentFlows?: Readonly>;
- };
+ } & OfferHealth;
};
}
+/**
+ * Public probe results for one offer, without diagnostic detail. On a rail
+ * block, these fields describe its own offer and appear only when `options`
+ * is absent.
+ */
+export interface OfferHealth {
+ readonly status?: AdapterHealth['status'];
+ /** Marks an unreachable probe; `status` does not describe the offer's health */
+ readonly undetermined?: 'unreachable';
+}
+
/** One x402 offer's public terms */
-export interface WellKnownX402Offer {
+export interface WellKnownX402Offer extends OfferHealth {
readonly network: string;
readonly asset: string;
readonly assetName?: string;
@@ -120,8 +135,6 @@ export interface WellKnownX402Offer {
readonly assetDecimals: number;
readonly payTo: string;
readonly assetTransferMethod?: 'permit2';
- /** Last reported health status, excluding diagnostic detail */
- readonly status?: AdapterHealth['status'];
}
/**
@@ -133,7 +146,7 @@ export interface WellKnownX402Quote {
readonly requestScheme: string;
/** The key in `PaymentRequired.extensions` that carries the quotes */
readonly extension: string;
- readonly status: 'experimental';
+ readonly status: FeatureStatus;
}
export interface BuildWellKnownOptions {
@@ -168,14 +181,25 @@ function publicProtocols(protocols: GatewayConfig['protocols']): WellKnownProtoc
};
}
+// Find the offer's probe by its x402 component name; return no fields if absent
+function offerHealth(
+ health: AdapterHealth | undefined,
+ offer: { readonly network: string; readonly asset: string; readonly payTo: string },
+): OfferHealth {
+ const name = x402OfferName(offer);
+ const component = health?.components?.find((candidate) => candidate.name === name);
+ if (component === undefined) return {};
+ const { status, undetermined } = component;
+ return { status, ...(undetermined !== undefined ? { undetermined } : {}) };
+}
+
// Allowlist public offer fields: RPC URLs can contain API keys
function publicOffer(
option: X402OptionConfig,
- statuses: ReadonlyMap,
+ health: AdapterHealth | undefined,
): WellKnownX402Offer {
const { network, asset, assetName, assetVersion, assetDecimals, payTo, assetTransferMethod } =
option;
- const status = statuses.get(x402OfferName(option));
return {
network,
asset,
@@ -184,7 +208,7 @@ function publicOffer(
assetDecimals,
payTo,
...(assetTransferMethod !== undefined ? { assetTransferMethod } : {}),
- ...(status !== undefined ? { status } : {}),
+ ...offerHealth(health, option),
};
}
@@ -204,7 +228,7 @@ function publicQuote(providers: readonly PaymentProvider[]): WellKnownX402Quote
| undefined;
if (x402?.quote === undefined) return undefined;
const { issuer, requestScheme, extension } = x402.quote;
- return { issuer, requestScheme, extension, status: 'experimental' };
+ return { issuer, requestScheme, extension, status: QUOTE_STATUS };
}
export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnownDocument {
@@ -214,10 +238,10 @@ export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnow
}));
const { x402, mpp } = options.config.payments;
- const x402Health = options.paymentHealth?.find((probed) => probed.name === 'x402')?.health;
- const offerStatuses = new Map(
- (x402Health?.components ?? []).map((component) => [component.name, component.status]),
- );
+ const probed = (name: string) =>
+ options.paymentHealth?.find((provider) => provider.name === name)?.health;
+ const x402Health = probed('x402');
+ const x402Options = x402?.options !== undefined && x402.options.length > 1 ? x402.options : [];
const quote = publicQuote(options.paymentProviders);
return {
@@ -254,15 +278,15 @@ export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnow
),
paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,
...flowOverrides(x402.resourcePaymentFlows),
- ...(x402.options !== undefined && x402.options.length > 1
- ? { options: x402.options.map((option) => publicOffer(option, offerStatuses)) }
- : {}),
+ ...(x402Options.length > 0
+ ? { options: x402Options.map((option) => publicOffer(option, x402Health)) }
+ : offerHealth(x402Health, x402)),
...(x402.resourceOptions !== undefined
? {
resourceOptions: Object.fromEntries(
Object.entries(x402.resourceOptions).map(([id, list]) => [
id,
- list.map((option) => publicOffer(option, offerStatuses)),
+ list.map((option) => publicOffer(option, x402Health)),
]),
),
}
@@ -285,6 +309,12 @@ export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnow
mode: resolveDeploymentMode(requireX402Network(mpp.network, 'payments.mpp.network')),
paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,
...flowOverrides(mpp.resourcePaymentFlows),
+ // MPP settles through an x402 provider, which names the offer
+ ...offerHealth(probed('mpp'), {
+ network: mpp.network,
+ asset: mpp.asset,
+ payTo: mpp.recipient,
+ }),
},
}
: {}),
diff --git a/src/payments/mpp/descriptor.ts b/src/payments/mpp/descriptor.ts
index cb07d18..a701c11 100644
--- a/src/payments/mpp/descriptor.ts
+++ b/src/payments/mpp/descriptor.ts
@@ -1,12 +1,15 @@
/**
* Describes the MPP profile and its unsupported variants.
*
- * The protocol name alone cannot identify a compatible intent, method and
- * extension set, so the descriptor lists both the target and its gaps.
+ * The descriptor identifies the intent, method, extensions and unsupported
+ * variants needed to assess compatibility. Status and unsupported variants
+ * come from `src/support/mpp.json`.
*
* Importing the descriptor does not load `mppx`.
*/
import type { AdapterDescriptor } from '../../core/public-types';
+import { descriptorStatus, exclusionNames } from '../../support/claims';
+import record from '../../support/mpp.json' with { type: 'json' };
import { PACKAGE_VERSION } from '../../version';
import { MPP_NETWORKS, MPP_PROFILE, MPP_SUPPORTED_SPEC } from './constants';
@@ -29,20 +32,6 @@ export const MPP_DESCRIPTOR: AdapterDescriptor = {
// HTTP request bodies only; MCP and A2A carry the proof in the body
'challenge-digest-binding',
],
- // The pinned specs are drafts and mppx is pre-1.0; the wire format may change
- status: 'experimental',
- unsupported: [
- // Name other methods as a class instead of maintaining a second list
- 'methods other than evm',
- // This profile supports only the EIP-3009 `authorization` credential
- 'credential=permit2',
- 'credential=transaction',
- 'credential=hash',
- // The draft allows splits only with permit2 credentials
- 'splits',
- 'intent=subscription',
- // A separate EVM draft, not an option of charge
- 'evm sessions',
- 'discovery extension',
- ],
+ status: descriptorStatus(record),
+ unsupported: exclusionNames(record),
};
diff --git a/src/payments/x402/facilitator.ts b/src/payments/x402/facilitator.ts
index 8cc1ea5..e9dfcaa 100644
--- a/src/payments/x402/facilitator.ts
+++ b/src/payments/x402/facilitator.ts
@@ -185,19 +185,18 @@ export function createRemoteFacilitatorBinding(
// The SDK bounds each attempt but not its retry waits. `Promise.race` keeps
// a handler on the abandoned call, so its later rejection is not unhandled.
+// The `TimeoutError` cause lets health() classify the deadline as unreachable.
function withDeadline(call: Promise, ms: number): Promise {
let timer: NodeJS.Timeout | undefined;
const deadline = new Promise((_, reject) => {
- timer = setTimeout(
- () =>
- reject(
- new CommerceError(
- 'PAYMENT_PROVIDER_UNAVAILABLE',
- `x402 provider: facilitator /supported did not answer within ${ms / 1000} s`,
- ),
- ),
- ms,
- );
+ timer = setTimeout(() => {
+ const message = `x402 provider: facilitator /supported did not answer within ${ms / 1000} s`;
+ reject(
+ new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', message, {
+ cause: new DOMException(message, 'TimeoutError'),
+ }),
+ );
+ }, ms);
timer.unref();
});
return Promise.race([call, deadline]).finally(() => clearTimeout(timer));
diff --git a/src/payments/x402/payload.ts b/src/payments/x402/payload.ts
index eda7373..814acbb 100644
--- a/src/payments/x402/payload.ts
+++ b/src/payments/x402/payload.ts
@@ -7,10 +7,11 @@
* which throws.
*/
import { PaymentPayloadV2Schema } from '@x402/core/schemas';
-import type { PaymentPayload } from '@x402/core/types';
+import type { PaymentPayload, PaymentRequired } from '@x402/core/types';
import type { ExactEIP3009Payload, ExactPermit2Payload } from '@x402/evm';
import { isRecord } from '../../core/is-record';
import { isEvmAddress } from './addresses';
+import { BAZAAR_EXTENSION_KEY } from './provider/bazaar';
export function decodePaymentSubmission(payloadBase64: string): PaymentPayload | undefined {
const json = decodeJson(payloadBase64);
@@ -28,18 +29,26 @@ export function declaredX402Version(payloadBase64: string): unknown {
}
/**
- * The payload as sent to a facilitator. `resource` is optional in v2 and
- * verify() has already matched it against the offer; hosted facilitators have
- * settled payloads without it, and none has been shown to accept this
- * gateway's `resource://` URL. `extensions` is dropped because quote echoes
- * are not used to verify payment, and a gas-sponsoring extension in a Permit2
- * payload would activate unsupported SDK facilitator behavior.
+ * Build the facilitator payload, dropping the buyer's `resource` and
+ * `extensions`. `resource` is optional in v2; verify() checks its URL against
+ * the challenge when present. Quote echoes are not used to verify payment,
+ * and a gas-sponsoring extension in a Permit2 payload would activate
+ * unsupported SDK facilitator behavior.
+ *
+ * When the `issued` challenge carries Bazaar metadata, attach its `resource`
+ * and `extensions.bazaar` for cataloging. The provider passes `issued` only
+ * for a facilitator that lists the extension. Use the issued values to keep
+ * an altered buyer echo from replacing the listing metadata.
*/
export function forFacilitator(
payload: T,
-): Omit {
+ issued: PaymentRequired | undefined,
+): Omit & Pick, 'resource' | 'extensions'> {
const { resource: _resource, extensions: _extensions, ...rest } = payload;
- return rest;
+ const bazaar = issued?.extensions?.[BAZAAR_EXTENSION_KEY];
+ return issued !== undefined && bazaar !== undefined
+ ? { ...rest, resource: issued.resource, extensions: { [BAZAAR_EXTENSION_KEY]: bazaar } }
+ : rest;
}
function decodeJson(payloadBase64: string): unknown {
diff --git a/src/payments/x402/provider/bazaar-forwarding.ts b/src/payments/x402/provider/bazaar-forwarding.ts
new file mode 100644
index 0000000..da8daab
--- /dev/null
+++ b/src/payments/x402/provider/bazaar-forwarding.ts
@@ -0,0 +1,85 @@
+// Forward Bazaar metadata to supporting facilitators and log cataloging outcomes
+import type { PaymentRequired } from '@x402/core/types';
+import { redactedErrorText } from '../../../core/errors';
+import { isRecord } from '../../../core/is-record';
+import { BAZAAR_EXTENSION_KEY } from './bazaar';
+import type { SupportedSource } from './fee-payer';
+import type { ProviderContext } from './types';
+
+// Maximum wait for `/supported` before forwarding a proof without metadata
+const SUPPORTED_GRACE_MS = 1_000;
+// Bound the amount of facilitator-controlled reason text written to the log
+const MAX_LOGGED_REASON_LENGTH = 200;
+
+export interface BazaarForwarding {
+ /**
+ * Return `issued` when it carries Bazaar metadata and the remote facilitator
+ * lists `bazaar` in `/supported`. Otherwise return `undefined`, which omits
+ * its `resource` and metadata. Failed or slow reads omit them too.
+ */
+ issuedFor(issued: PaymentRequired | undefined): Promise;
+ /** Log a cataloging refusal from a verify or settle result, once per resource */
+ report(resourceId: string, extensionResponses: Record | undefined): void;
+}
+
+/**
+ * Forward metadata only to remote facilitators that list `bazaar` in
+ * `/supported`, as specified in x402 v2 section 7.3. Unsupported fields could
+ * otherwise cause a facilitator to reject the buyer's payment. The in-process
+ * facilitator keeps no catalog and receives no metadata. Wait up to one second
+ * for `/supported`, then proceed without metadata if the read is slow or fails.
+ */
+export function createBazaarForwarding(
+ ctx: ProviderContext,
+ currentSupported: SupportedSource,
+): BazaarForwarding {
+ const { remoteBinding, logger } = ctx;
+ let unlistedLogged = false;
+ const rejectedLogged = new Set();
+
+ async function listed(): Promise {
+ if (remoteBinding?.kind !== 'remote') return false;
+ let timer: NodeJS.Timeout | undefined;
+ const late = new Promise((resolve) => {
+ timer = setTimeout(() => resolve(undefined), SUPPORTED_GRACE_MS);
+ timer.unref();
+ });
+ const supported = await Promise.race([currentSupported(), late])
+ .catch(() => undefined)
+ .finally(() => clearTimeout(timer));
+ if (supported === undefined) return false;
+ const lists =
+ Array.isArray(supported.extensions) && supported.extensions.includes(BAZAAR_EXTENSION_KEY);
+ if (!lists && !unlistedLogged) {
+ unlistedLogged = true;
+ logger.warn(
+ { facilitator: remoteBinding.describe },
+ 'x402: the facilitator does not list the bazaar extension in /supported; Bazaar metadata stays in challenges but is not sent to it',
+ );
+ }
+ return lists;
+ }
+
+ return {
+ async issuedFor(issued) {
+ if (issued?.extensions?.[BAZAAR_EXTENSION_KEY] === undefined) return undefined;
+ return (await listed()) ? issued : undefined;
+ },
+ report(resourceId, extensionResponses) {
+ const outcome = extensionResponses?.[BAZAAR_EXTENSION_KEY];
+ if (!isRecord(outcome) || outcome['status'] !== 'rejected') return;
+ if (rejectedLogged.has(resourceId)) return;
+ rejectedLogged.add(resourceId);
+ const reason = outcome['rejectedReason'];
+ logger.warn(
+ {
+ resourceId,
+ ...(typeof reason === 'string'
+ ? { reportedReason: redactedErrorText(reason).slice(0, MAX_LOGGED_REASON_LENGTH) }
+ : {}),
+ },
+ 'x402: the facilitator rejected the Bazaar metadata of a resource and will not catalog it. Payment is unaffected',
+ );
+ },
+ };
+}
diff --git a/src/payments/x402/provider/bazaar.ts b/src/payments/x402/provider/bazaar.ts
new file mode 100644
index 0000000..72dcec9
--- /dev/null
+++ b/src/payments/x402/provider/bazaar.ts
@@ -0,0 +1,210 @@
+// Build HTTP and MCP Bazaar metadata without loading an SDK. Config loading
+// can use these helpers to report omitted resources and surfaces before startup.
+import type { CommerceResource } from '../../../core';
+import { validateBackendRequestShape } from '../../../core/execution/backend-request';
+import {
+ exampleObject,
+ exampleValue,
+ publishedInputSchema,
+} from '../../../core/execution/schema-example';
+import { compileJsonSchema, unenforcedSchemaPart } from '../../../core/execution/validation';
+
+/** The extension's key in a challenge's `extensions` */
+export const BAZAAR_EXTENSION_KEY = 'bazaar';
+
+/** Maximum serialized extension size accepted by `bazaarMetadata`, in bytes */
+export const MAX_BAZAAR_EXTENSION_BYTES = 4096;
+
+/** Maximum description length accepted by `bazaarMetadata` */
+export const MAX_BAZAAR_DESCRIPTION_LENGTH = 500;
+
+/** Experimental. One surface's `extensions.bazaar` value */
+export interface BazaarExtension {
+ readonly info: Readonly>;
+ readonly schema: Readonly>;
+}
+
+/** Supported Bazaar metadata surfaces */
+export type BazaarSurface = 'http' | 'mcp';
+
+export interface BazaarMetadata {
+ readonly extensions: Partial>;
+ /** Omission reasons and affected surfaces, for config-load warnings */
+ readonly omitted: readonly {
+ readonly surfaces: readonly BazaarSurface[];
+ readonly reason: string;
+ }[];
+}
+
+const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
+
+/**
+ * Build Bazaar extensions for the requested surfaces. Metadata is omitted
+ * unless the generated example passes input schema and backend request shape
+ * checks, and the schema passes checks for supported keywords and valid values.
+ * These checks avoid publishing examples the gateway rejects before pricing
+ * or malformed schemas a facilitator cannot compile. `mimeType` is the
+ * resource's declared media type; an omitted value is treated as JSON.
+ */
+export function bazaarMetadata(
+ resource: CommerceResource,
+ surfaces: readonly BazaarSurface[],
+ mimeType?: string,
+): BazaarMetadata {
+ if (surfaces.length === 0) return { extensions: {}, omitted: [] };
+ const all = (reason: string): BazaarMetadata => ({
+ extensions: {},
+ omitted: [{ surfaces, reason }],
+ });
+
+ const description = resource.description ?? resource.name;
+ if (description.length > MAX_BAZAAR_DESCRIPTION_LENGTH) {
+ return all(
+ `its description is longer than ${MAX_BAZAAR_DESCRIPTION_LENGTH} characters, which the CDP facilitator refuses`,
+ );
+ }
+ const schema = resource.inputSchema ?? {};
+ const part = unenforcedSchemaPart(schema, 'input');
+ if (part !== undefined) {
+ return all(`its input schema cannot be published as is: ${part.path} ${part.message}`);
+ }
+ const example = exampleObject(schema);
+ if (!compileJsonSchema(schema)(example).valid || !shapeAccepts(resource, example)) {
+ return all('the example generated from its input schema fails the gateway input checks');
+ }
+
+ const built = {
+ http: () => httpForm(resource, schema, example, mimeType),
+ mcp: () => mcpForm(resource, description, example),
+ };
+ const extensions: Partial> = {};
+ const oversized: BazaarSurface[] = [];
+ for (const surface of surfaces) {
+ const extension = built[surface]();
+ if (Buffer.byteLength(JSON.stringify(extension)) > MAX_BAZAAR_EXTENSION_BYTES) {
+ oversized.push(surface);
+ } else {
+ extensions[surface] = extension;
+ }
+ }
+ return {
+ extensions,
+ omitted:
+ oversized.length > 0
+ ? [
+ {
+ surfaces: oversized,
+ reason: `the extension exceeds ${MAX_BAZAAR_EXTENSION_BYTES} bytes`,
+ },
+ ]
+ : [],
+ };
+}
+
+function shapeAccepts(resource: CommerceResource, example: unknown): boolean {
+ try {
+ validateBackendRequestShape(resource.handler, example, {
+ requestId: 'bazaar-example',
+ resourceId: resource.id,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Recognize JSON media types, including those with a `+json` syntax suffix
+const JSON_MEDIA_TYPE = /^[^/;\s]+\/(?:[^;\s]+\+)?json\s*(?:;|$)/i;
+
+// The invoke route takes a JSON body. Match the x402 SDK builder by publishing
+// `output` only when a JSON response example is available.
+function httpForm(
+ resource: CommerceResource,
+ schema: Record,
+ example: Record,
+ mimeType: string | undefined,
+): BazaarExtension {
+ const output =
+ mimeType === undefined || JSON_MEDIA_TYPE.test(mimeType)
+ ? outputExample(resource.outputSchema)
+ : undefined;
+ return {
+ info: {
+ input: { type: 'http', method: 'POST', bodyType: 'json', body: example },
+ ...(output !== undefined ? { output: { type: 'json', example: output } } : {}),
+ },
+ schema: {
+ $schema: JSON_SCHEMA_2020_12,
+ type: 'object',
+ properties: {
+ input: {
+ type: 'object',
+ properties: {
+ type: { type: 'string', const: 'http' },
+ method: { type: 'string', enum: ['POST'] },
+ bodyType: { type: 'string', enum: ['json'] },
+ body: schema,
+ },
+ required: ['type', 'method', 'bodyType', 'body'],
+ additionalProperties: false,
+ },
+ ...(output !== undefined
+ ? {
+ output: {
+ type: 'object',
+ properties: { type: { type: 'string' }, example: resource.outputSchema },
+ required: ['type'],
+ },
+ }
+ : {}),
+ },
+ required: ['input'],
+ },
+ };
+}
+
+// A tool is keyed by its endpoint URL and `toolName`, the resource id
+function mcpForm(
+ resource: CommerceResource,
+ description: string,
+ example: Record,
+): BazaarExtension {
+ return {
+ info: {
+ input: {
+ type: 'mcp',
+ toolName: resource.id,
+ description,
+ inputSchema: publishedInputSchema(resource.inputSchema),
+ example,
+ },
+ },
+ schema: {
+ $schema: JSON_SCHEMA_2020_12,
+ type: 'object',
+ properties: {
+ input: {
+ type: 'object',
+ properties: {
+ type: { type: 'string', const: 'mcp' },
+ toolName: { type: 'string' },
+ description: { type: 'string' },
+ inputSchema: { type: 'object' },
+ example: { type: 'object' },
+ },
+ required: ['type', 'toolName', 'inputSchema'],
+ additionalProperties: false,
+ },
+ },
+ required: ['input'],
+ },
+ };
+}
+
+// Publish an output example only when its schema uses the supported subset
+// and local validation accepts it; runtime delivery does not validate output schemas
+function outputExample(schema: Record | undefined): unknown {
+ if (schema === undefined || unenforcedSchemaPart(schema) !== undefined) return undefined;
+ const example = exampleValue(schema, 'output');
+ return compileJsonSchema(schema)(example).valid ? example : undefined;
+}
diff --git a/src/payments/x402/provider/health.ts b/src/payments/x402/provider/health.ts
index 4803d83..19791d7 100644
--- a/src/payments/x402/provider/health.ts
+++ b/src/payments/x402/provider/health.ts
@@ -6,6 +6,7 @@ import { erc20Abi } from 'viem';
import { type AdapterHealth, CommerceError } from '../../../core';
import { redactedErrorText } from '../../../core/errors';
import { isRecord } from '../../../core/is-record';
+import { gotNoAnswer } from '../../../core/no-answer';
import { normalizeAddress } from '../addresses';
import type { createLocalPublicClient } from '../chain';
import type { FacilitatorBinding } from '../facilitator';
@@ -281,27 +282,37 @@ export function createHealthCheck(ctx: ProviderContext): () => Promise
- offerHealth(offer, kinds).catch((err: unknown) => ({
- status: 'fail' as const,
- detail: `x402 health check failed: ${redactedErrorText(err)}`,
- })),
+ offerHealth(offer, kinds).catch(
+ (err: unknown): OfferResult => ({
+ status: 'fail',
+ detail: `x402 health check failed: ${redactedErrorText(err)}`,
+ // The SDK throws its own timeout error from `/supported`
+ ...(gotNoAnswer(err, ['FacilitatorTimeoutError'])
+ ? { undetermined: 'unreachable' }
+ : {}),
+ }),
+ ),
),
);
const failed = results.some((result) => result.status === 'fail');
const details = offers.flatMap((offer, index) => {
- const result = results[index] as (typeof results)[number];
+ const result = results[index] as OfferResult;
if (failed && result.status !== 'fail') return [];
return [offers.length === 1 ? result.detail : `${x402OfferName(offer)}: ${result.detail}`];
});
return {
status: failed ? 'fail' : 'pass',
detail: details.join('; '),
- components: offers.map((offer, index) => ({
- name: x402OfferName(offer),
- status: (results[index] as (typeof results)[number]).status,
- })),
+ components: offers.map((offer, index) => {
+ const { status, undetermined } = results[index] as OfferResult;
+ return {
+ name: x402OfferName(offer),
+ status,
+ ...(undetermined !== undefined ? { undetermined } : {}),
+ };
+ }),
checkedAt,
durationMs: clock.monotonicMs() - startedAt,
};
@@ -338,6 +349,13 @@ export function createHealthCheck(ctx: ProviderContext): () => Promise> = {
+ evm: 1024,
+ svm: 2304,
+ near: 1280,
+};
// Requirement metadata naming the offer `selectRequirement` chose, by index
export const SELECTED_OFFER_KEY = 'x402.offer';
@@ -61,7 +81,9 @@ export function createRequirementBuilders(
readonly createRequirement: (context: PaymentContext) => Promise;
readonly selectRequirement: (context: PaymentVerificationContext) => Promise;
} {
- const { options, offersFor, clock, ids, maxTimeoutSeconds } = ctx;
+ const { options, offersFor, clock, ids, maxTimeoutSeconds, logger } = ctx;
+ // Resources whose HTTP challenge has already been logged as too large
+ const oversizedLogged = new Set();
async function createRequirement(context: PaymentContext): Promise {
const offers = offersFor(context.resource.id);
@@ -111,21 +133,32 @@ export function createRequirementBuilders(
const identifier = paymentIdentifierExtensions(context.resource);
const extensions =
identifier === undefined ? quoteExtensions : { ...quoteExtensions, ...identifier };
+ const bazaar =
+ context.protocol === 'http' || context.protocol === 'mcp'
+ ? options.resourceBazaar?.[context.resource.id]?.[context.protocol]
+ : undefined;
- // The v2 challenge document as sent on the wire. The HTTP adapter
- // base64-encodes it into `PAYMENT-REQUIRED` and MCP passes it through, so
- // both surfaces offer the same challenge.
+ // Build the v2 challenge document. HTTP base64-encodes it into
+ // `PAYMENT-REQUIRED`; MCP passes the document through directly.
//
- // `resource.url` is outside the EIP-3009 signature. A single offer puts its
- // network and payee in it, so the buyer's echo identifies the offer. With
- // several, the URL stays the same whichever one the buyer pays.
+ // `accepted` identifies the offer paid by a proof. With a matching
+ // `resourceUrls` entry, `resource.url` uses the configured URL for this
+ // resource and request surface. Otherwise a single offer's `resource://`
+ // URL includes its network and payee; multiple offers share one URL.
+ // The URL is outside the EIP-3009 signature; verification rejects a
+ // mismatched URL only when the proof echoes it.
const resourceId = encodeURIComponent(context.resource.id);
+ const surface = context.protocol === 'acp' ? undefined : context.protocol;
+ const publicUrl =
+ surface !== undefined ? options.resourceUrls?.[context.resource.id]?.[surface] : undefined;
const envelope: PaymentRequired = {
x402Version: X402_VERSION,
resource: {
- url: single
- ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}`
- : `resource://agent-commerce/resources/${resourceId}`,
+ url:
+ publicUrl ??
+ (single
+ ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}`
+ : `resource://agent-commerce/resources/${resourceId}`),
description: context.resource.description ?? context.resource.name,
// The media type the merchant declares, else `application/json`; an HTTP
// delivery carries the backend's own type when it is text and fits the body
@@ -134,6 +167,18 @@ export function createRequirementBuilders(
accepts,
...(extensions !== undefined ? { extensions } : {}),
};
+ const challenge =
+ bazaar === undefined
+ ? envelope
+ : withBazaar(
+ envelope,
+ bazaar,
+ // MCP carries the challenge in the result body, not a header
+ context.protocol === 'http'
+ ? Math.max(...offers.map((offer) => PROOF_RESERVE_BYTES[offer.family]))
+ : undefined,
+ context.resource.id,
+ );
const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1000).toISOString();
@@ -153,7 +198,7 @@ export function createRequirementBuilders(
provider: 'x402',
version: X402_PROTOCOL_VERSION,
accepts: accepts as unknown as Record[],
- envelope: envelope as unknown as Record,
+ envelope: challenge as unknown as Record,
},
metadata: {
[SETTLE_AFTER_BACKEND_METADATA_KEY]: paymentFlow === 'authorization',
@@ -164,6 +209,31 @@ export function createRequirementBuilders(
};
}
+ // Omit Bazaar if the HTTP challenge plus its proof reserve exceeds 8 KiB.
+ // `headerReserve` is undefined for other surfaces.
+ function withBazaar(
+ envelope: PaymentRequired,
+ bazaar: unknown,
+ headerReserve: number | undefined,
+ resourceId: string,
+ ): PaymentRequired {
+ const extended = {
+ ...envelope,
+ extensions: { ...envelope.extensions, [BAZAAR_EXTENSION_KEY]: bazaar },
+ };
+ if (headerReserve === undefined) return extended;
+ const encoded = 4 * Math.ceil(Buffer.byteLength(JSON.stringify(extended)) / 3);
+ if (encoded + headerReserve <= MAX_HTTP_HEADER_BYTES) return extended;
+ if (!oversizedLogged.has(resourceId)) {
+ oversizedLogged.add(resourceId);
+ logger.warn(
+ { resourceId, bytes: encoded, reservedBytes: headerReserve },
+ 'x402: Bazaar metadata left out of an HTTP challenge too large to leave room for the signed proof in an 8 KiB header',
+ );
+ }
+ return envelope;
+ }
+
/**
* Selects the unique offer matching `accepted`, leaving zero or multiple
* matches unchanged for `verify()` to reject. Selection identifies the
diff --git a/src/payments/x402/provider/settle.ts b/src/payments/x402/provider/settle.ts
index ed474c0..70eb9e5 100644
--- a/src/payments/x402/provider/settle.ts
+++ b/src/payments/x402/provider/settle.ts
@@ -1,10 +1,11 @@
// Settles a verified proof and classifies the facilitator's answer
-import type { PaymentRequirements, SettleResponse } from '@x402/core/types';
+import type { PaymentRequired, PaymentRequirements, SettleResponse } from '@x402/core/types';
import type { PaymentResult, PaymentSettlementContext } from '../../../core';
import { CommerceError } from '../../../core';
import { redactedErrorText } from '../../../core/errors';
import { isTransactionReference } from '../addresses';
import { decodePaymentSubmission, forFacilitator } from '../payload';
+import type { BazaarForwarding } from './bazaar-forwarding';
import {
isNearVerdict,
isOnChainRevertError,
@@ -23,6 +24,7 @@ import type { ProviderContext } from './types';
/** Builds the provider's `settle`, which throws unless handed a successful verification */
export function createSettle(
ctx: ProviderContext,
+ bazaar: BazaarForwarding,
): (context: PaymentSettlementContext) => Promise {
const { offersFor, clock, logger } = ctx;
@@ -70,10 +72,13 @@ export function createSettle(
rejectionReason,
});
+ const issued = await bazaar.issuedFor(
+ requirement.challenge.envelope as PaymentRequired | undefined,
+ );
const scope = offer.binding.open();
let sdkResult: SettleResponse;
try {
- sdkResult = await scope.settle(forFacilitator(payload), requirements);
+ sdkResult = await scope.settle(forFacilitator(payload, issued), requirements);
} catch (err) {
if (isProviderUnavailableError(err) || scope.transportFailed()) {
throw new CommerceError(
@@ -106,6 +111,8 @@ export function createSettle(
return rejectedSettlement('transaction_reverted');
}
+ bazaar.report(requirement.resourceId, sdkResult.extensionResponses);
+
// verify() established the payer. The Solana scheme's settlement example
// names the fee payer there, while x402 v2 defines the payer's wallet.
const payer = verification.payer ?? sdkResult.payer;
diff --git a/src/payments/x402/provider/types.ts b/src/payments/x402/provider/types.ts
index 02bf5ef..2d27042 100644
--- a/src/payments/x402/provider/types.ts
+++ b/src/payments/x402/provider/types.ts
@@ -7,6 +7,7 @@ import type { X402FacilitatorConfig } from '../guardrails';
import type { CustomNetworks, DeploymentMode, X402Network } from '../networks';
import type { X402AssetTransferMethod } from '../options';
import type { X402PaymentFlow } from '../payment-flow';
+import type { BazaarExtension, BazaarSurface } from './bazaar';
import type { QuoteIssuer } from './quote';
/** A single offer and the settings every offer shares */
@@ -25,6 +26,24 @@ export interface X402ProviderOptions extends X402OfferOptions {
* keyed by resource id. Defaults to `application/json`.
*/
readonly resourceMimeTypes?: Readonly>;
+ /**
+ * Experimental. Maps resource ids and HTTP/MCP surfaces to the challenge's
+ * `extensions.bazaar` value. Omitted when the encoded HTTP challenge's
+ * `PAYMENT-REQUIRED` value plus its proof reserve exceeds 8 KiB.
+ * Verify and settle send it and the challenge's `resource` to a remote
+ * facilitator that lists `bazaar` in `/supported`.
+ */
+ readonly resourceBazaar?: Readonly<
+ Record>>>
+ >;
+ /**
+ * Experimental. Maps resource ids and request surfaces to the public
+ * `resource.url` used in their challenges. Requests without a surface,
+ * ACP requests and missing entries use `resource://agent-commerce/...`.
+ */
+ readonly resourceUrls?: Readonly<
+ Record>>>
+ >;
/**
* Which facilitator verifies and broadcasts. `local` runs one in this process
* against a dev chain, and its `signerPrivateKey` pays gas there, usually
diff --git a/src/payments/x402/provider/verify.ts b/src/payments/x402/provider/verify.ts
index 174c779..697543f 100644
--- a/src/payments/x402/provider/verify.ts
+++ b/src/payments/x402/provider/verify.ts
@@ -6,6 +6,7 @@ import { CommerceError, RECONCILIATION_METADATA_KEY } from '../../../core';
import { redactedErrorText } from '../../../core/errors';
import { normalizeAddress, sameAddress } from '../addresses';
import { declaredX402Version, decodePaymentSubmission, forFacilitator } from '../payload';
+import type { BazaarForwarding } from './bazaar-forwarding';
import { X402_VERSION } from './constants';
import { offerCurrency } from './offers';
import { paymentIdentifierEchoed } from './payment-id';
@@ -22,6 +23,7 @@ const RELAYER_GRACE_MS = 1_000;
export function createVerify(
ctx: ProviderContext,
nearRelayers: (offer: NearOffer) => Promise,
+ bazaar: BazaarForwarding,
): (context: PaymentVerificationContext) => Promise {
const { offersFor, clock, logger, svm, near } = ctx;
@@ -167,10 +169,13 @@ export function createVerify(
// Fetch NEAR relayers alongside verification; failed `/supported` reads yield none
const relayers = offer.family === 'near' ? nearRelayers(offer) : undefined;
+ const issued = await bazaar.issuedFor(
+ requirement.challenge.envelope as PaymentRequired | undefined,
+ );
const scope = offer.binding.open();
let sdkResult: VerifyResponse;
try {
- sdkResult = await scope.verify(forFacilitator(payload), requirements);
+ sdkResult = await scope.verify(forFacilitator(payload, issued), requirements);
} catch (err) {
// A throw means no verdict was obtained, so it is never held against the
// buyer. Only an unclassified one is logged, as it may be an SDK fault.
@@ -184,6 +189,8 @@ export function createVerify(
);
}
+ bazaar.report(requirement.resourceId, sdkResult.extensionResponses);
+
if (!sdkResult.isValid) {
// An RPC that never answered is not a payment that failed a check
if (scope.transportFailed() || NO_VERDICT_REASONS.has(sdkResult.invalidReason ?? '')) {
diff --git a/src/protocols/a2a/agent-card.ts b/src/protocols/a2a/agent-card.ts
index 0399378..3c12917 100644
--- a/src/protocols/a2a/agent-card.ts
+++ b/src/protocols/a2a/agent-card.ts
@@ -6,8 +6,8 @@
* shape through fields it does define: a sentence in the agent description,
* which also says where the schemas are published, and one example per skill.
*/
-import { AUTHORIZATION_INPUT_FIELD, type CommerceResource, PAYMENT_INPUT_FIELD } from '../../core';
-import { isRecord } from '../../core/is-record';
+import { type CommerceResource, PAYMENT_INPUT_FIELD } from '../../core';
+import { exampleObject } from '../../core/execution/schema-example';
import { joinUrl } from '../http';
import { A2A_JSON_MEDIA_TYPE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION } from './constants';
import { A2A_CALL_SHAPE } from './message-mapping';
@@ -49,50 +49,6 @@ function skillDescription(resource: CommerceResource): string {
return base;
}
-/**
- * Build a sample from schema examples, defaults, enum values or the declared
- * type. Objects include required properties only. Other constraints may need
- * different input.
- */
-function exampleValue(schema: unknown, name: string): unknown {
- if (!isRecord(schema)) return `<${name}>`;
- const examples = schema['examples'];
- if (Array.isArray(examples) && examples.length > 0) return examples[0];
- if (schema['default'] !== undefined) return schema['default'];
- const allowed = schema['enum'];
- if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];
- const declared = schema['type'];
- const type: unknown = Array.isArray(declared) ? declared[0] : declared;
- switch (type) {
- case 'object':
- return exampleObject(schema);
- case 'array':
- return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : [];
- case 'number':
- case 'integer':
- return 0;
- case 'boolean':
- return false;
- case 'null':
- return null;
- default:
- return `<${name}>`;
- }
-}
-
-function exampleObject(schema: Record): Record {
- const properties = isRecord(schema['properties']) ? schema['properties'] : {};
- const required = Array.isArray(schema['required']) ? schema['required'] : [];
- const example: Record = {};
- for (const key of required) {
- // The reserved fields carry proofs, which no example can hold
- if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)
- continue;
- example[key] = exampleValue(properties[key], key);
- }
- return example;
-}
-
/** The `data` value of a data part that calls the skill, as JSON */
function skillExample(resource: CommerceResource): string {
return JSON.stringify({
diff --git a/src/protocols/a2a/descriptor.ts b/src/protocols/a2a/descriptor.ts
index 47be8c7..c66b9f7 100644
--- a/src/protocols/a2a/descriptor.ts
+++ b/src/protocols/a2a/descriptor.ts
@@ -1,13 +1,13 @@
/**
- * Adapter self-description.
- *
- * `supportedSpec` is the A2A specification revision (`1.0.1`), never the
- * negotiation version (`1.0`) and never this package's version. Status is
- * `experimental` while the adapter lacks the features in the unsupported list
- * below; an entry leaves that list only when its feature is implemented.
+ * `supportedSpec` pins the A2A specification revision (`1.0.1`). Negotiation
+ * uses `1.0`; the package version is independent. Status and unsupported
+ * features come from `src/support/a2a.json`. Remove an unsupported entry only
+ * after implementing its feature.
*/
import type { AdapterDescriptor } from '../../core';
-import { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants';
+import record from '../../support/a2a.json' with { type: 'json' };
+import { descriptorStatus, exclusionNames } from '../../support/claims';
+import { A2A_SPEC_VERSION } from './constants';
// What this adapter implements
const A2A_CAPABILITIES: readonly string[] = [
@@ -19,28 +19,12 @@ const A2A_CAPABILITIES: readonly string[] = [
];
/**
- * Major A2A features this adapter does not implement, served on
- * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes
- * full protocol support
+ * Unsupported A2A features, published at `/.well-known/agent-commerce` and
+ * printed by `doctor` to show the limits of protocol support.
+ * The support record also lists the `A2A_UNSUPPORTED_METHODS` refused by the
+ * transport.
*/
-export const A2A_UNSUPPORTED: readonly string[] = [
- // Methods, as the protocol names them; the transport refuses the same list
- ...A2A_UNSUPPORTED_METHODS,
- // Transports other than the one binding served
- 'HTTP+JSON/REST binding',
- 'gRPC binding',
- // Behaviors
- 'SSE',
- 'long-running task persistence',
- 'task resumption other than an x402 extension payment',
- 'push notifications',
- 'multi-turn conversational continuation',
- 'authenticated extended agent cards',
- 'A2A authentication schemes',
- 'artifact types beyond Agent Commerce outcome data',
- // Instances with separate receipt stores cannot resume each other's tasks
- 'x402 extension payments across gateway instances',
-];
+export const A2A_UNSUPPORTED: readonly string[] = exclusionNames(record);
export function buildDescriptor(implementationVersion: string): AdapterDescriptor {
return {
@@ -49,7 +33,7 @@ export function buildDescriptor(implementationVersion: string): AdapterDescripto
implementationVersion,
supportedSpec: A2A_SPEC_VERSION,
capabilities: A2A_CAPABILITIES,
- status: 'experimental',
+ status: descriptorStatus(record),
unsupported: A2A_UNSUPPORTED,
};
}
diff --git a/src/protocols/acp/descriptor.ts b/src/protocols/acp/descriptor.ts
index 02f43bc..ff3e05a 100644
--- a/src/protocols/acp/descriptor.ts
+++ b/src/protocols/acp/descriptor.ts
@@ -1,12 +1,11 @@
/**
- * Adapter self-description.
- *
- * `supportedSpec` is the pinned ACP snapshot, never this package's version.
- * Status is `experimental` while the adapter lacks the features in the
- * unsupported list below; an entry leaves that list only when its feature is
- * implemented.
+ * `supportedSpec` pins the ACP snapshot independently of the package version.
+ * Status and unsupported features come from `src/support/acp.json`.
+ * Remove an unsupported entry only after implementing its feature.
*/
import type { AdapterDescriptor } from '../../core';
+import record from '../../support/acp.json' with { type: 'json' };
+import { descriptorStatus, exclusionNames } from '../../support/claims';
import { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants';
// What this adapter implements
@@ -22,32 +21,11 @@ const ACP_CAPABILITIES: readonly string[] = [
];
/**
- * Major ACP features this adapter does not implement, served on
- * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes
- * full protocol support
+ * Unsupported ACP features from the support record, published at
+ * `/.well-known/agent-commerce` and printed by `doctor` to show the limits of
+ * protocol support
*/
-export const ACP_UNSUPPORTED: readonly string[] = [
- // Services this seller does not implement, named as ACP names them. The
- // discovery document advertises `checkout` alone, and these are the reason.
- 'carts service',
- 'feed service',
- 'standalone orders service',
- 'delegate_payment',
- 'delegate_authentication',
- // Bindings and delivery directions
- 'ACP MCP transport binding',
- 'webhooks',
- 'outbound merchant-to-agent delivery',
- 'ACP client role',
- // Request authentication beyond the bearer token
- 'Signature header verification',
- 'Timestamp replay-window verification',
- // Extensions, versioning and payment handlers
- 'discount extension',
- 'general ACP extension framework',
- 'multiple ACP API versions',
- 'seller-backed payment handler integration',
-];
+export const ACP_UNSUPPORTED: readonly string[] = exclusionNames(record);
export function buildDescriptor(implementationVersion: string): AdapterDescriptor {
return {
@@ -56,7 +34,7 @@ export function buildDescriptor(implementationVersion: string): AdapterDescripto
implementationVersion,
supportedSpec: ACP_SPEC_VERSION,
capabilities: ACP_CAPABILITIES,
- status: 'experimental',
+ status: descriptorStatus(record),
unsupported: ACP_UNSUPPORTED,
};
}
diff --git a/src/protocols/http.ts b/src/protocols/http.ts
index 1fde76d..4a8fee8 100644
--- a/src/protocols/http.ts
+++ b/src/protocols/http.ts
@@ -57,3 +57,13 @@ export async function readCappedBody(req: IncomingMessage, maxBytes: number): Pr
export function joinUrl(baseUrl: string, mountPath: string): string {
return `${baseUrl.replace(/\/+$/, '')}/${mountPath.replace(/^\/+|\/+$/g, '')}`;
}
+
+/**
+ * Join the base and mount path with `joinUrl`, then normalize with the URL
+ * parser: lowercase scheme and host, no default port. x402 challenges and MCP
+ * Registry listings both use this form, which makes their endpoint URL strings
+ * match. Throws when the joined URL cannot be parsed.
+ */
+export function publicEndpointUrl(baseUrl: string, mountPath: string): string {
+ return new URL(joinUrl(baseUrl, mountPath)).href;
+}
diff --git a/src/protocols/mcp/descriptor.ts b/src/protocols/mcp/descriptor.ts
index dd8e542..90d7ddd 100644
--- a/src/protocols/mcp/descriptor.ts
+++ b/src/protocols/mcp/descriptor.ts
@@ -1,10 +1,12 @@
/**
- * Adapter self-description. `supportedSpec` lists the modern revision and
- * the newest 2025-era revision. The SDK's legacy fallback also accepts older
- * 2025-era revisions.
+ * `supportedSpec` lists the modern revision and the newest 2025-era revision.
+ * The SDK's legacy fallback also accepts older revisions, back to 2024-10-07.
+ * Tests do not negotiate that oldest revision.
*/
import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/server';
import type { AdapterDescriptor } from '../../core';
+import { descriptorStatus, exclusionNames } from '../../support/claims';
+import record from '../../support/mcp.json' with { type: 'json' };
import { MCP_MODERN_PROTOCOL_REVISION } from './constants';
// List the modern revision followed by the SDK's latest legacy revision
@@ -14,33 +16,10 @@ const MCP_SUPPORTED_SPEC = `${MCP_MODERN_PROTOCOL_REVISION}, ${LATEST_PROTOCOL_V
const MCP_CAPABILITIES: readonly string[] = ['tools/list', 'tools/call'];
/**
- * MCP surfaces this adapter does not implement, listed so its descriptor never
- * implies blanket protocol compatibility.
- *
- * `dns-rebinding-protection` is delegated rather than missing: the gateway's
- * `onRequest` hook validates Host and Origin for `/mcp` (see adapter.ts), and
- * the adapter provides none on its own.
+ * Unsupported MCP surfaces from the support record, published in the descriptor
+ * to show the limits of protocol support
*/
-export const MCP_UNSUPPORTED: readonly string[] = [
- 'resources',
- 'prompts',
- 'sampling',
- 'completions',
- 'elicitation',
- 'roots',
- 'logging',
- 'notifications/tools/list_changed',
- 'tasks',
- 'dns-rebinding-protection',
- 'authorization',
- 'sessions',
- 'subscriptions',
- 'pagination',
- 'HTTP+SSE transport',
- // mppx reads challenges and refusals from tool-result `_meta`.
- 'MPP payment-required as JSON-RPC error -32042',
- 'MPP verification failure as JSON-RPC error -32043',
-];
+export const MCP_UNSUPPORTED: readonly string[] = exclusionNames(record);
export function buildDescriptor(implementationVersion: string): AdapterDescriptor {
return {
@@ -49,7 +28,7 @@ export function buildDescriptor(implementationVersion: string): AdapterDescripto
implementationVersion,
supportedSpec: MCP_SUPPORTED_SPEC,
capabilities: MCP_CAPABILITIES,
- status: 'stable',
+ status: descriptorStatus(record),
unsupported: MCP_UNSUPPORTED,
};
}
diff --git a/src/protocols/mcp/tool-mapping.ts b/src/protocols/mcp/tool-mapping.ts
index 46b6e4b..8f9bb5e 100644
--- a/src/protocols/mcp/tool-mapping.ts
+++ b/src/protocols/mcp/tool-mapping.ts
@@ -12,7 +12,7 @@ import {
PAYMENT_INPUT_FIELD,
type PaymentMethodName,
} from '../../core';
-import { isRecord } from '../../core/is-record';
+import { publishedInputSchema } from '../../core/execution/schema-example';
import { MPP_MCP_CREDENTIAL_META_KEY } from '../../payments/mpp/transport';
import { X402_MCP_PAYMENT_META_KEY } from '../../payments/x402/transport';
import { MCP_TOOL_NAME_PATTERN } from './constants';
@@ -109,17 +109,8 @@ export function buildToolDescription(resource: CommerceResource): string {
* would otherwise refuse to send them.
*/
export function buildInputSchema(resource: CommerceResource): Tool['inputSchema'] {
- const base = resource.inputSchema;
- const baseIsObject = isRecord(base);
-
- // Keep object-valued property schemas from the resource's config JSON
- const basePropertyEntries: readonly [string, JSONObject][] =
- baseIsObject && isRecord(base.properties)
- ? Object.entries(base.properties).filter((entry): entry is [string, JSONObject] =>
- isRecord(entry[1]),
- )
- : [];
- const properties: Record = Object.fromEntries(basePropertyEntries);
+ const schema = publishedInputSchema(resource.inputSchema);
+ const properties = { ...schema.properties } as Record;
// Both overwrite a resource-declared property of the same name; config
// rejects that collision at load time
@@ -143,23 +134,5 @@ export function buildInputSchema(resource: CommerceResource): Tool['inputSchema'
};
}
- const required =
- baseIsObject && Array.isArray(base.required)
- ? base.required.filter((v): v is string => typeof v === 'string')
- : [];
-
- const extra = baseIsObject
- ? Object.fromEntries(
- Object.entries(base).filter(
- ([key]) => key !== 'type' && key !== 'properties' && key !== 'required',
- ),
- )
- : {};
-
- return {
- ...extra,
- type: 'object',
- properties,
- ...(required.length > 0 ? { required } : {}),
- };
+ return { ...schema, properties } as Tool['inputSchema'];
}
diff --git a/src/support/a2a.json b/src/support/a2a.json
new file mode 100644
index 0000000..db12234
--- /dev/null
+++ b/src/support/a2a.json
@@ -0,0 +1,88 @@
+{
+ "name": "a2a",
+ "kind": "protocol",
+ "title": "A2A",
+ "status": "experimental",
+ "role": "Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension.",
+ "subset": "Agent Card, `SendMessage`, paid flow and the x402 extension",
+ "spec": {
+ "revisions": ["1.0.1"],
+ "display": "v1.0.1; negotiation `1.0`; `JSONRPC` binding",
+ "source": {
+ "repo": "a2aproject/A2A",
+ "commit": "3303592588e388e62e0f69f701af531d2f4e3991"
+ },
+ "stable": true,
+ "statement": "the first stable, production-ready version",
+ "checked": "2026-11-17"
+ },
+ "packages": [{ "name": "@a2a-js/sdk", "use": "test" }],
+ "artifacts": [],
+ "features": [
+ { "name": "agent-card", "status": "experimental" },
+ { "name": "jsonrpc", "status": "experimental" },
+ { "name": "SendMessage", "status": "experimental" },
+ { "name": "x402-extension", "status": "experimental" }
+ ],
+ "exclusions": [
+ { "name": "SendStreamingMessage" },
+ { "name": "GetTask" },
+ { "name": "ListTasks" },
+ { "name": "CancelTask" },
+ { "name": "SubscribeToTask" },
+ { "name": "CreateTaskPushNotificationConfig" },
+ { "name": "GetTaskPushNotificationConfig" },
+ { "name": "ListTaskPushNotificationConfigs" },
+ { "name": "DeleteTaskPushNotificationConfig" },
+ { "name": "GetExtendedAgentCard" },
+ { "name": "HTTP+JSON/REST binding" },
+ { "name": "gRPC binding" },
+ { "name": "SSE" },
+ { "name": "long-running task persistence" },
+ { "name": "task resumption other than an x402 extension payment" },
+ { "name": "push notifications" },
+ { "name": "multi-turn conversational continuation" },
+ { "name": "text parts" },
+ { "name": "file and URL parts (including inline bytes)" },
+ { "name": "multi-part messages" },
+ { "name": "message roles other than ROLE_USER" },
+ { "name": "authenticated extended agent cards" },
+ { "name": "A2A authentication schemes" },
+ { "name": "artifact types beyond Agent Commerce outcome data" },
+ {
+ "name": "x402 extension payments across gateway instances",
+ "note": "Instances with separate receipt stores cannot resume each other's tasks."
+ }
+ ],
+ "deviations": [],
+ "conformance": {
+ "suite": "Our tests against the A2A 1.0.1 specification; the A2A TCK has not been run.",
+ "tests": [
+ "tests/conformance/a2a/agent-card.test.ts",
+ "tests/conformance/a2a/errors.test.ts",
+ "tests/conformance/a2a/free-resource.test.ts",
+ "tests/conformance/a2a/paid-resource.test.ts",
+ "tests/conformance/a2a/protocol-version.test.ts"
+ ],
+ "skipped": []
+ },
+ "gaps": [
+ {
+ "requirement": "§3.1: GetTask, ListTasks and CancelTask, which every agent implements",
+ "state": "open"
+ },
+ {
+ "requirement": "§3.2.2: returnImmediately as well as the blocking default",
+ "state": "open"
+ },
+ {
+ "requirement": "§3.3.2: validate all input parameters, including tenant and configuration",
+ "state": "open"
+ },
+ {
+ "requirement": "§7.1: encrypted communication in production; merchant.publicBaseUrl accepts http",
+ "state": "open"
+ }
+ ],
+ "docs": ["docs/protocols/a2a.md"]
+}
diff --git a/src/support/acp.json b/src/support/acp.json
new file mode 100644
index 0000000..3df678c
--- /dev/null
+++ b/src/support/acp.json
@@ -0,0 +1,89 @@
+{
+ "name": "acp",
+ "kind": "protocol",
+ "title": "ACP",
+ "status": "experimental",
+ "role": "Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment.",
+ "subset": "discovery and the five checkout operations",
+ "spec": {
+ "revisions": ["2026-04-17"],
+ "display": "stable snapshot `2026-04-17`; REST binding",
+ "source": {
+ "repo": "agentic-commerce-protocol/agentic-commerce-protocol",
+ "commit": "6b828681206f1f98a3faba978610ced66770d2ae"
+ },
+ "stable": false,
+ "statement": "currently in `beta`",
+ "checked": "2026-11-17"
+ },
+ "packages": [],
+ "artifacts": [
+ {
+ "path": "src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json",
+ "revision": "6b828681206f1f98a3faba978610ced66770d2ae"
+ },
+ {
+ "path": "tests/fixtures/acp/2026-04-17",
+ "revision": "6b828681206f1f98a3faba978610ced66770d2ae"
+ }
+ ],
+ "features": [
+ { "name": "rest transport", "status": "experimental" },
+ { "name": "well-known discovery", "status": "experimental" },
+ { "name": "bearer authentication", "status": "experimental" },
+ { "name": "API-Version enforcement", "status": "experimental" },
+ { "name": "request header forwarding to the merchant", "status": "experimental" },
+ { "name": "checkout service", "status": "experimental" },
+ { "name": "createCheckoutSession", "status": "experimental" },
+ { "name": "updateCheckoutSession", "status": "experimental" },
+ { "name": "getCheckoutSession", "status": "experimental" },
+ { "name": "completeCheckoutSession", "status": "experimental" },
+ { "name": "cancelCheckoutSession", "status": "experimental" }
+ ],
+ "exclusions": [
+ {
+ "name": "carts service",
+ "note": "The discovery document advertises only the checkout service."
+ },
+ { "name": "feed service" },
+ { "name": "standalone orders service" },
+ { "name": "delegate_payment" },
+ { "name": "delegate_authentication" },
+ { "name": "ACP MCP transport binding" },
+ { "name": "webhooks", "note": "The merchant backend sends ACP order webhooks itself." },
+ { "name": "outbound merchant-to-agent delivery" },
+ { "name": "ACP client role" },
+ {
+ "name": "Signature header verification",
+ "note": "The adapter forwards the header to the merchant unverified."
+ },
+ {
+ "name": "Timestamp replay-window verification",
+ "note": "The adapter forwards the header to the merchant unverified."
+ },
+ { "name": "discount extension" },
+ { "name": "general ACP extension framework" },
+ { "name": "multiple ACP API versions" },
+ { "name": "seller-backed payment handler integration" }
+ ],
+ "deviations": [
+ {
+ "summary": "After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, and another execution could duplicate the order.",
+ "spec": "ACP RFC §6.5",
+ "tests": ["tests/conformance/acp/idempotency.test.ts", "tests/conformance/acp/errors.test.ts"]
+ }
+ ],
+ "conformance": {
+ "suite": "Our tests against the vendored schema and official examples; ACP publishes no conformance suite.",
+ "tests": [
+ "tests/conformance/acp/checkout.test.ts",
+ "tests/conformance/acp/errors.test.ts",
+ "tests/conformance/acp/idempotency.test.ts",
+ "tests/conformance/acp/protocol.test.ts",
+ "tests/conformance/acp/snapshot.test.ts"
+ ],
+ "skipped": []
+ },
+ "gaps": [],
+ "docs": ["docs/protocols/acp.md"]
+}
diff --git a/src/support/ap2.json b/src/support/ap2.json
new file mode 100644
index 0000000..cb00fc7
--- /dev/null
+++ b/src/support/ap2.json
@@ -0,0 +1,88 @@
+{
+ "name": "ap2",
+ "kind": "authorization",
+ "title": "AP2",
+ "status": "experimental",
+ "role": "Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it.",
+ "subset": "closed Checkout Mandate verification before settlement",
+ "spec": {
+ "revisions": ["v0.2.0"],
+ "display": "v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode",
+ "source": {
+ "repo": "google-agentic-commerce/AP2",
+ "commit": "b4587ac1d055888a73b4b21750973cffba961793"
+ },
+ "stable": false,
+ "statement": "Standardization of the specification will continue within the Agentic Authentication Technical and Payments Technical Working Groups in FIDO",
+ "checked": "2026-11-17"
+ },
+ "packages": [
+ { "name": "jose", "use": "runtime" },
+ { "name": "@sd-jwt/core", "use": "runtime" },
+ { "name": "canonicalize", "use": "runtime" }
+ ],
+ "artifacts": [
+ {
+ "path": "tests/fixtures/ap2/v0.2.0",
+ "revision": "b4587ac1d055888a73b4b21750973cffba961793"
+ }
+ ],
+ "features": [
+ { "name": "direct-mode", "status": "experimental" },
+ { "name": "trusted-agent-provider", "status": "experimental" },
+ { "name": "mandate.checkout.1", "status": "experimental" },
+ { "name": "sd-jwt-presentation", "status": "experimental" },
+ { "name": "ES256", "status": "experimental" },
+ { "name": "sha-256", "status": "experimental" },
+ { "name": "static-inline-trust", "status": "experimental" },
+ { "name": "merchant-checkout-jwt-binding", "status": "experimental" },
+ { "name": "agent-commerce/ap2/checkout/v1", "status": "experimental" },
+ { "name": "purchase-binding", "status": "experimental" },
+ { "name": "replay-defence", "status": "experimental" }
+ ],
+ "exclusions": [
+ { "name": "autonomous mode" },
+ {
+ "name": "open checkout mandates (mandate.checkout.open.1)",
+ "note": "Rejected because the provider does not evaluate spending constraints."
+ },
+ { "name": "payment mandates (mandate.payment.1)" },
+ { "name": "spending constraint evaluation" },
+ { "name": "cnf-bound agent keys" },
+ { "name": "user credential delegation (OpenID4VP)" },
+ { "name": "delegation chains and key-binding JWTs" },
+ {
+ "name": "JWKS and any key discovery by URL (jku, x5u)",
+ "note": "Operators supply all keys in config."
+ },
+ { "name": "issuer metadata fetching" },
+ { "name": "remote revocation" },
+ { "name": "key rotation without a config change" },
+ { "name": "signature algorithms other than ES256" },
+ { "name": "digest algorithms other than sha-256" },
+ { "name": "mandate issuance" },
+ { "name": "checkout receipts" },
+ {
+ "name": "AP2 transport adapter or /.well-known/ap2",
+ "note": "HTTP, MCP and A2A carry the mandate in the gateway's own carriers; AP2 v0.2.0 defines none."
+ },
+ { "name": "AP2 as a payment rail" },
+ { "name": "AP2 over the ACP checkout adapter" }
+ ],
+ "deviations": [],
+ "conformance": {
+ "suite": "Tests using mandates minted by the AP2 v0.2.0 reference SDK, plus end-to-end refusal cases.",
+ "tests": [
+ "tests/unit/authorization-ap2/sdk-vectors.test.ts",
+ "tests/integration/ap2-x402-conformance.test.ts"
+ ],
+ "skipped": []
+ },
+ "gaps": [
+ {
+ "requirement": "Return a Checkout Receipt once the merchant has accepted or rejected a Checkout Mandate",
+ "state": "open"
+ }
+ ],
+ "docs": ["docs/protocols/ap2.md"]
+}
diff --git a/src/support/claims.ts b/src/support/claims.ts
new file mode 100644
index 0000000..7589252
--- /dev/null
+++ b/src/support/claims.ts
@@ -0,0 +1,34 @@
+/**
+ * Read support status, feature status and exclusion names for descriptors,
+ * discovery and `doctor`, without loading external packages.
+ * `scripts/support-record.ts` validates records in tests and tooling; runtime
+ * readers trust them.
+ */
+import { CommerceError } from '../core/errors';
+
+/** The fields of a support record that runtime code reads */
+export interface SupportClaims {
+ readonly status: string;
+ readonly features: readonly { readonly name: string; readonly status: string }[];
+ readonly exclusions: readonly { readonly name: string }[];
+}
+
+export type FeatureStatus = 'supported' | 'experimental' | 'partial';
+
+/** Maps `supported` to `stable` without changing the descriptor's status union */
+export function descriptorStatus(record: SupportClaims): 'stable' | 'experimental' {
+ return record.status === 'supported' ? 'stable' : 'experimental';
+}
+
+/** The strings a descriptor publishes in `unsupported` */
+export function exclusionNames(record: SupportClaims): readonly string[] {
+ return record.exclusions.map((exclusion) => exclusion.name);
+}
+
+export function featureStatus(record: SupportClaims, name: string): FeatureStatus {
+ const feature = record.features.find((candidate) => candidate.name === name);
+ if (feature === undefined) {
+ throw new CommerceError('INTERNAL_ERROR', `support record has no feature "${name}"`);
+ }
+ return feature.status as FeatureStatus;
+}
diff --git a/src/support/http.json b/src/support/http.json
new file mode 100644
index 0000000..f14cca7
--- /dev/null
+++ b/src/support/http.json
@@ -0,0 +1,15 @@
+{
+ "name": "http",
+ "kind": "protocol",
+ "title": "HTTP",
+ "status": "supported",
+ "role": "Transport that carries x402 and MPP payments on each resource's invoke route.",
+ "subset": "resource routes and rail-specific payment headers",
+ "packages": [],
+ "artifacts": [],
+ "features": [],
+ "exclusions": [],
+ "deviations": [],
+ "gaps": [],
+ "docs": ["docs/protocols/http.md"]
+}
diff --git a/src/support/mcp.json b/src/support/mcp.json
new file mode 100644
index 0000000..f436fdb
--- /dev/null
+++ b/src/support/mcp.json
@@ -0,0 +1,68 @@
+{
+ "name": "mcp",
+ "kind": "protocol",
+ "title": "MCP",
+ "status": "supported",
+ "role": "Transport that carries x402 and MPP payments in tool calls.",
+ "subset": "tool discovery, invocation, payment-required and error mapping",
+ "spec": {
+ "revisions": ["2026-07-28", "2025-11-25"],
+ "display": "MCP `2026-07-28` and `2025-11-25`",
+ "source": {
+ "repo": "modelcontextprotocol/modelcontextprotocol",
+ "commit": "05aeb07b2db0c02adc4813a7c09f208ca8774152"
+ },
+ "stable": true,
+ "statement": "Current: the current protocol version, which is ready for use and may continue to receive backwards compatible changes",
+ "checked": "2026-11-17"
+ },
+ "packages": [
+ { "name": "@modelcontextprotocol/server", "use": "runtime" },
+ { "name": "@modelcontextprotocol/client", "use": "test" },
+ { "name": "@modelcontextprotocol/sdk", "use": "test" }
+ ],
+ "artifacts": [],
+ "features": [
+ { "name": "tools/list", "status": "supported" },
+ { "name": "tools/call", "status": "supported" }
+ ],
+ "exclusions": [
+ { "name": "resources" },
+ { "name": "prompts" },
+ { "name": "sampling" },
+ { "name": "completions" },
+ { "name": "elicitation" },
+ { "name": "roots" },
+ { "name": "logging" },
+ { "name": "notifications/tools/list_changed" },
+ { "name": "tasks" },
+ {
+ "name": "dns-rebinding-protection",
+ "note": "The adapter relies on the gateway's `onRequest` hook to validate Host and Origin for the MCP mount."
+ },
+ { "name": "authorization" },
+ { "name": "sessions" },
+ { "name": "subscriptions" },
+ { "name": "pagination" },
+ { "name": "HTTP+SSE transport" },
+ {
+ "name": "MPP payment-required as JSON-RPC error -32042",
+ "note": "mppx reads challenges from the tool result's `_meta`."
+ },
+ {
+ "name": "MPP verification failure as JSON-RPC error -32043",
+ "note": "mppx reads refusals from the tool result's `_meta`."
+ }
+ ],
+ "deviations": [],
+ "conformance": {
+ "suite": "Specification tests through the v1 and v2 SDK clients.",
+ "tests": [
+ "tests/conformance/mcp/mcp-conformance.test.ts",
+ "tests/conformance/mcp/modern-era.test.ts"
+ ],
+ "skipped": []
+ },
+ "gaps": [],
+ "docs": ["docs/protocols/mcp.md"]
+}
diff --git a/src/support/mpp.json b/src/support/mpp.json
new file mode 100644
index 0000000..e97ed9f
--- /dev/null
+++ b/src/support/mpp.json
@@ -0,0 +1,130 @@
+{
+ "name": "mpp",
+ "kind": "payment",
+ "title": "MPP",
+ "status": "experimental",
+ "role": "Payment rail, carried by HTTP, MCP and A2A.",
+ "subset": "`charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A",
+ "spec": {
+ "revisions": [
+ "draft-httpauth-payment-01",
+ "draft-payment-intent-charge-00",
+ "draft-evm-charge-00"
+ ],
+ "display": "drafts at `tempoxyz/mpp-specs@806fdb8`",
+ "source": {
+ "repo": "tempoxyz/mpp-specs",
+ "commit": "806fdb8b8c92cda5c84b8660558921b6bbeef7e0"
+ },
+ "stable": false,
+ "statement": "Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time.",
+ "checked": "2026-11-17"
+ },
+ "packages": [{ "name": "mppx", "use": "runtime" }],
+ "artifacts": [],
+ "features": [
+ { "name": "intent=charge", "status": "experimental" },
+ { "name": "method=evm", "status": "experimental" },
+ { "name": "credential=authorization", "status": "experimental" },
+ { "name": "eip-3009", "status": "experimental" },
+ { "name": "network=eip155:31337", "status": "experimental" },
+ { "name": "network=eip155:84532", "status": "experimental" },
+ { "name": "network=eip155:8453", "status": "experimental" },
+ { "name": "asset=USDC", "status": "experimental" },
+ { "name": "verify-before-settle", "status": "experimental" },
+ { "name": "authorization-flow", "status": "experimental" },
+ { "name": "upfront-flow", "status": "experimental" },
+ { "name": "payment-receipt", "status": "experimental" },
+ { "name": "challenge-digest-binding", "status": "experimental" }
+ ],
+ "exclusions": [
+ { "name": "methods other than evm" },
+ {
+ "name": "credential=permit2",
+ "note": "The profile accepts only the EIP-3009 authorization credential."
+ },
+ { "name": "credential=transaction" },
+ { "name": "credential=hash" },
+ { "name": "splits", "note": "The draft allows splits only with `permit2` credentials." },
+ { "name": "intent=subscription" },
+ { "name": "evm sessions", "note": "A separate EVM draft, not an option of charge." },
+ { "name": "discovery extension" }
+ ],
+ "deviations": [
+ {
+ "summary": "The EIP-3009 nonce is keccak256 of `JSON.stringify([id, realm])`, as `mppx` 0.13 derives it, not of `abi.encodePacked(id, realm)`; a credential using the draft's nonce fails with `wrong_nonce`.",
+ "spec": "draft-evm-charge-00",
+ "tests": ["tests/unit/payments-mpp/provider.test.ts"]
+ },
+ {
+ "summary": "Over MCP, payment errors are tool results with `isError` and the challenges in `_meta`, not the JSON-RPC errors the draft maps them to (-32042, -32043, -32602 and -32603).",
+ "spec": "draft-payment-transport-mcp-00",
+ "tests": ["tests/integration/mcp-payment-bindings.test.ts"]
+ },
+ {
+ "summary": "An unpaid request that gets a 402 also stores a `resource.requested` event beside the challenge.",
+ "spec": "draft-httpauth-payment-01 §11.4",
+ "tests": ["tests/unit/core/execution/pipeline.test.ts"]
+ },
+ {
+ "summary": "A credential whose attempt is reserved or settlement-uncertain gets 409 without a fresh challenge, because a second challenge could lead to a second payment.",
+ "spec": "draft-httpauth-payment-01 §4.2; draft-evm-charge-00",
+ "tests": ["tests/integration/mpp-carriers.test.ts"]
+ },
+ {
+ "summary": "With `paymentFlow: authorization`, the backend runs before the transfer, which the charge intent counts as partial access before payment. The default, `upfront`, settles first.",
+ "spec": "draft-payment-intent-charge-00",
+ "tests": ["tests/e2e/payment/mpp-settlement.e2e.test.ts"]
+ }
+ ],
+ "combinations": [
+ {
+ "surface": "http",
+ "method": "mpp",
+ "level": "e2e",
+ "evidence": "tests/e2e/payment/mpp-settlement.e2e.test.ts"
+ },
+ {
+ "surface": "http",
+ "method": "mpp",
+ "authorization": "ap2",
+ "level": "e2e",
+ "evidence": "tests/e2e/authorization/ap2-mpp.e2e.test.ts"
+ },
+ {
+ "surface": "mcp",
+ "method": "mpp",
+ "level": "integration",
+ "evidence": "tests/integration/mcp-payment-bindings.test.ts"
+ },
+ {
+ "surface": "a2a",
+ "method": "mpp",
+ "level": "integration",
+ "evidence": "tests/integration/mpp-carriers.test.ts"
+ },
+ {
+ "surface": "http",
+ "method": "mpp",
+ "level": "testnet",
+ "evidence": "tests/testnet/mpp-base-sepolia.smoke.test.ts"
+ },
+ {
+ "surface": "http",
+ "method": "mpp",
+ "level": "mainnet",
+ "evidence": "tests/mainnet/mpp-base.smoke.test.ts"
+ }
+ ],
+ "gaps": [
+ {
+ "requirement": "Each challenge id is single-use (charge intent); two payers can each settle against one challenge",
+ "state": "open"
+ },
+ {
+ "requirement": "Payment-Receipt only after an on-chain receipt with a matching Transfer log; the gateway trusts the facilitator's settle result",
+ "state": "open"
+ }
+ ],
+ "docs": ["docs/protocols/mpp.md"]
+}
diff --git a/src/support/x402.json b/src/support/x402.json
new file mode 100644
index 0000000..4286bf1
--- /dev/null
+++ b/src/support/x402.json
@@ -0,0 +1,138 @@
+{
+ "name": "x402",
+ "kind": "payment",
+ "title": "x402",
+ "status": "supported",
+ "role": "Payment rail, carried by HTTP, MCP and A2A.",
+ "subset": "`exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding",
+ "spec": {
+ "revisions": ["v2"],
+ "display": "x402 v2",
+ "source": {
+ "repo": "x402-foundation/x402",
+ "commit": "51a0664c2b7826e3cb02595481eb6848a1b11815"
+ },
+ "stable": null,
+ "statement": "Protocol Version: 2",
+ "checked": "2026-11-17"
+ },
+ "packages": [
+ { "name": "@x402/core", "use": "runtime" },
+ { "name": "@x402/evm", "use": "runtime" },
+ { "name": "@x402/svm", "use": "runtime" },
+ { "name": "@x402/near", "use": "runtime" },
+ { "name": "@x402/mcp", "use": "test" }
+ ],
+ "artifacts": [],
+ "features": [
+ { "name": "exact-evm", "status": "supported" },
+ { "name": "exact-svm", "status": "supported" },
+ { "name": "exact-near", "status": "partial" },
+ { "name": "local-facilitator", "status": "supported" },
+ { "name": "remote-facilitator", "status": "supported" },
+ { "name": "eip-3009", "status": "supported" },
+ { "name": "permit2", "status": "supported" },
+ { "name": "caip-2", "status": "supported" },
+ { "name": "mode=local", "status": "supported" },
+ { "name": "mode=testnet", "status": "supported" },
+ { "name": "mode=mainnet", "status": "supported" },
+ { "name": "authorization-flow", "status": "supported" },
+ { "name": "upfront-flow", "status": "supported" },
+ { "name": "multiple-offers", "status": "partial" },
+ {
+ "name": "erc-8409-quotes",
+ "status": "experimental",
+ "spec": {
+ "revisions": ["0ee33230"],
+ "display": "draft `SergeevDmitry/ERCs@0ee33230`",
+ "source": {
+ "repo": "SergeevDmitry/ERCs",
+ "commit": "0ee33230ca9f9f41a714382552a47cd860465ca7"
+ },
+ "stable": false,
+ "statement": "status: Draft",
+ "checked": "2026-11-17"
+ },
+ "title": "ERC-8409",
+ "role": "x402 feature: EIP-712 signed quotes on the EVM offers of a challenge.",
+ "subset": "signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce`"
+ },
+ { "name": "public-resource-url", "status": "experimental" },
+ { "name": "bazaar", "status": "experimental" }
+ ],
+ "exclusions": [
+ { "name": "permit2 gas sponsoring extensions" },
+ { "name": "upto scheme" },
+ { "name": "batch-settlement scheme" },
+ { "name": "auth-capture scheme" },
+ {
+ "name": "x402 v1",
+ "note": "A payload declaring an `x402Version` other than 2 is refused as `invalid_x402_version` on every carrier."
+ },
+ { "name": "payer-bound quotes", "feature": "erc-8409-quotes" },
+ {
+ "name": "contract quote issuers (ERC-1271, ERC-6492, EIP-7702 delegates)",
+ "feature": "erc-8409-quotes"
+ },
+ {
+ "name": "quote consumption, single-use enforcement or revocation",
+ "feature": "erc-8409-quotes"
+ },
+ { "name": "quote client nonces", "feature": "erc-8409-quotes" },
+ { "name": "quotes for MPP, Solana or NEAR", "feature": "erc-8409-quotes" },
+ {
+ "name": "signed receipts and the x402 offer-receipt extension",
+ "feature": "erc-8409-quotes"
+ },
+ { "name": "remote quote signers and KMS", "feature": "erc-8409-quotes" },
+ { "name": "per-resource quote toggles", "feature": "erc-8409-quotes" }
+ ],
+ "deviations": [],
+ "combinations": [
+ {
+ "surface": "http",
+ "method": "x402",
+ "level": "e2e",
+ "evidence": "tests/e2e/payment/x402-settlement.e2e.test.ts"
+ },
+ {
+ "surface": "a2a",
+ "method": "x402",
+ "level": "e2e",
+ "evidence": "tests/e2e/payment/x402-settlement.e2e.test.ts"
+ },
+ {
+ "surface": "http",
+ "method": "x402",
+ "authorization": "ap2",
+ "level": "e2e",
+ "evidence": "tests/e2e/authorization/ap2-x402.e2e.test.ts"
+ },
+ {
+ "surface": "mcp",
+ "method": "x402",
+ "level": "e2e",
+ "evidence": "tests/e2e/payment/x402-bazaar.e2e.test.ts"
+ },
+ {
+ "surface": "mcp",
+ "method": "x402",
+ "level": "integration",
+ "evidence": "tests/integration/mcp-payment-bindings.test.ts"
+ },
+ {
+ "surface": "http",
+ "method": "x402",
+ "level": "testnet",
+ "evidence": "tests/testnet/x402.smoke.test.ts"
+ },
+ {
+ "surface": "http",
+ "method": "x402",
+ "level": "mainnet",
+ "evidence": "tests/mainnet/x402.smoke.test.ts"
+ }
+ ],
+ "gaps": [],
+ "docs": ["docs/protocols/x402.md"]
+}
diff --git a/tests/e2e/payment/x402-bazaar.e2e.test.ts b/tests/e2e/payment/x402-bazaar.e2e.test.ts
new file mode 100644
index 0000000..8f9eba3
--- /dev/null
+++ b/tests/e2e/payment/x402-bazaar.e2e.test.ts
@@ -0,0 +1,393 @@
+/**
+ * Bazaar metadata during settlement on Anvil through a loopback facilitator.
+ * Its recorded `/verify` and `/settle` bodies must use the challenge's
+ * `resource` and `extensions.bazaar` when `payments.x402.bazaar` is enabled,
+ * including when the buyer alters the echoed metadata. Each purchase must
+ * move funds. With Bazaar disabled, or for MPP alongside Bazaar, the facilitator
+ * payload contains only `x402Version`, `accepted` and `payload`.
+ */
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
+import { x402Client } from '@x402/core/client';
+import type { PaymentPayload, PaymentRequired } from '@x402/core/types';
+import { registerExactEvmScheme } from '@x402/evm/exact/client';
+import { wrapMCPClientWithPayment } from '@x402/mcp';
+import { Challenge } from 'mppx';
+import { charge as clientCharge } from 'mppx/evm/client';
+import { privateKeyToAccount } from 'viem/accounts';
+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { type GatewayConfig, parseConfig } from '../../../src/config';
+import {
+ NOOP_LOGGER,
+ PAYMENT_HEADER,
+ PAYMENT_REQUIRED_HEADER,
+ PAYMENT_RESPONSE_HEADER,
+} from '../../../src/core';
+import { createGateway, type GatewayInstance } from '../../../src/gateway';
+import { createConfiguredPaymentProviders } from '../../../src/gateway/payment-providers';
+import { type AnvilHandle, deployLocalChain, startAnvil } from '../../../src/payments/x402/testing';
+import { createMcpAdapter } from '../../../src/protocols/mcp';
+import { createSqliteReceiptStore, type SqliteReceiptStore } from '../../../src/storage/receipts';
+import {
+ type LoopbackBody,
+ type LoopbackFacilitator,
+ startLoopbackFacilitator,
+} from '../../fixtures/x402/loopback-facilitator';
+import { expectRealSettlement, readBalances } from '../../fixtures/x402/settlement';
+
+const PORT = 18801;
+const NETWORK = 'eip155:31337';
+const BASE = 'https://shop.example';
+const INPUT = { city: 'Oslo' };
+const ONE_USDC = 1_000_000n;
+const THREE_KEYS = ['x402Version', 'accepted', 'payload'];
+
+type EvmChallenge = Parameters['createCredential']>[0]['challenge'];
+
+interface Stack {
+ readonly gateway: GatewayInstance;
+ readonly store: SqliteReceiptStore;
+ readonly facilitator: LoopbackFacilitator;
+ readonly url: string;
+ readonly config: GatewayConfig;
+}
+
+let anvil: AnvilHandle;
+let deployment: Awaited>;
+let withBazaar: Stack;
+let withoutBazaar: Stack;
+// Bazaar is enabled, but the facilitator does not advertise the extension
+let unlisted: Stack;
+let mcp: Client | undefined;
+
+function rawConfig(facilitatorUrl: string, bazaar: boolean): Record {
+ const facilitator = { mode: 'remote', url: facilitatorUrl, auth: { type: 'none' } };
+ const resource = (expose: string[], payments: string[]) => ({
+ name: 'Forecast',
+ description: 'Forecast for a city',
+ input: {
+ type: 'object',
+ properties: { city: { type: 'string' } },
+ required: ['city'],
+ additionalProperties: false,
+ },
+ backend: { type: 'http', method: 'POST', url: 'http://merchant.invalid/forecast' },
+ pricing: { type: 'fixed', amount: '1.00', currency: 'USDC' },
+ expose,
+ payments,
+ });
+ const domain = { assetName: deployment.assetName, assetVersion: deployment.assetVersion };
+ return {
+ version: 1,
+ merchant: { id: 'bazaar-e2e', name: 'Bazaar E2E', publicBaseUrl: BASE },
+ server: { port: 0, host: '127.0.0.1', allowedOrigins: [] },
+ storage: { receipts: { driver: 'sqlite', path: ':memory:' } },
+ protocols: { http: { enabled: true }, mcp: { enabled: true, mountPath: '/mcp' } },
+ resources: {
+ forecast: resource(['http', 'mcp'], ['x402']),
+ // MPP serves this resource because it is listed first; Bazaar metadata is omitted
+ forecast_mpp: resource(['http'], ['mpp', 'x402']),
+ },
+ payments: {
+ x402: {
+ enabled: true,
+ network: NETWORK,
+ rpcUrl: anvil.rpcUrl,
+ asset: deployment.asset,
+ ...domain,
+ assetDecimals: deployment.assetDecimals,
+ payTo: deployment.merchant.address,
+ maxTimeoutSeconds: 120,
+ facilitator,
+ ...(bazaar ? { publicResourceUrl: true, bazaar: { enabled: true } } : {}),
+ },
+ mpp: {
+ enabled: true,
+ network: NETWORK,
+ rpcUrl: anvil.rpcUrl,
+ asset: deployment.asset,
+ ...domain,
+ recipient: deployment.merchant.address,
+ realm: 'shop.example',
+ challengeSecret: 'bazaar-e2e-challenge-secret'.padEnd(32, 'x'),
+ facilitator,
+ },
+ },
+ };
+}
+
+async function startStack(bazaar: boolean, extensions: string[] = ['bazaar']): Promise {
+ const facilitator = await startLoopbackFacilitator({
+ evm: {
+ chains: [{ network: NETWORK, rpcUrl: anvil.rpcUrl }],
+ signerPrivateKey: deployment.facilitator.privateKey,
+ },
+ extensions,
+ });
+ const config = parseConfig(rawConfig(facilitator.url, bazaar), {});
+ const store = createSqliteReceiptStore({ path: ':memory:', logger: NOOP_LOGGER });
+ await store.init();
+ const gateway = await createGateway({
+ config,
+ store,
+ paymentProviders: await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER),
+ protocolAdapters: [createMcpAdapter()],
+ logger: NOOP_LOGGER,
+ backend: {
+ async call() {
+ return { status: 200, body: { forecast: 'sun' }, headers: {}, durationMs: 1 };
+ },
+ },
+ });
+ const { url } = await gateway.listen();
+ return { gateway, store, facilitator, url, config };
+}
+
+function invoke(stack: Stack, id: string, headers: Record = {}) {
+ return stack.gateway.server.inject({
+ method: 'POST',
+ url: `/api/resources/${id}/invoke`,
+ headers: { host: new URL(BASE).host, 'content-type': 'application/json', ...headers },
+ payload: INPUT,
+ });
+}
+
+const decode = (value: unknown): Record =>
+ JSON.parse(Buffer.from(String(value), 'base64').toString('utf8'));
+
+const encode = (proof: PaymentPayload) => Buffer.from(JSON.stringify(proof)).toString('base64');
+
+function buyer(): x402Client {
+ const client = new x402Client();
+ registerExactEvmScheme(client, {
+ signer: privateKeyToAccount(deployment.buyer.privateKey),
+ networks: [NETWORK],
+ });
+ client.setSpendControls(false);
+ return client;
+}
+
+async function httpChallenge(stack: Stack): Promise {
+ const unpaid = await invoke(stack, 'forecast');
+ expect(unpaid.statusCode).toBe(402);
+ return decode(unpaid.headers[PAYMENT_REQUIRED_HEADER]) as unknown as PaymentRequired;
+}
+
+function balances() {
+ return readBalances({
+ rpcUrl: anvil.rpcUrl,
+ asset: deployment.asset,
+ buyer: deployment.buyer.address,
+ merchant: deployment.merchant.address,
+ });
+}
+
+// Run a purchase, verify its balance changes and receipt transaction, then
+// return the facilitator request bodies it produced
+async function purchase(
+ stack: Stack,
+ pay: () => Promise,
+ provider: 'x402' | 'mpp' = 'x402',
+): Promise {
+ const from = stack.facilitator.bodies.length;
+ const before = await balances();
+
+ await pay();
+
+ const [receipt] = await stack.store.listReceipts({ limit: 1 });
+ expect(receipt?.payment).toMatchObject({ provider, status: 'settled' });
+ await expectRealSettlement({
+ rpcUrl: anvil.rpcUrl,
+ asset: deployment.asset,
+ buyer: deployment.buyer.address,
+ merchant: deployment.merchant.address,
+ before,
+ after: await balances(),
+ amountBaseUnits: ONE_USDC,
+ txHash: receipt?.payment?.externalReference as string,
+ });
+ return stack.facilitator.bodies.slice(from);
+}
+
+async function payHttp(stack: Stack, proof: PaymentPayload): Promise {
+ const paid = await invoke(stack, 'forecast', { [PAYMENT_HEADER]: encode(proof) });
+ expect(paid.statusCode).toBe(200);
+ expect(paid.json()).toEqual({ forecast: 'sun' });
+ return String(decode(paid.headers[PAYMENT_RESPONSE_HEADER])['transaction']);
+}
+
+const payloads = (bodies: LoopbackBody[]) => bodies.map(({ body }) => body['paymentPayload']);
+
+beforeAll(async () => {
+ anvil = await startAnvil({ port: PORT, silent: true });
+ deployment = await deployLocalChain({ rpcUrl: anvil.rpcUrl, buyerInitialBalance: '10.00' });
+ withBazaar = await startStack(true);
+ withoutBazaar = await startStack(false);
+ unlisted = await startStack(true, []);
+}, 180_000);
+
+afterEach(async () => {
+ await mcp?.close().catch(() => {});
+ mcp = undefined;
+});
+
+afterAll(async () => {
+ for (const stack of [withBazaar, withoutBazaar, unlisted]) {
+ await stack?.gateway.close().catch(() => {});
+ await stack?.store.close().catch(() => {});
+ await stack?.facilitator.close();
+ }
+ await anvil?.stop();
+});
+
+describe('x402 Bazaar metadata - real local chain', () => {
+ it('HTTP: settles, and the facilitator verifies and settles with the 402 resource and metadata', async () => {
+ const required = await httpChallenge(withBazaar);
+ expect(required.resource.url).toBe(`${BASE}/api/resources/forecast/invoke`);
+ expect(Object.keys(required.extensions ?? {})).toEqual(['bazaar']);
+ const proof = await buyer().createPaymentPayload(required);
+ let transaction = '';
+
+ const bodies = await purchase(withBazaar, async () => {
+ transaction = await payHttp(withBazaar, proof);
+ });
+
+ expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']);
+ for (const payload of payloads(bodies)) {
+ expect(payload).toEqual({
+ x402Version: 2,
+ accepted: required.accepts[0],
+ payload: proof.payload,
+ resource: required.resource,
+ extensions: { bazaar: required.extensions?.['bazaar'] },
+ });
+ }
+ const [receipt] = await withBazaar.store.listReceipts({ limit: 1 });
+ expect(receipt?.payment?.externalReference).toBe(transaction);
+ });
+
+ it('HTTP: an altered echo changes nothing the facilitator receives', async () => {
+ const required = await httpChallenge(withBazaar);
+ const proof = await buyer().createPaymentPayload(required);
+ const altered: PaymentPayload = {
+ ...proof,
+ resource: {
+ ...(proof.resource as PaymentRequired['resource']),
+ description: 'Free money',
+ },
+ extensions: {
+ bazaar: { info: { input: { type: 'http', body: { poisoned: true } } } },
+ 'payment-identifier': { info: { id: 'pay_1234567890abcdef' } },
+ eip2612GasSponsoring: { info: { signature: '0x00' } },
+ },
+ };
+
+ const bodies = await purchase(withBazaar, async () => {
+ await payHttp(withBazaar, altered);
+ });
+
+ expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']);
+ for (const payload of payloads(bodies)) {
+ expect(payload).toEqual({
+ x402Version: 2,
+ accepted: required.accepts[0],
+ payload: proof.payload,
+ resource: required.resource,
+ extensions: { bazaar: required.extensions?.['bazaar'] },
+ });
+ }
+ });
+
+ it('MCP: an @x402/mcp client settles, and the facilitator gets the MCP challenge metadata', async () => {
+ mcp = new Client({ name: 'bazaar-e2e-buyer', version: '0.0.0-test' });
+ await mcp.connect(
+ new StreamableHTTPClientTransport(new URL(`${withBazaar.url}/mcp`)) as Transport,
+ );
+ const challenged = (await mcp.callTool({
+ name: 'forecast',
+ arguments: INPUT,
+ })) as CallToolResult;
+ const required = challenged.structuredContent as unknown as PaymentRequired;
+ expect(required.resource.url).toBe(`${BASE}/mcp`);
+ expect(Object.keys(required.extensions ?? {})).toEqual(['bazaar']);
+
+ const bodies = await purchase(withBazaar, async () => {
+ const result = await wrapMCPClientWithPayment(mcp as Client, buyer(), {
+ autoPayment: true,
+ }).callTool('forecast', INPUT);
+ expect(result.paymentMade).toBe(true);
+ expect(result.isError).not.toBe(true);
+ });
+
+ expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']);
+ for (const payload of payloads(bodies) as Record[]) {
+ expect(Object.keys(payload)).toEqual([...THREE_KEYS, 'resource', 'extensions']);
+ expect(payload['resource']).toEqual(required.resource);
+ expect(payload['extensions']).toEqual({ bazaar: required.extensions?.['bazaar'] });
+ }
+ });
+
+ it('feature off: settles with only x402Version, accepted and payload sent', async () => {
+ const required = await httpChallenge(withoutBazaar);
+ expect(required).not.toHaveProperty('extensions');
+ const proof = await buyer().createPaymentPayload(required);
+
+ const bodies = await purchase(withoutBazaar, async () => {
+ await payHttp(withoutBazaar, proof);
+ });
+
+ expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']);
+ for (const payload of payloads(bodies) as Record[]) {
+ expect(Object.keys(payload)).toEqual(THREE_KEYS);
+ }
+ });
+
+ it('facilitator without the extension: settles with the metadata in the 402 and none sent', async () => {
+ const required = await httpChallenge(unlisted);
+ expect(Object.keys(required.extensions ?? {})).toEqual(['bazaar']);
+ const proof = await buyer().createPaymentPayload(required);
+
+ const bodies = await purchase(unlisted, async () => {
+ await payHttp(unlisted, proof);
+ });
+
+ expect(unlisted.facilitator.requests).toContain('GET /supported');
+ expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']);
+ for (const payload of payloads(bodies) as Record[]) {
+ expect(Object.keys(payload)).toEqual(THREE_KEYS);
+ }
+ });
+
+ it('MPP beside Bazaar: settles with only x402Version, accepted and payload sent', async () => {
+ // Config omits the x402 URL and metadata because MPP serves this resource
+ expect(withBazaar.config.payments.x402?.resourceBazaar).not.toHaveProperty('forecast_mpp');
+ expect(withBazaar.config.payments.x402?.resourceUrls).not.toHaveProperty('forecast_mpp');
+ const bodies = await purchase(
+ withBazaar,
+ async () => {
+ const unpaid = await invoke(withBazaar, 'forecast_mpp');
+ expect(unpaid.statusCode).toBe(402);
+ expect(unpaid.headers[PAYMENT_REQUIRED_HEADER]).toBeUndefined();
+ const challenge = Challenge.deserialize(String(unpaid.headers['www-authenticate']));
+ const credential = await clientCharge({
+ account: privateKeyToAccount(deployment.buyer.privateKey),
+ authorization: { name: deployment.assetName, version: deployment.assetVersion },
+ }).createCredential({ challenge: challenge as unknown as EvmChallenge, context: {} });
+
+ const paid = await invoke(withBazaar, 'forecast_mpp', {
+ authorization: String(credential),
+ });
+
+ expect(paid.statusCode).toBe(200);
+ },
+ 'mpp',
+ );
+
+ expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']);
+ for (const payload of payloads(bodies) as Record[]) {
+ expect(Object.keys(payload)).toEqual(THREE_KEYS);
+ }
+ });
+});
diff --git a/tests/fixtures/mcp-registry/2025-12-11/server.schema.json b/tests/fixtures/mcp-registry/2025-12-11/server.schema.json
new file mode 100644
index 0000000..9f6469b
--- /dev/null
+++ b/tests/fixtures/mcp-registry/2025-12-11/server.schema.json
@@ -0,0 +1,574 @@
+{
+ "$comment": "This file is auto-generated from docs/reference/api/openapi.yaml. Do not edit manually. Run 'make generate-schema' to update.",
+ "$id": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "$ref": "#/definitions/ServerDetail",
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "Argument": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/PositionalArgument"
+ },
+ {
+ "$ref": "#/definitions/NamedArgument"
+ }
+ ],
+ "description": "Warning: Arguments construct command-line parameters that may contain user-provided input. This creates potential command injection risks if clients execute commands in a shell environment. For example, a malicious argument value like ';rm -rf ~/Development' could execute dangerous commands. Clients should prefer non-shell execution methods (e.g., posix_spawn) when possible to eliminate injection risks entirely. Where not possible, clients should obtain consent from users or agents to run the resolved command before execution."
+ },
+ "Icon": {
+ "description": "An optionally-sized icon that can be displayed in a user interface.",
+ "properties": {
+ "mimeType": {
+ "description": "Optional MIME type override if the source MIME type is missing or generic. Must be one of: image/png, image/jpeg, image/jpg, image/svg+xml, image/webp.",
+ "enum": [
+ "image/png",
+ "image/jpeg",
+ "image/jpg",
+ "image/svg+xml",
+ "image/webp"
+ ],
+ "example": "image/png",
+ "type": "string"
+ },
+ "sizes": {
+ "description": "Optional array of strings that specify sizes at which the icon can be used. Each string should be in WxH format (e.g., '48x48', '96x96') or 'any' for scalable formats like SVG. If not provided, the client should assume that the icon can be used at any size.",
+ "examples": [
+ [
+ "48x48",
+ "96x96"
+ ],
+ [
+ "any"
+ ]
+ ],
+ "items": {
+ "pattern": "^(\\d+x\\d+|any)$",
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "src": {
+ "description": "A standard URI pointing to an icon resource. Must be an HTTPS URL. Consumers SHOULD take steps to ensure URLs serving icons are from the same domain as the server or a trusted domain. Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain executable JavaScript.",
+ "example": "https://example.com/icon.png",
+ "format": "uri",
+ "maxLength": 255,
+ "type": "string"
+ },
+ "theme": {
+ "description": "Optional specifier for the theme this icon is designed for. 'light' indicates the icon is designed to be used with a light background, and 'dark' indicates the icon is designed to be used with a dark background. If not provided, the client should assume the icon can be used with any theme.",
+ "enum": [
+ "light",
+ "dark"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "src"
+ ],
+ "type": "object"
+ },
+ "Input": {
+ "properties": {
+ "choices": {
+ "description": "A list of possible values for the input. If provided, the user must select one of these values.",
+ "example": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "default": {
+ "description": "The default value for the input. This should be a valid value for the input. If you want to provide input examples or guidance, use the `placeholder` field instead.",
+ "type": "string"
+ },
+ "description": {
+ "description": "A description of the input, which clients can use to provide context to the user.",
+ "type": "string"
+ },
+ "format": {
+ "default": "string",
+ "description": "Specifies the input format. Supported values include `filepath`, which should be interpreted as a file on the user's filesystem.\n\nWhen the input is converted to a string, booleans should be represented by the strings \"true\" and \"false\", and numbers should be represented as decimal values.",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "filepath"
+ ],
+ "type": "string"
+ },
+ "isRequired": {
+ "default": false,
+ "type": "boolean"
+ },
+ "isSecret": {
+ "default": false,
+ "description": "Indicates whether the input is a secret value (e.g., password, token). If true, clients should handle the value securely.",
+ "type": "boolean"
+ },
+ "placeholder": {
+ "description": "A placeholder for the input to be displaying during configuration. This is used to provide examples or guidance about the expected form or content of the input.",
+ "type": "string"
+ },
+ "value": {
+ "description": "The value for the input. If this is not set, the user may be prompted to provide a value. If a value is set, it should not be configurable by end users.\n\nIdentifiers wrapped in `{curly_braces}` will be replaced with the corresponding properties from the input `variables` map. If an identifier in braces is not found in `variables`, or if `variables` is not provided, the `{curly_braces}` substring should remain unchanged.\n",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "InputWithVariables": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/Input"
+ },
+ {
+ "properties": {
+ "variables": {
+ "additionalProperties": {
+ "$ref": "#/definitions/Input"
+ },
+ "description": "A map of variable names to their values. Keys in the input `value` that are wrapped in `{curly_braces}` will be replaced with the corresponding variable values.",
+ "type": "object"
+ }
+ },
+ "type": "object"
+ }
+ ]
+ },
+ "KeyValueInput": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/InputWithVariables"
+ },
+ {
+ "properties": {
+ "name": {
+ "description": "Name of the header or environment variable.",
+ "example": "SOME_VARIABLE",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "LocalTransport": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/StdioTransport"
+ },
+ {
+ "$ref": "#/definitions/StreamableHttpTransport"
+ },
+ {
+ "$ref": "#/definitions/SseTransport"
+ }
+ ],
+ "description": "Transport protocol configuration for local/package context"
+ },
+ "NamedArgument": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/InputWithVariables"
+ },
+ {
+ "properties": {
+ "isRepeated": {
+ "default": false,
+ "description": "Whether the argument can be repeated multiple times.",
+ "type": "boolean"
+ },
+ "name": {
+ "description": "The flag name, including any leading dashes.",
+ "example": "--port",
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "named"
+ ],
+ "example": "named",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "name"
+ ],
+ "type": "object"
+ }
+ ],
+ "description": "A command-line `--flag={value}`."
+ },
+ "Package": {
+ "properties": {
+ "environmentVariables": {
+ "description": "A mapping of environment variables to be set when running the package.",
+ "items": {
+ "$ref": "#/definitions/KeyValueInput"
+ },
+ "type": "array"
+ },
+ "fileSha256": {
+ "description": "SHA-256 hash of the package file for integrity verification. Required for MCPB packages and optional for other package types. Authors are responsible for generating correct SHA-256 hashes when creating server.json. If present, MCP clients must validate the downloaded file matches the hash before running packages to ensure file integrity.",
+ "example": "fe333e598595000ae021bd27117db32ec69af6987f507ba7a63c90638ff633ce",
+ "pattern": "^[a-f0-9]{64}$",
+ "type": "string"
+ },
+ "identifier": {
+ "description": "Package identifier - either a package name (for registries) or URL (for direct downloads)",
+ "examples": [
+ "@modelcontextprotocol/server-brave-search",
+ "https://github.com/example/releases/download/v1.0.0/package.mcpb"
+ ],
+ "type": "string"
+ },
+ "packageArguments": {
+ "description": "A list of arguments to be passed to the package's binary.",
+ "items": {
+ "$ref": "#/definitions/Argument"
+ },
+ "type": "array"
+ },
+ "registryBaseUrl": {
+ "description": "Base URL of the package registry",
+ "examples": [
+ "https://registry.npmjs.org",
+ "https://pypi.org",
+ "https://docker.io",
+ "https://api.nuget.org/v3/index.json",
+ "https://github.com",
+ "https://gitlab.com"
+ ],
+ "format": "uri",
+ "type": "string"
+ },
+ "registryType": {
+ "description": "Registry type indicating how to download packages (e.g., 'npm', 'pypi', 'oci', 'nuget', 'mcpb')",
+ "examples": [
+ "npm",
+ "pypi",
+ "oci",
+ "nuget",
+ "mcpb"
+ ],
+ "type": "string"
+ },
+ "runtimeArguments": {
+ "description": "A list of arguments to be passed to the package's runtime command (such as docker or npx). The `runtimeHint` field should be provided when `runtimeArguments` are present.",
+ "items": {
+ "$ref": "#/definitions/Argument"
+ },
+ "type": "array"
+ },
+ "runtimeHint": {
+ "description": "A hint to help clients determine the appropriate runtime for the package. This field should be provided when `runtimeArguments` are present.",
+ "examples": [
+ "npx",
+ "uvx",
+ "docker",
+ "dnx"
+ ],
+ "type": "string"
+ },
+ "transport": {
+ "$ref": "#/definitions/LocalTransport",
+ "description": "Transport protocol configuration for the package"
+ },
+ "version": {
+ "description": "Package version. Must be a specific version. Version ranges are rejected (e.g., '^1.2.3', '~1.2.3', '\u003e=1.2.3', '1.x', '1.*').",
+ "example": "1.0.2",
+ "minLength": 1,
+ "not": {
+ "const": "latest"
+ },
+ "type": "string"
+ }
+ },
+ "required": [
+ "registryType",
+ "identifier",
+ "transport"
+ ],
+ "type": "object"
+ },
+ "PositionalArgument": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/InputWithVariables"
+ },
+ {
+ "anyOf": [
+ {
+ "required": [
+ "valueHint"
+ ]
+ },
+ {
+ "required": [
+ "value"
+ ]
+ }
+ ],
+ "properties": {
+ "isRepeated": {
+ "default": false,
+ "description": "Whether the argument can be repeated multiple times in the command line.",
+ "type": "boolean"
+ },
+ "type": {
+ "enum": [
+ "positional"
+ ],
+ "example": "positional",
+ "type": "string"
+ },
+ "valueHint": {
+ "description": "An identifier for the positional argument. It is not part of the command line. It may be used by client configuration as a label identifying the argument. It is also used to identify the value in transport URL variable substitution.",
+ "example": "file_path",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ }
+ ],
+ "description": "A positional input is a value inserted verbatim into the command line."
+ },
+ "RemoteTransport": {
+ "allOf": [
+ {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/StreamableHttpTransport"
+ },
+ {
+ "$ref": "#/definitions/SseTransport"
+ }
+ ]
+ },
+ {
+ "properties": {
+ "variables": {
+ "additionalProperties": {
+ "$ref": "#/definitions/Input"
+ },
+ "description": "Configuration variables that can be referenced in URL template {curly_braces}. The key is the variable name, and the value defines the variable properties.",
+ "type": "object"
+ }
+ },
+ "type": "object"
+ }
+ ],
+ "description": "Transport protocol configuration for remote context - extends StreamableHttpTransport or SseTransport with variables"
+ },
+ "Repository": {
+ "description": "Repository metadata for the MCP server source code. Enables users and security experts to inspect the code, improving transparency.",
+ "properties": {
+ "id": {
+ "description": "Repository identifier from the hosting service (e.g., GitHub repo ID). Owned and determined by the source forge. Should remain stable across repository renames and may be used to detect repository resurrection attacks - if a repository is deleted and recreated, the ID should change. For GitHub, use: gh api repos/\u003cowner\u003e/\u003crepo\u003e --jq '.id'",
+ "example": "b94b5f7e-c7c6-d760-2c78-a5e9b8a5b8c9",
+ "type": "string"
+ },
+ "source": {
+ "description": "Repository hosting service identifier. Used by registries to determine validation and API access methods.",
+ "example": "github",
+ "type": "string"
+ },
+ "subfolder": {
+ "description": "Optional relative path from repository root to the server location within a monorepo or nested package structure. Must be a clean relative path.",
+ "example": "src/everything",
+ "type": "string"
+ },
+ "url": {
+ "description": "Repository URL for browsing source code. Should support both web browsing and git clone operations.",
+ "example": "https://github.com/modelcontextprotocol/servers",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "url",
+ "source"
+ ],
+ "type": "object"
+ },
+ "ServerDetail": {
+ "description": "Schema for a static representation of an MCP server. Used in various contexts related to discovery, installation, and configuration.",
+ "properties": {
+ "$schema": {
+ "description": "JSON Schema URI for this server.json format",
+ "example": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "format": "uri",
+ "type": "string"
+ },
+ "_meta": {
+ "description": "Extension metadata using reverse DNS namespacing for vendor-specific data",
+ "properties": {
+ "io.modelcontextprotocol.registry/publisher-provided": {
+ "additionalProperties": true,
+ "description": "Publisher-provided metadata for downstream registries",
+ "example": {
+ "buildInfo": {
+ "commit": "abc123def456",
+ "pipelineId": "build-789",
+ "timestamp": "2023-12-01T10:30:00Z"
+ },
+ "tool": "publisher-cli",
+ "version": "1.2.3"
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "description": {
+ "description": "Clear human-readable explanation of server functionality. Should focus on capabilities, not implementation details.",
+ "example": "MCP server providing weather data and forecasts via OpenWeatherMap API",
+ "maxLength": 100,
+ "minLength": 1,
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface. Clients that support rendering icons MUST support at least the following MIME types: image/png and image/jpeg (safe, universal compatibility). Clients SHOULD also support: image/svg+xml (scalable but requires security precautions) and image/webp (modern, efficient format).",
+ "items": {
+ "$ref": "#/definitions/Icon"
+ },
+ "type": "array"
+ },
+ "name": {
+ "description": "Server name in reverse-DNS format. Must contain exactly one forward slash separating namespace from server name.",
+ "example": "io.github.user/weather",
+ "maxLength": 200,
+ "minLength": 3,
+ "pattern": "^[a-zA-Z0-9.-]+/[a-zA-Z0-9._-]+$",
+ "type": "string"
+ },
+ "packages": {
+ "items": {
+ "$ref": "#/definitions/Package"
+ },
+ "type": "array"
+ },
+ "remotes": {
+ "items": {
+ "$ref": "#/definitions/RemoteTransport"
+ },
+ "type": "array"
+ },
+ "repository": {
+ "$ref": "#/definitions/Repository",
+ "description": "Optional repository metadata for the MCP server source code. Recommended for transparency and security inspection."
+ },
+ "title": {
+ "description": "Optional human-readable title or display name for the MCP server. MCP subregistries or clients MAY choose to use this for display purposes.",
+ "example": "Weather API",
+ "maxLength": 100,
+ "minLength": 1,
+ "type": "string"
+ },
+ "version": {
+ "description": "Version string for this server. SHOULD follow semantic versioning (e.g., '1.0.2', '2.1.0-alpha'). Equivalent of Implementation.version in MCP specification. Non-semantic versions are allowed but may not sort predictably. Version ranges are rejected (e.g., '^1.2.3', '~1.2.3', '\u003e=1.2.3', '1.x', '1.*').",
+ "example": "1.0.2",
+ "maxLength": 255,
+ "type": "string"
+ },
+ "websiteUrl": {
+ "description": "Optional URL to the server's homepage, documentation, or project website. This provides a central link for users to learn more about the server. Particularly useful when the server has custom installation instructions or setup requirements.",
+ "example": "https://modelcontextprotocol.io/examples",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "description",
+ "version"
+ ],
+ "type": "object"
+ },
+ "SseTransport": {
+ "properties": {
+ "headers": {
+ "description": "HTTP headers to include",
+ "items": {
+ "$ref": "#/definitions/KeyValueInput"
+ },
+ "type": "array"
+ },
+ "type": {
+ "description": "Transport type",
+ "enum": [
+ "sse"
+ ],
+ "example": "sse",
+ "type": "string"
+ },
+ "url": {
+ "description": "Server-Sent Events endpoint URL template. Variables in {curly_braces} are resolved based on context: In Package context, they reference argument valueHints, argument names, or environment variable names from the parent Package. In Remote context, they reference variables from the transport's 'variables' object. After variable substitution, this should produce a valid URI.",
+ "example": "https://mcp-fs.example.com/sse",
+ "pattern": "^https?://[^\\s]+$",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "url"
+ ],
+ "type": "object"
+ },
+ "StdioTransport": {
+ "properties": {
+ "type": {
+ "description": "Transport type",
+ "enum": [
+ "stdio"
+ ],
+ "example": "stdio",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "StreamableHttpTransport": {
+ "properties": {
+ "headers": {
+ "description": "HTTP headers to include",
+ "items": {
+ "$ref": "#/definitions/KeyValueInput"
+ },
+ "type": "array"
+ },
+ "type": {
+ "description": "Transport type",
+ "enum": [
+ "streamable-http"
+ ],
+ "example": "streamable-http",
+ "type": "string"
+ },
+ "url": {
+ "description": "URL template for the streamable-http transport. Variables in {curly_braces} are resolved based on context: In Package context, they reference argument valueHints, argument names, or environment variable names from the parent Package. In Remote context, they reference variables from the transport's 'variables' object. After variable substitution, this should produce a valid URI.",
+ "example": "https://api.example.com/mcp",
+ "pattern": "^https?://[^\\s]+$",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "url"
+ ],
+ "type": "object"
+ }
+ },
+ "title": "server.json defining a Model Context Protocol (MCP) server"
+}
diff --git a/tests/fixtures/x402/loopback-facilitator.ts b/tests/fixtures/x402/loopback-facilitator.ts
index 801d927..4984544 100644
--- a/tests/fixtures/x402/loopback-facilitator.ts
+++ b/tests/fixtures/x402/loopback-facilitator.ts
@@ -30,9 +30,16 @@ export interface LoopbackFacilitator {
readonly url: string;
/** Requests received as `METHOD URL`, including any query string */
readonly requests: readonly string[];
+ /** Parsed POST bodies received at `/verify` and `/settle` */
+ readonly bodies: readonly LoopbackBody[];
close(): Promise;
}
+export interface LoopbackBody {
+ readonly operation: 'verify' | 'settle';
+ readonly body: Record;
+}
+
async function readJson(req: IncomingMessage): Promise> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
@@ -62,6 +69,8 @@ export async function startLoopbackFacilitator(options: {
readonly near?: LoopbackNear;
/** Serves https with this certificate, since a mainnet gateway refuses a plain-HTTP facilitator */
readonly tls?: { readonly key: string; readonly cert: string };
+ /** Extension identifiers advertised by `/supported`; empty by default */
+ readonly extensions?: readonly string[];
}): Promise {
const chains = options.evm?.chains ?? [];
const bindings = new Map(
@@ -99,6 +108,7 @@ export async function startLoopbackFacilitator(options: {
}
const requests: string[] = [];
+ const bodies: LoopbackBody[] = [];
const handle = (req: IncomingMessage, res: ServerResponse) => {
requests.push(`${req.method} ${req.url}`);
const reply = (status: number, body: unknown) => {
@@ -114,7 +124,7 @@ export async function startLoopbackFacilitator(options: {
...chains.map(({ network }) => ({ x402Version: 2, scheme: 'exact', network })),
...sdk.flatMap((supported) => supported.kinds.filter((kind) => kind.x402Version === 2)),
],
- extensions: [],
+ extensions: options.extensions ?? [],
signers: Object.assign({}, ...sdk.map((supported) => supported.signers)),
});
return;
@@ -127,6 +137,7 @@ export async function startLoopbackFacilitator(options: {
}
readJson(req)
.then(async (body) => {
+ bodies.push({ operation, body });
const requirements = body['paymentRequirements'] as { network: string };
const payload = body['paymentPayload'] as never;
const sdkFacilitator = sdkFacilitators.get(requirements.network);
@@ -160,6 +171,7 @@ export async function startLoopbackFacilitator(options: {
return {
url: `${options.tls ? 'https' : 'http'}://127.0.0.1:${(server.address() as AddressInfo).port}`,
requests,
+ bodies,
close: () => new Promise((resolve) => server.close(() => resolve())),
};
}
diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts
index c81cff2..67d9bdb 100644
--- a/tests/integration/a2a-x402-extension.test.ts
+++ b/tests/integration/a2a-x402-extension.test.ts
@@ -3,19 +3,29 @@
* providers, the real A2A adapter, and an `@x402/core` client building the
* `PaymentPayload`. Only the facilitator HTTP client is mocked.
*/
+
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { x402Client } from '@x402/core/client';
import type { PaymentRequired } from '@x402/core/types';
import { registerExactEvmScheme } from '@x402/evm/exact/client';
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { GatewayConfig } from '../../src/config';
-import type { CanonicalRequest, CommerceResource, PaymentMethodName } from '../../src/core';
+import type {
+ CanonicalRequest,
+ CommerceResource,
+ PaymentMethodName,
+ ReceiptStore,
+} from '../../src/core';
import { createGateway, type GatewayInstance } from '../../src/gateway';
import { createMppPaymentProvider } from '../../src/payments/mpp/provider';
import { createX402PaymentProvider } from '../../src/payments/x402/provider';
import { createA2aAdapter } from '../../src/protocols/a2a';
import type { A2aAgentCard, A2aTask } from '../../src/protocols/a2a/types';
import { A2A_X402_EXTENSION_URI } from '../../src/protocols/a2a/x402-extension';
+import { createSqliteReceiptStore } from '../../src/storage/receipts';
import { createFakeStore } from '../unit/gateway/helpers';
process.env['NODE_ENV'] = 'test';
@@ -44,6 +54,16 @@ const REMOTE = {
auth: { type: 'none' },
} as const;
const buyer = privateKeyToAccount(generatePrivateKey());
+const X402_OPTIONS = {
+ network: 'eip155:31337',
+ rpcUrl: RPC_URL,
+ asset: ASSET,
+ assetName: AUTHORIZATION.name,
+ assetVersion: AUTHORIZATION.version,
+ assetDecimals: 6,
+ payTo: PAY_TO,
+ facilitator: REMOTE,
+} as const;
let gateway: GatewayInstance;
let backendCalls = 0;
@@ -90,16 +110,7 @@ beforeEach(async () => {
config: config(),
store: createFakeStore(),
paymentProviders: [
- createX402PaymentProvider({
- network: 'eip155:31337',
- rpcUrl: RPC_URL,
- asset: ASSET,
- assetName: AUTHORIZATION.name,
- assetVersion: AUTHORIZATION.version,
- assetDecimals: 6,
- payTo: PAY_TO,
- facilitator: REMOTE,
- }),
+ createX402PaymentProvider(X402_OPTIONS),
createMppPaymentProvider({
network: 'eip155:31337',
recipient: PAY_TO,
@@ -567,3 +578,83 @@ describe('an AP2 mandate sent with the x402 extension payment', () => {
expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED');
});
});
+
+describe('x402 A2A extension with the public resource URL, across a restart', () => {
+ const A2A_URL = 'http://localhost:8080/a2a';
+ let dir = '';
+ let store: ReceiptStore | undefined;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'a2a-public-url-'));
+ });
+
+ afterEach(async () => {
+ await gateway.close().catch(() => {});
+ await store?.close();
+ store = undefined;
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ // Use the shared receipt file to preserve tasks awaiting payment across boots
+ async function boot(publicUrl: boolean): Promise {
+ await gateway.close().catch(() => {});
+ await store?.close();
+ store = createSqliteReceiptStore({ path: join(dir, 'receipts.db') });
+ await store.init();
+ gateway = await createGateway({
+ config: config(),
+ store,
+ paymentProviders: [
+ createX402PaymentProvider({
+ ...X402_OPTIONS,
+ ...(publicUrl ? { resourceUrls: { x402_report: { a2a: A2A_URL } } } : {}),
+ }),
+ ],
+ protocolAdapters: [createA2aAdapter({ store })],
+ backend: {
+ async call() {
+ backendCalls++;
+ return { status: 200, body: { report: 'paid' }, headers: {}, durationMs: 1 };
+ },
+ },
+ });
+ }
+
+ const submitted = async (task: A2aTask) => ({
+ 'x402.payment.status': 'payment-submitted',
+ 'x402.payment.payload': await paymentPayload(task),
+ });
+
+ it('pays a task after a restart, its proof echoing the A2A URL, and settles once', async () => {
+ await boot(true);
+ const task = await challenged();
+ const required = task.status.message?.metadata?.['x402.payment.required'] as PaymentRequired;
+ expect(required.resource.url).toBe(A2A_URL);
+ const metadata = await submitted(task);
+
+ await boot(true);
+ const { body } = await rpc(pay(task, metadata));
+
+ expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED');
+ expect(backendCalls).toBe(1);
+ expect(facilitator.settle).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses a task challenged before the URL was turned on, and settles nothing', async () => {
+ await boot(false);
+ const task = await challenged();
+ const metadata = await submitted(task);
+
+ await boot(true);
+ const { body } = await rpc(pay(task, metadata));
+
+ expect(body.result?.task.status.state).toBe('TASK_STATE_FAILED');
+ expect(body.result?.task.status.message?.metadata).toMatchObject({
+ 'x402.payment.status': 'payment-failed',
+ 'x402.payment.error': 'invalid_payment_requirements',
+ });
+ expect(backendCalls).toBe(0);
+ expect(facilitator.verify).not.toHaveBeenCalled();
+ expect(facilitator.settle).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/integration/baseline-goldens.test.ts b/tests/integration/baseline-goldens.test.ts
new file mode 100644
index 0000000..453fdc8
--- /dev/null
+++ b/tests/integration/baseline-goldens.test.ts
@@ -0,0 +1,511 @@
+/**
+ * 2.7.2 baseline for x402 challenges over HTTP, MCP and A2A, remote facilitator
+ * request bodies, the well-known document and a healthy `doctor --json` report.
+ *
+ * Keep challenge and facilitator request bytes unchanged when 2.8.0 options are
+ * disabled. If a change alters a golden, update its file in the same commit and
+ * explain why.
+ *
+ * The gateway uses the provider and adapter setup from `runGateway`. One loopback
+ * server fakes the JSON-RPC nodes, remote facilitator and merchant backend.
+ */
+import { createServer, type IncomingMessage, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
+import { privateKeyToAccount } from 'viem/accounts';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { createAp2AuthorizationProvider } from '../../src/authorization/ap2';
+import { printDoctorReport, runDoctor } from '../../src/cli/commands/doctor';
+import { type GatewayConfig, parseConfig } from '../../src/config';
+import { NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_REQUIRED_HEADER } from '../../src/core';
+import { createGateway } from '../../src/gateway';
+import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers';
+import { createPaymentProof } from '../../src/payments/x402/client';
+import { createA2aAdapter } from '../../src/protocols/a2a';
+import { A2A_X402_EXTENSION_URI } from '../../src/protocols/a2a/x402-extension';
+import { createAcpAdapter } from '../../src/protocols/acp';
+import { createMcpAdapter } from '../../src/protocols/mcp';
+import { createSqliteReceiptStore } from '../../src/storage/receipts';
+import { PACKAGE_VERSION } from '../../src/version';
+import { createParties } from '../unit/authorization-ap2/fixtures';
+import { createCapturingIo } from '../unit/cli/fixtures';
+
+process.env['NODE_ENV'] = 'test';
+
+const BASE_SEPOLIA = 'eip155:84532';
+const ARBITRUM_SEPOLIA = 'eip155:421614';
+const PAY_TO = '0x1111111111111111111111111111111111111111';
+// Anvil account 2. LOCAL DEVELOPMENT ONLY - DO NOT FUND
+const BUYER_KEY = '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a' as const;
+const BUYER = privateKeyToAccount(BUYER_KEY).address;
+// A fixed nonce and validity window keep the signature and payment payload deterministic
+const NONCE = `0x${'42'.repeat(32)}` as const;
+const VALID_BEFORE = 4_102_444_800;
+const TX = `0x${'ab'.repeat(32)}`;
+const GOLDEN = './goldens/2.7.2';
+
+// Capture raw facilitator request bodies by route
+const facilitatorBodies: Record = { verify: [], settle: [] };
+let upstream: Server;
+let upstreamUrl = '';
+
+async function readBody(req: IncomingMessage): Promise {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(chunk as Buffer);
+ return Buffer.concat(chunks).toString('utf8');
+}
+
+// Use the chain ID from the RPC path and report code at any address.
+// Return 6 for eth_call to satisfy the token decimals health check.
+function rpcResult(chainId: number, method: string): unknown {
+ if (method === 'eth_chainId') return `0x${chainId.toString(16)}`;
+ if (method === 'eth_getCode') return '0x6080';
+ if (method === 'eth_call') return `0x${'6'.padStart(64, '0')}`;
+ return undefined;
+}
+
+function startUpstream(): Promise {
+ upstream = createServer(async (req, res) => {
+ const body = await readBody(req);
+ const path = req.url ?? '';
+ const reply = (value: unknown) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+ };
+ const rpc = /^\/rpc\/(\d+)$/.exec(path);
+ if (rpc) {
+ const { id, method } = JSON.parse(body) as { id: number; method: string };
+ const result = rpcResult(Number(rpc[1]), method);
+ reply(
+ result === undefined
+ ? { jsonrpc: '2.0', id, error: { code: -32601, message: `no ${method}` } }
+ : { jsonrpc: '2.0', id, result },
+ );
+ return;
+ }
+ if (path === '/facilitator/supported') {
+ reply({
+ kinds: [BASE_SEPOLIA, ARBITRUM_SEPOLIA].map((network) => ({
+ x402Version: 2,
+ scheme: 'exact',
+ network,
+ })),
+ extensions: [],
+ signers: {},
+ });
+ return;
+ }
+ if (path === '/facilitator/verify') {
+ facilitatorBodies['verify']?.push(body);
+ reply({ isValid: true, payer: BUYER });
+ return;
+ }
+ if (path === '/facilitator/settle') {
+ facilitatorBodies['settle']?.push(body);
+ reply({ success: true, transaction: TX, network: BASE_SEPOLIA, payer: BUYER });
+ return;
+ }
+ if (path.startsWith('/backend/')) {
+ reply({ ok: true });
+ return;
+ }
+ res.writeHead(404).end();
+ });
+ return new Promise((resolve) =>
+ upstream.listen(0, '127.0.0.1', () => {
+ upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
+ resolve();
+ }),
+ );
+}
+
+const pathInput = {
+ type: 'object',
+ properties: { checkout_session_id: { type: 'string' } },
+ required: ['checkout_session_id'],
+ additionalProperties: false,
+};
+const bodyInput = { type: 'object', additionalProperties: true };
+
+// Define a free checkout operation exposed only through ACP
+function acpResource(method: string, path: string, withPath: boolean, withBody: boolean) {
+ return {
+ name: `ACP ${method} ${path}`,
+ input: {
+ type: 'object',
+ properties: {
+ ...(withPath ? { path: pathInput } : {}),
+ ...(withBody ? { body: bodyInput } : {}),
+ },
+ required: withPath ? ['path'] : ['body'],
+ additionalProperties: false,
+ },
+ backend: {
+ type: 'http',
+ method,
+ url: `${upstreamUrl}/backend${path}`,
+ inputBindings: {
+ ...(withPath ? { path: 'path' } : {}),
+ ...(withBody ? { body: 'body' } : {}),
+ },
+ },
+ pricing: { type: 'free' },
+ expose: ['acp'],
+ };
+}
+
+// Configure HTTP, MCP, A2A and ACP with x402, MPP and AP2 using the 2.7.2 config format
+async function goldenConfig(x402: Record): Promise {
+ const parties = await createParties();
+ const session = '/checkout_sessions/{checkout_session_id}';
+ return parseConfig(
+ {
+ version: 1,
+ merchant: {
+ id: 'golden-store',
+ name: 'Golden Store',
+ publicBaseUrl: 'https://gateway.example',
+ },
+ server: { port: 8080, host: '127.0.0.1' },
+ storage: { receipts: { driver: 'sqlite', path: ':memory:' } },
+ protocols: {
+ http: { enabled: true },
+ mcp: { enabled: true, mountPath: '/mcp' },
+ a2a: { enabled: true, mountPath: '/a2a' },
+ acp: {
+ enabled: true,
+ mountPath: '/acp',
+ auth: { type: 'bearer', token: 'golden-acp-token' },
+ idempotency: { retentionHours: 24 },
+ checkout: {
+ operations: {
+ createCheckoutSession: 'acp_create',
+ updateCheckoutSession: 'acp_update',
+ getCheckoutSession: 'acp_get',
+ completeCheckoutSession: 'acp_complete',
+ cancelCheckoutSession: 'acp_cancel',
+ },
+ },
+ },
+ },
+ resources: {
+ market_report: {
+ name: 'Market Report',
+ description: 'Latest market analysis for a symbol.',
+ input: {
+ type: 'object',
+ properties: { symbol: { type: 'string' } },
+ required: ['symbol'],
+ additionalProperties: false,
+ },
+ backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/report` },
+ pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' },
+ expose: ['http', 'mcp', 'a2a'],
+ payments: ['x402'],
+ },
+ // Require AP2 on a resource to keep doctor from warning that AP2 is unused
+ ap2_report: {
+ name: 'Mandated Report',
+ input: { type: 'object', properties: {}, additionalProperties: false },
+ backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/ap2-report` },
+ pricing: { type: 'fixed', amount: '0.02', currency: 'USDC' },
+ expose: ['http'],
+ payments: ['x402'],
+ authorization: { required: ['ap2'] },
+ },
+ mpp_report: {
+ name: 'MPP Report',
+ input: { type: 'object', properties: {}, additionalProperties: false },
+ backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/mpp-report` },
+ pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' },
+ expose: ['http'],
+ payments: ['mpp'],
+ },
+ acp_create: acpResource('POST', '/checkout_sessions', false, true),
+ acp_update: acpResource('POST', session, true, true),
+ acp_get: acpResource('GET', session, true, false),
+ acp_complete: acpResource('POST', `${session}/complete`, true, true),
+ acp_cancel: acpResource('POST', `${session}/cancel`, true, true),
+ },
+ payments: {
+ x402: {
+ enabled: true,
+ facilitator: { mode: 'remote', url: `${upstreamUrl}/facilitator` },
+ maxTimeoutSeconds: 120,
+ ...x402,
+ },
+ mpp: {
+ enabled: true,
+ network: BASE_SEPOLIA,
+ rpcUrl: `${upstreamUrl}/rpc/84532`,
+ asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
+ assetName: 'USDC',
+ assetVersion: '2',
+ recipient: PAY_TO,
+ realm: 'gateway.example',
+ challengeSecret: 'golden-mpp-challenge-secret-'.padEnd(32, 'x'),
+ facilitator: { mode: 'remote', url: `${upstreamUrl}/facilitator` },
+ },
+ },
+ authorization: {
+ ap2: {
+ enabled: true,
+ specVersion: '0.2.0',
+ mode: 'direct',
+ trust: {
+ mandateIssuers: parties.mandateIssuers,
+ checkoutIssuers: parties.checkoutIssuers,
+ },
+ },
+ },
+ },
+ {},
+ );
+}
+
+function singleOffer(): Record {
+ return { network: BASE_SEPOLIA, rpcUrl: `${upstreamUrl}/rpc/84532`, payTo: PAY_TO };
+}
+
+function multiOffer(): Record {
+ return {
+ options: [
+ { network: BASE_SEPOLIA, payTo: PAY_TO },
+ { network: ARBITRUM_SEPOLIA, payTo: PAY_TO, assetTransferMethod: 'permit2' },
+ ],
+ networks: {
+ [BASE_SEPOLIA]: { rpcUrl: `${upstreamUrl}/rpc/84532` },
+ [ARBITRUM_SEPOLIA]: { rpcUrl: `${upstreamUrl}/rpc/421614` },
+ },
+ };
+}
+
+interface Running {
+ readonly url: string;
+ readonly config: GatewayConfig;
+ close(): Promise;
+}
+
+// Wire the store, providers and adapters as in `runGateway`, without signal handlers
+async function startGateway(config: GatewayConfig): Promise {
+ const store = createSqliteReceiptStore({ path: ':memory:' });
+ await store.init();
+ const paymentProviders = await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER);
+ const ap2 = config.authorization?.ap2;
+ const authorizationProviders = ap2?.enabled
+ ? [createAp2AuthorizationProvider({ config: ap2, logger: NOOP_LOGGER, store })]
+ : [];
+ const { mcp, a2a, acp } = config.protocols;
+ if (!acp.enabled) throw new Error('the golden config enables ACP');
+ const gateway = await createGateway({
+ config: { ...config, server: { ...config.server, port: 0 } },
+ store,
+ paymentProviders,
+ authorizationProviders,
+ protocolAdapters: [
+ createMcpAdapter({ mountPath: mcp.mountPath }),
+ createA2aAdapter({ mountPath: a2a.mountPath, agentName: config.merchant.name, store }),
+ createAcpAdapter({
+ mountPath: acp.mountPath,
+ token: acp.auth.token,
+ operations: acp.checkout.operations,
+ idempotency: acp.idempotency,
+ store,
+ }),
+ ],
+ logger: NOOP_LOGGER,
+ });
+ const { url } = await gateway.listen();
+ return {
+ url,
+ config,
+ async close() {
+ await gateway.close();
+ for (const provider of authorizationProviders) provider.close();
+ await store.close();
+ },
+ };
+}
+
+// Require the captured bytes to match compact or two-space-indented JSON.
+// Normalize loopback URLs, the package version and ISO timestamps for stable snapshots.
+function golden(raw: string, gatewayUrl: string): string {
+ const parsed: unknown = JSON.parse(raw);
+ const pretty = JSON.stringify(parsed, null, 2);
+ expect([JSON.stringify(parsed), pretty]).toContain(raw);
+ return `${pretty}\n`
+ .replaceAll(upstreamUrl, 'http://upstream.invalid')
+ .replaceAll(gatewayUrl, 'http://gateway.invalid')
+ .replaceAll(PACKAGE_VERSION, '')
+ .replaceAll(/"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z"/g, '""');
+}
+
+// Snapshot discovery and require a healthy `doctor --json` report from the gateway
+async function expectDiscoveryGoldens(running: Running, suffix: string): Promise {
+ const res = await fetch(`${running.url}/.well-known/agent-commerce`);
+ expect(res.status).toBe(200);
+ await expect(golden(await res.text(), running.url)).toMatchFileSnapshot(
+ `${GOLDEN}/well-known-${suffix}.json`,
+ );
+
+ const report = await runDoctor(
+ { gatewayUrl: running.url },
+ {
+ loadConfig: async () => running.config,
+ fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }),
+ hasChainDeployScript: () => false,
+ },
+ );
+ expect(report.exitCode).toBe(0);
+ expect(report.score.passed).toBe(report.score.total);
+ const io = createCapturingIo();
+ printDoctorReport(report, io, true);
+ await expect(golden(io.out.join('\n'), running.url)).toMatchFileSnapshot(
+ `${GOLDEN}/doctor-${suffix}.json`,
+ );
+}
+
+async function challengeHeader(url: string): Promise {
+ const res = await fetch(`${url}/api/resources/market_report/invoke`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ symbol: 'ETH' }),
+ });
+ expect(res.status).toBe(402);
+ const header = res.headers.get(PAYMENT_REQUIRED_HEADER);
+ if (header === null) throw new Error('no PAYMENT-REQUIRED header');
+ return Buffer.from(header, 'base64').toString('utf8');
+}
+
+beforeAll(startUpstream);
+afterAll(() => new Promise((resolve) => upstream.close(() => resolve())));
+
+describe('2.7.2 goldens: single x402 offer, every protocol, MPP and AP2', () => {
+ let running: Running;
+
+ beforeAll(async () => {
+ running = await startGateway(await goldenConfig(singleOffer()));
+ });
+ afterAll(() => running?.close());
+
+ it('the challenge in PAYMENT-REQUIRED, and the same document on MCP and A2A', async () => {
+ const raw = await challengeHeader(running.url);
+ await expect(golden(raw, running.url)).toMatchFileSnapshot(
+ `${GOLDEN}/x402-challenge-single.json`,
+ );
+ const envelope = JSON.parse(raw) as Record;
+
+ const client = new Client({ name: 'golden-client', version: '0.0.0-test' });
+ await client.connect(
+ new StreamableHTTPClientTransport(new URL(`${running.url}/mcp`)) as Transport,
+ );
+ const mcp = (await client.callTool({
+ name: 'market_report',
+ arguments: { symbol: 'ETH' },
+ })) as { isError?: boolean; structuredContent?: Record };
+ await client.close();
+ expect(mcp.isError).toBe(true);
+ for (const key of Object.keys(envelope)) {
+ expect(mcp.structuredContent?.[key]).toEqual(envelope[key]);
+ }
+
+ const a2a = await fetch(`${running.url}/a2a`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'a2a-version': '1.0',
+ 'a2a-extensions': A2A_X402_EXTENSION_URI,
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'golden',
+ method: 'SendMessage',
+ params: {
+ message: {
+ role: 'ROLE_USER',
+ messageId: 'msg-golden',
+ parts: [
+ {
+ data: { resource: 'market_report', input: { symbol: 'ETH' } },
+ mediaType: 'application/json',
+ },
+ ],
+ },
+ },
+ }),
+ });
+ const { task } = (
+ (await a2a.json()) as {
+ result: { task: { status: { message: { metadata: Record } } } };
+ }
+ ).result;
+ expect(task.status.message.metadata['x402.payment.required']).toEqual(envelope);
+ });
+
+ it('the verify and settle bodies a remote facilitator receives', async () => {
+ const envelope = JSON.parse(await challengeHeader(running.url)) as {
+ resource: unknown;
+ accepts: Record[];
+ };
+ const offer = envelope.accepts[0];
+ if (offer === undefined) throw new Error('no offer');
+ // Include the buyer's resource echo and extension to check that the gateway
+ // strips both before forwarding the payment payload to the facilitator
+ const signed = await createPaymentProof({
+ buyerPrivateKey: BUYER_KEY,
+ accepts: offer,
+ extensions: { bazaar: { info: { input: { type: 'http', method: 'GET' } } } },
+ overrides: { nonce: NONCE, validBefore: VALID_BEFORE },
+ });
+ const proof = Buffer.from(
+ JSON.stringify({
+ resource: envelope.resource,
+ ...JSON.parse(Buffer.from(signed, 'base64').toString('utf8')),
+ }),
+ ).toString('base64');
+ facilitatorBodies['verify'] = [];
+ facilitatorBodies['settle'] = [];
+
+ const paid = await fetch(`${running.url}/api/resources/market_report/invoke`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', [PAYMENT_HEADER]: proof },
+ body: JSON.stringify({ symbol: 'ETH' }),
+ });
+ expect(paid.status).toBe(200);
+
+ const [verify] = facilitatorBodies['verify'] ?? [];
+ const [settle] = facilitatorBodies['settle'] ?? [];
+ expect(facilitatorBodies['verify']).toHaveLength(1);
+ expect(facilitatorBodies['settle']).toHaveLength(1);
+ await expect(golden(verify as string, running.url)).toMatchFileSnapshot(
+ `${GOLDEN}/facilitator-verify.json`,
+ );
+ await expect(golden(settle as string, running.url)).toMatchFileSnapshot(
+ `${GOLDEN}/facilitator-settle.json`,
+ );
+ });
+
+ it('the well-known document and a healthy doctor --json report', () =>
+ expectDiscoveryGoldens(running, 'single'));
+});
+
+describe('2.7.2 goldens: two x402 offers', () => {
+ let running: Running;
+
+ beforeAll(async () => {
+ running = await startGateway(await goldenConfig(multiOffer()));
+ });
+ afterAll(() => running?.close());
+
+ it('the challenge in PAYMENT-REQUIRED', async () => {
+ const raw = await challengeHeader(running.url);
+ await expect(golden(raw, running.url)).toMatchFileSnapshot(
+ `${GOLDEN}/x402-challenge-multi.json`,
+ );
+ });
+
+ it('the well-known document and a healthy doctor --json report', () =>
+ expectDiscoveryGoldens(running, 'multi'));
+});
diff --git a/tests/integration/doctor-certainty.test.ts b/tests/integration/doctor-certainty.test.ts
new file mode 100644
index 0000000..bea7606
--- /dev/null
+++ b/tests/integration/doctor-certainty.test.ts
@@ -0,0 +1,317 @@
+/**
+ * Run `doctor` against a gateway with an unreachable RPC or facilitator, using
+ * one x402 offer, two offers and MPP; test an unreachable backend separately.
+ * Real viem and x402 SDK clients produce the errors classified by health().
+ * A released loopback port simulates a target that does not respond.
+ */
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { runDoctor } from '../../src/cli/commands/doctor';
+import type { DoctorCheck } from '../../src/cli/commands/doctor/types';
+import { type GatewayConfig, parseConfig } from '../../src/config';
+import { NOOP_LOGGER } from '../../src/core';
+import { createGateway, type GatewayInstance } from '../../src/gateway';
+import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers';
+import { createSqliteReceiptStore } from '../../src/storage/receipts';
+import { releasedPort } from '../unit/gateway/helpers';
+
+process.env['NODE_ENV'] = 'test';
+
+const BASE_SEPOLIA = 'eip155:84532';
+const ARBITRUM_SEPOLIA = 'eip155:421614';
+const PAY_TO = '0x1111111111111111111111111111111111111111';
+const USDC = '0x036CbD53842c5426634e7929541eC2318f3dCF7e';
+
+let upstream: Server;
+let upstreamUrl = '';
+// A loopback port that was bound and released: a connection to it is refused
+let silentUrl = '';
+
+// The RPC returns the chain id from its path, mock bytecode and 6 decimals.
+// `/rpc/error` returns JSON-RPC errors. The facilitator supports both networks;
+// `/denied/supported` returns 401.
+function startUpstream(): Promise {
+ upstream = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
+ req.on('end', () => {
+ const path = req.url ?? '';
+ const reply = (value: unknown, status = 200) => {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+ };
+ const rpc = /^\/rpc\/(\w+)$/.exec(path);
+ if (rpc) {
+ const { id, method } = JSON.parse(Buffer.concat(chunks).toString('utf8')) as {
+ id: number;
+ method: string;
+ };
+ const chainId = Number(rpc[1]);
+ const result =
+ method === 'eth_chainId'
+ ? `0x${chainId.toString(16)}`
+ : method === 'eth_getCode'
+ ? '0x6080'
+ : method === 'eth_call'
+ ? `0x${'6'.padStart(64, '0')}`
+ : undefined;
+ reply(
+ Number.isNaN(chainId) || result === undefined
+ ? { jsonrpc: '2.0', id, error: { code: -32601, message: `no ${method}` } }
+ : { jsonrpc: '2.0', id, result },
+ );
+ return;
+ }
+ if (path === '/facilitator/supported') {
+ reply({
+ kinds: [BASE_SEPOLIA, ARBITRUM_SEPOLIA].map((network) => ({
+ x402Version: 2,
+ scheme: 'exact',
+ network,
+ })),
+ extensions: [],
+ signers: {},
+ });
+ return;
+ }
+ if (path === '/denied/supported') {
+ reply({ error: 'unauthorized' }, 401);
+ return;
+ }
+ if (path.startsWith('/backend/')) {
+ reply({ ok: true });
+ return;
+ }
+ res.writeHead(404).end();
+ });
+ });
+ return new Promise((resolve) =>
+ upstream.listen(0, '127.0.0.1', () => {
+ upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
+ resolve();
+ }),
+ );
+}
+
+interface Targets {
+ readonly rpc?: string;
+ readonly facilitator?: string;
+ readonly backend?: string;
+}
+
+// One paid resource on the given rail; every target defaults to the healthy upstream
+function config(rail: 'x402' | 'x402-multi' | 'mpp', targets: Targets = {}): GatewayConfig {
+ const rpc = targets.rpc ?? `${upstreamUrl}/rpc/84532`;
+ const facilitator = { mode: 'remote', url: targets.facilitator ?? `${upstreamUrl}/facilitator` };
+ const x402 =
+ rail === 'x402'
+ ? { network: BASE_SEPOLIA, rpcUrl: rpc, payTo: PAY_TO }
+ : {
+ options: [
+ { network: BASE_SEPOLIA, payTo: PAY_TO },
+ { network: ARBITRUM_SEPOLIA, payTo: PAY_TO },
+ ],
+ networks: {
+ [BASE_SEPOLIA]: { rpcUrl: rpc },
+ [ARBITRUM_SEPOLIA]: { rpcUrl: `${upstreamUrl}/rpc/421614` },
+ },
+ };
+ return parseConfig(
+ {
+ version: 1,
+ merchant: { id: 'certainty', name: 'Certainty', publicBaseUrl: 'https://gateway.example' },
+ server: { port: 8080, host: '127.0.0.1' },
+ storage: { receipts: { driver: 'sqlite', path: ':memory:' } },
+ protocols: { http: { enabled: true }, mcp: { enabled: false, mountPath: '/mcp' } },
+ resources: {
+ report: {
+ name: 'Report',
+ input: { type: 'object', properties: {}, additionalProperties: false },
+ backend: {
+ type: 'http',
+ method: 'GET',
+ url: `${targets.backend ?? upstreamUrl}/backend/r`,
+ },
+ pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' },
+ expose: ['http'],
+ payments: [rail === 'mpp' ? 'mpp' : 'x402'],
+ },
+ },
+ payments:
+ rail === 'mpp'
+ ? {
+ mpp: {
+ enabled: true,
+ network: BASE_SEPOLIA,
+ rpcUrl: rpc,
+ asset: USDC,
+ assetName: 'USDC',
+ assetVersion: '2',
+ recipient: PAY_TO,
+ realm: 'gateway.example',
+ challengeSecret: 'certainty-mpp-challenge-secret-'.padEnd(32, 'x'),
+ facilitator,
+ },
+ }
+ : { x402: { enabled: true, facilitator, maxTimeoutSeconds: 120, ...x402 } },
+ },
+ {},
+ );
+}
+
+let gateway: GatewayInstance | undefined;
+
+// Start a gateway with configured payment providers, then run doctor against it
+async function doctor(gatewayConfig: GatewayConfig): Promise