[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECM44C8BZD6Y4JZDQGG65M":3,"skill-same:01M7ECM44C8BZD6Y4JZDQGG65M":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECM44C8BZD6Y4JZDQGG65M","x402-ai-gateway",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Fx402-ai-gateway\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# x402-ai-gateway\n\n# x402 AI Inference Gateway\n\nClass of work: an **OpenAI-compatible AI gateway** that charges **per call in\nUSDC on Base** via the [x402 protocol](https:\u002F\u002Fx402.gitbook.io\u002Fx402) instead of\nAPI keys \u002F subscriptions. Agents discover it via **Bazaar** (MCP-native\ndiscovery) and **x402scan**, pay with an `X-PAYMENT` header, and get a response.\nTarget user: CortexCloud (Jonathan \u002F @jonahthan433, repo\n`github.com\u002Fjonahthan433\u002FCortexCloudAPI`, container CT 105 on Proxmox `ninyi`).\n\n## Mental model\n\n```\nagent --POST \u002Fchat\u002Fcompletions, no API key--> gateway\n  gateway: no X-PAYMENT? --> 402 + PaymentRequirements JSON (accepts[])\n  agent: pays USDC on Base, sends X-PAYMENT (base64 PaymentPayload)\n  gateway: verifies+settles via CDP facilitator --> routes to Gemini\u002FGroq\u002FOpenRouter\u002FNVIDIA\n  gateway: StreamingResponse \u002F JSON, X-PAYMENT-RESPONSE header\n```\n\nNo auth beyond payment. **Current receiving (merchant) address:\n`0x311760952bd4f26b08f9d868f07bc52a16c63d62`** (changed 2026-08-02 per user;\nold `0xE816eA741a0084748DC9f2BEeB86Be6705862365` appears in older notes). All\nwallet\u002Fpayment code is HIGH-RISK; explain changes before applying; never\nsilently alter the recipient.\n\n## ⚠️ CHANGING THE RECEIVING ADDRESS (payTo) — the systemd-Environment trap\n`WALLET_ADDRESS` lives in **TWO places**: `\u002Fopt\u002FCortexCloudAPI\u002F.env` AND the\nsystemd unit `\u002Fetc\u002Fsystemd\u002Fsystem\u002Fcortexcloud.service` — the unit has the var\nin `Environment=` **twice** (lines 8–9, duplicate). pydantic-settings gives\nprocess env vars precedence over `env_file`, so editing only `.env` +\n`systemctl restart` changes NOTHING (the 402 challenge keeps serving the old\npayTo). Correct sequence:\n1. `sed -i \"s|WALLET_ADDRESS=\u003Cold>|WALLET_ADDRESS=\u003Cnew>|g\"` the unit file\n   (fixes BOTH duplicate lines), `sed` the `.env` too (keep them in sync).\n2. `systemctl daemon-reload && systemctl restart cortexcloud.service`.\n3. Verify the live challenge: `curl -X POST localhost:8000\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions -H content-type:application\u002Fjson -d '{}' | grep -oE '\"payTo\":\"[^\"]*\"'`.\n4. Confirm funds land: USDC `balanceOf(\u003Cnew>)` via `eth_call` on\n   `https:\u002F\u002Fmainnet.base.org` (`0x70a08231` + addr, 32-byte left-padded),\n   hex \u002F 1e6 = USDC. Proven: first payment to the new address = exactly 5000\n   atomic (`0x1388` = $0.005) with `POST \u002Fsettle → 200` in journalctl.\nDiagnosis shortcut when payTo looks stale despite a restart: check\n`cat \u002Fproc\u002F\u003Cuvicorn-pid>\u002Fenviron | tr '\\0' '\\n' | grep WALLET` — a baked env\nvar there proves the unit (not `.env`) is the source.\n\n### ⚠️ Deriving the REAL payTo from a CDP_WALLET_SECRET (PKCS#8 EC key)\nA `CDP_WALLET_SECRET` in `.env` is a base64 **PKCS#8 SEC1** key, and if the\nconfigured `WALLET_ADDRESS` was hand-copied from the CDP dashboard it may NOT\nmatch the key's actual address — leaving every signed challenge advertising the\nwrong recipient. Derive the truth from the key and compare before deploying:\n```python\nfrom cryptography.hazmat.primitives.serialization import load_pem_private_key\nfrom cryptography.hazmat.primitives import serialization\nfrom Crypto.Hash import keccak   # pycryptodome — NOT hashlib.sha3_256!\npem = \"-----BEGIN PRIVATE KEY-----\\n\"+secret+\"\\n-----END PRIVATE KEY-----\"\nkey = load_pem_private_key(pem.encode(), None)\npub = key.public_key().public_bytes(serialization.Encoding.X962,\n                                    serialization.PublicFormat.UncompressedPoint)\nk = keccak.new(digest_bits=256); k.update(pub[1:])   # skip 0x04 prefix byte\nderived = \"0x\" + k.hexdigest()[-40:]                  # == CDP dashboard address\n```\n**CRITICAL:** `hashlib.sha3_256` is the NIST variant and yields a DIFFERENT\naddress (I 100% got a wrong address for a second before catching it). Ethereum\nuses keccak-256 = pycryptodome `Crypto.Hash.keccak` \u002F `eth_keys`. Then keep the\nderived address in sync in BOTH `.env` AND the systemd unit (above), restart,\nand re-probe the live payTo. `cryptography` may not exist on the host — run the\nderivation inside the CT with `\u002Fopt\u002Fcortexcloud-venv\u002Fbin\u002Fpython`.\n\n## Live protocol facts (verified against x402-foundation\u002Fx402 `main`, 2026-07)\n\n- **x402 has V1 and V2.** V1 `PaymentRequirements`: `scheme, network,\n  maxAmountRequired, mimeType, payTo, asset, extra` (+ optional `resource`,\n  `recipient`). V2 uses `amount` (not `maxAmountRequired`), no `mimeType`\u002F\n  `recipient`, and a stricter `network`.\n- **The 402 response MUST carry a valid `x402Version` + a Bazaar input schema.** For\n  x402scan's `@agentcash\u002Fdiscovery` validator (`validatePaymentRequiredDetailed`), emit\n  **`x402Version: 2`** with `accepts[]` carrying `scheme, network` (CAIP-2 `eip155:8453`),\n  `asset`, `amount` (**STRING atomic USDC**, v2 uses `amount` not `maxAmountRequired`),\n  `payTo`, and `maxTimeoutSeconds`, plus `extensions.bazaar.schema.properties.input.properties.body`\n  (input schema is MANDATORY — missing it is a hard error). v1 bodies are accepted by the\n  parser but warn \"v1 not supported by agentcash\". **This v2+input-schema requirement is\n  the #1 cause of \"No valid x402 response found (HTTP 402)\"** even when the endpoint\n  already returns 402. Full shape + headless validator: `mlops\u002Fx402-pay-per-call-gateway`\n  → `references\u002Fx402scan-v2-validator.md`.\n- **`network` format:** V1 accepts any non-empty string, but the canonical \u002F\n  expected value is CAIP-2: **`eip155:8453`** (Base mainnet) or `eip155:84532`\n  (Base Sepolia). Do NOT send bare `\"base\"` — it parses but breaks discovery\n  validators. Set `X402_NETWORK=eip155:8453` for mainnet.\n- **USDC on Base contract:** `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`\n  (correct; this is what `asset` must be).\n- **`maxAmountRequired`** is a STRING of USDC atomic units (6 decimals):\n  `\"$0.005\"` → `\"5000\"`. Don't send a float.\n## CDP facilitator contract (VERIFIED 2026-08-02 — first real settlement landed)\n\n- **Client v2 header:** ONE `PAYMENT-SIGNATURE` header (base64 of `{x402Version, payload:{authorization,signature}, extensions, resource, accepted}`). Legacy `x-payment` split is DEAD — gate only on `payment-signature`.\n- **\u002Fvalidate envelope:** TOP-LEVEL `{resource, method, headers, body}`. A `{payload:{…}}` wrapper → 400 `property \"resource\" is missing`. Response: `{valid: bool, preflight: [...], simulation, statusCode}` — check `valid`, NOT `success`.\n- **\u002Fsettle envelope:** `{x402Version, paymentPayload, paymentRequirements}`. `paymentPayload` = the DECODED PAYMENT-SIGNATURE HEADER ITSELF (v2 requires `accepted`). `paymentRequirements` = `{x402Version:2, **accepted-flattened, resource, extensions}` (v2 requires `scheme` at top).\n- **Auth:** per-request ES256 JWT via `cdp.x402.x402.create_cdp_auth_headers(api_key_id, api_key_secret)()` → `{verify, settle, supported, list}` headers. cdp-sdk 1.47.1 in CT venv. Hand-rolled JWT = 401; secret is base64(32B key || 32B pub). NEVER static bearer.\n- **Bazaar preflight:** CDP validate REQUIRES `extensions.bazaar.info = {input:{type:\"http\", method, bodyType:\"json\", body:{…}}, output:{type, format, example}}` in the 402 challenge — missing it → `simulation.outcome: \"rejected\", rejectionReason: \"invalid discovery configuration\"`. All 12 other preflight checks (returns_402, x402_version, accepts[], amount ≥ $0.001, payTo, …) must stay green.\n- **Body re-injection:** middleware reads `await request.body()` for the facilitator envelope → must re-inject via `request._receive` before `call_next`, else downstream routes hang\u002Fempty.\n- **On success:** set `X-PAYMENT-RESPONSE` = base64(`{success:true, details:settle_data}`) — the 2.20 client's `processPaymentResult` reads it.\n- **E2E proof:** proxy (2.20 @x402, wallet 0xCed8…374A) → 402 → sign → validate → settle → 200 llama \"PAID\", balance −$0.001928. Restart service after deploys (systemd, CT105).\n\n## High-volume performance (S1 landed 2026-08-02 — proof cache + nonce dedup)\n\nFor throughput, do NOT call CDP validate+settle on every request. Verified design\n(live in `app\u002Fcore\u002Fcache.py` + `app\u002Fmiddleware\u002Fx402.py`):- **Proof cache:** after a successful settle, store `sha256(payment_signature)` →\n  `x402:proof:\u003Chash>` TTL **60s**. A request whose proof hash is cached skips CDP\n  entirely (still sets `X-PAYMENT-RESPONSE`). Verified: settle 3.2s → cache-hit\n  0.7s, zero CDP calls in journal.\n- **Nonce dedup:** EIP-3009 `authorization.nonce` claimed via Redis `SETNX`\n  (`x402:nonce:\u003Cnonce>`, TTL = `validBefore − now`, clamp [1, 3600]). Reject\n  402 `\"Payment nonce already used\"` BEFORE CDP. Same-proof replays ride the\n  cache (by design — that's what the cache is for); a DIFFERENT proof reusing a\n  nonce hits the gate. Since proof TTL == nonce TTL, the nonce gate only fires\n  on proof-hash-differing replays within the window — after both expire the\n  payment re-verifies (correct). Defense in depth: even if our gate lapses, CDP\n  itself rejects replayed nonces (\"authorization nonce already submitted\").\n- **FAIL-OPEN is mandatory:** every cache\u002FRedis call catches exceptions and\n  falls through to the real CDP path. A Redis outage must never block a payment.\n- Decode `payment_signature` ONCE at the top of the payment branch (it feeds the\n  cache check, nonce gate, payer address, and the settle envelope).\n- Full design + test transcript: `references\u002Fpayment-caching.md`. Replay-test\n  harness (captures a real signed header for cache\u002Fnonce testing):\n  `scripts\u002Fsign_replay.mjs` — run with `EVM_PRIVATE_KEY=0x… node sign_replay.mjs\n  > sig.txt`, then replay via curl with `-H \"payment-signature: $(cat sig.txt)\"`.\n  Gotcha: `x402HTTPClient().encodePaymentSignatureHeader(payload)` returns the\n  header key UPPERCASE `PAYMENT-SIGNATURE`, and `createPaymentPayload(challenge)`\n  is the 2.20 method that mints the payload (both confirmed against the esm dist).\n\n## S2 — connection pooling (landed 2026-08-02)\n\n`app\u002Fcore\u002Fhttp.py` — `shared_client(name, timeout, headers)` returns ONE\npersistent `httpx.AsyncClient` per (name, timeout, headers) key with\n`Limits(max_connections=50, max_keepalive_connections=20)`; never open a client\nper request. Wired into:\n- `x402\u002Fonchain_routes.py::_rpc_call` → `shared_client(\"base_rpc\", 10.0)`; RPC\n  failure responses are **503** `upstream_base_rpc` (were 502 — the 10s hard\n  timeout means httpx raises instead of hanging, so the error path is the 503).\n- `middleware\u002Fx402.py` CDP validate\u002Fsettle → `shared_client(\"cdp\", 30.0)` — 2\n  calls per fresh payment, the biggest per-request win.\nVerified: paid chat 200 via pooled client; paid `balance` GET 200 with real\ndata; unpaid 402 intact. Test harness: sign per-resource via `sign_replay.mjs`\nwith `RESOURCE=... BODY='{}'` env vars (GET routes take the signature as a\n`payment-signature` HEADER — POSTing a GET-only route → 405 Method Not Allowed).\n\n## ⚠️ Deploy pitfalls (each cost a failed deploy or a full-route outage)\n\n- **Unprivileged LXC: `pct push` cannot overwrite `nobody`-owned files.** CT\n  root maps to host uid 100000 and has no DAC-override over host-mapped files,\n  so overwriting a `nobody:nogroup` file fails with `Permission denied` while\n  the rest of the push chain silently stops. Fix: `pct exec 105 -- rm -f\n  \u003Cpath>` FIRST, then push. Check ownership with `ls -la` if a push fails.\n- **Verify imports BEFORE restarting the service.** `main.py` wraps the x402\n  router includes in a try\u002Fexcept (`Failed to initialize x402 payment gateway:\n  \u003Cerr>`), so an import-time error in a middleware\u002Froute module (e.g. a\n  module-level `await` from a mangled dedent) silently drops the ENTIRE\n  `\u002Fx402\u002Fv1` router set → everything 404s while `\u002Fopenapi.json` still lists the\n  paths (it's the static `app.openapi = lambda: _OPENAPI_SPEC` override, NOT\n  routing truth). Pre-flight: `cd \u002Fopt\u002FCortexCloudAPI &&\n  \u002Fopt\u002Fcortexcloud-venv\u002Fbin\u002Fpython -c \"import app.main\"` (and `ast.parse` the\n  file you edited) before `systemctl restart`. Post-restart check: journal\n  `--since` grep for `Failed to initialize x402 payment gateway`.\n\n## CDP n AUTH IS PER-REQUEST ES256 JWT, NOT A STATIC BEARER (verified\n  this session — the #1 settlement blocker).** The v2 facilitator REQUIRES signed\n  `Authorization` JWTs built per request via `cdp.x402.x402.create_cdp_auth_headers(\n  api_key_id, api_key_secret)`. A static `Bearer \u003CX402_FACILITATOR_API_KEY>` returns\n  **401 Unauthorized** on mainnet — real USDC CANNOT settle with a static token.\n  Correct wiring (cdp-sdk 1.47.1 installed on CT):\n  ```python\n  from cdp.x402.x402 import create_cdp_auth_headers   # NOTE: NOT cdp.x402 (not re-exported)\n  def _cdp_headers():\n      return create_cdp_auth_headers(\n          settings.X402_FACILITATOR_API_KEY_ID,\n          settings.X402_FACILITATOR_API_KEY_SECRET,\n      )()   # -> {\"verify\":{...},\"settle\":{...},\"supported\":{...},\"list\":{...}}\n  # merge per-endpoint: headers={**facilitator_headers, **_cdp_headers().get(\"verify\", {})}\n  ```\n  The signed headers carry `Authorization` (ES256 JWT) + `Correlation-Context`.\n  Config needs TWO env vars, not one: `X402_FACILITATOR_API_KEY_ID` + `_SECRET`\n  (add both to `app\u002Fcore\u002Fconfig.py`). `cdp-sdk` also upgrades `web3` to 7.x — see\n  web3-7.x note below. Verify the key works BEFORE burning buyer USDC: a quick\n  `create_cdp_auth_headers(id,secret)()` + `GET {FACILITATOR}\u002Fsupported` must return\n  **200** (proves JWT signing + key valid). Then `\u002Fverify`+`\u002Fsettle` work.\n\n- **⚠️ INGESTING THE CDP KEY THE USER PASTES — validate, never guess.** Pasted\n  secrets get mangled by chat clients: a UUID can arrive **truncated** (e.g.\n  `...c418` missing its final hex char) and Cyrillic look-alikes can replace ASCII\n  (`В`→B, `С`→C, `Е`→E, `Т`→T, `Н`→H, `х`→x) so base64 becomes invalid and a static\n  bearer fails with 401. **Never clean or guess around the corruption.** Detect\n  non-ASCII in an allegedly-ASCII secret (`any(ord(c) > 127 for c in secret)`) and\n  verify the key ID is a full 36-char UUID; if either fails, RE-REQUEST a clean copy\n  — ideally via screenshot (the CDP \"Save your API key\" screen shows the exact\n  string) or by having the user write it to a file on the CT. Confirmed this session:\n  the first paste had 6 Cyrillic chars + a truncated ID; the screenshot re-send was\n  clean and worked first try.\n- **⚠️ 402 `accepts[]` MUST carry the EIP-712 domain `extra` (verified this session).**\n  CDP's facilitator verifies the EIP-3009 signature against the USDC EIP-712 domain.\n  If `accepts[0]` omits it, settlement returns\n  `missing EIP-712 domain name\u002Fversion in requirements.extra` and the payment fails\n  (buyer USDC untouched). The challenge MUST include:\n  ```python\n  \"accepts\": [{\n      \"scheme\": \"exact\",\n      \"network\": settings.X402_NETWORK,            # eip155:8453\n      \"asset\": \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n      \"amount\": str(price_atomic),                 # STRING atomic USDC\n      \"payTo\": settings.WALLET_ADDRESS,\n      \"maxTimeoutSeconds\": 60,\n      \"extra\": {\"name\": \"USD Coin\", \"version\": \"2\"},   # REQUIRED for EIP-3009 verify\n  }]\n  ```\n  This `extra` field is separate from `extensions.bazaar.schema` and from any\n  `resource` object — all three coexist in the v2 body.\n- **⚠️ PAYMENT HEADER NAME (real interop bug, caught by the e2e test).** The x402\n  **SDK v2 client sends `PAYMENT-SIGNATURE`**, NOT `X-PAYMENT`. A middleware that\n  only reads `X-PAYMENT` rejects EVERY real SDK client (\"Invalid X-PAYMENT\n  header\"). **Accept BOTH**: `request.headers.get(\"X-PAYMENT\") or\n  request.headers.get(\"PAYMENT-SIGNATURE\")`. Also forward the challenge\n  `x402Version` (v2) into the facilitator validation body — hardcoding\n  `x402Version: 1` makes v2 payloads fail verification. Both fixes applied this\n  session; the e2e test is what exposed them, proving `discover`-clean audits\n  alone are NOT sufficient.\n- **Repo moved:** `coinbase\u002Fx402` is now a fork; canonical is\n  **`x402-foundation\u002Fx402`**. Fetch the spec from there, not training memory.\n\n## In-process proof verification (S1 hardening — do NOT trust CDP \u002Fvalidate to be your only check)\n\nDefault posture is to hand the whole `payment-signature` to the CDP facilitator\n`\u002Fverify`+`\u002Fsettle`. **That in itself is a paid-acceptance bug**: a gateway that\nonly validates via the facilitator accepts any proof the facilitator returns\n`valid` — if that external check is wrong you get free service or stolen funds. Harden\nwith a **local (in-gateway) EIP-712 `TransferAuthorization` verifier** run in the\npayment middleware BEFORE the CDP call. Checks exactly (fail-closed → any failure\nis a hard 402, never `call_next`):\n\n- **ECDSA signer recovery in-process** — `eth_account` recovers the signer from\n  and requires it equals `authorization.from`. Never\n  outsource signature verification to a third-party validator.\n- **amount ≥ required** — compare caller's paid atomic vs OUR price table (the\n  same `usd_to_usdc_atomic(price_str)` the 402 challenge carried), NEVER the\n  caller's stated price.\n- **chainId == 8453** (parse `eip155:8453` or bare int), **asset == USDC on Base\n  `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`**, **payTo == `WALLET_ADDRESS`**\n  (all before any RPC), and **expiry**: reject `validBefore` \u003C now−30s (clock\n  skew) or > now+300s (proof stockpiling).\n- **Constant-time hex compare** (`hmac.compare_digest`, lowercased) for\n  asset\u002FpayTo\u002Fhash checks — never `==` on attacker-controlled hex.\n- Keep nonce replay via Redis `SETNX` (existing) and the 60s proof cache — the\n  local verifier is additive; the CDP call still does the real on-chain settle.\n\nThe full documented fail-closed module (`app\u002Fmiddleware\u002Fpayverify.py`) with the\nEIP-712 `_AUTH_TYPES` domain\u002Fmessage and `_extract_sig` (65-byte r||s||v hex +\nv\u002Fr\u002Fs split) is in **`references\u002Fpayment-verify-inprocess.md`** — copy it.\n\n**Self-check (mandatory before relying on it):** sign a real EIP-712\nTransferAuthorization with `eth_account`, prove recover round-trips, and assert\nevery negative branch (`tests\u002Fpayverify.py` style — the session's module\n`9\u002F9`). Reuse the deployed module's own `_AUTH_TYPES` so the test and production\nsign the byte-identical struct. Two gotchas seen in practice: `HexBytes.hex()`\nalready has NO `0x` (don't `[2:]` it — corrupts bytes); a test payTo must be a\n**valid-checksum** address or ABI encoding throws (`EncodingTypeError`), so use\n`Account.create().address` for the mismatch case, not a hand-typed string.\nNet: the declarative fields compare against the server's own 402 challenge\n(guaranteed-correct); the EIP-712 struct is the ONE thing that must match the\nreal client — no signed proof in logs means the first live payment is the real\ntest, and failure is fail-closed (safe 402, not fraud).\n\n## Bazaar discovery (the priority discovery surface)\n\nBazaar is how autonomous agents find your routes — it has **native MCP support**\nagent frameworks consume directly. Higher priority than x402scan.\n\n- The **Python x402 SDK has full Bazaar parity** — `x402[extensions]` ships\n  `x402.extensions.bazaar` with `declare_discovery_extension`,\n  `declare_mcp_discovery_extension`, `resource_service`, `facilitator`. NOT\n  TS-only. Confirmed installed at v2.14.0.\n- Per route, declare: `input_schema` (JSON Schema of body fields like\n  `model`\u002F`messages`), `output=OutputConfig(example=\u003Cresponse shape>)`,\n  `description`, and `body_type=\"json\"` for POST routes. Returns\n  `{\"bazaar\": {...}}` to attach as `extensions` in a `RouteConfig`.\n- Expose an MCP endpoint (`declare_mcp_discovery_extension`) so agents call\n  directly. Keep the existing (verified) custom payment middleware for the\n  actual charging — discovery metadata is additive, doesn't touch payment flow.\n\n### Client-side MCP server (ship one — the agent-install surface)\nBazaar is programmatic discovery; agents also need a **published MCP server** they\ncan `claude mcp add` \u002F `npx`. This is the *client-side* counterpart: an MCP server\nthat exposes your gateway's tools and pays per call via x402 from the agent's own\nwallet. Building it (TS: `@modelcontextprotocol\u002Fsdk` + `@x402\u002Ffetch` +\n`@x402\u002Fevm`) is a distinct, reusable technique — full build + verification +\npitfalls in **`references\u002Fmcp-server-build.md`** (built + verified as\n`@cortexcloud\u002Fmcp`, 2026-07-12). Load-bearing lessons: lazy-init the paid fetch so\nthe free `models` tool works without a wallet key; viem needs a `0x`-prefixed key;\nimport `registerExactEvmScheme` from `@x402\u002Fevm\u002Fexact\u002Fclient` (not `@x402\u002Fevm`).\nThe install line should mirror the rival: `npx @cortexcloud\u002Fmcp`.\n\n### Client-side OpenAI-compatible proxy (the ClawRouter equivalent — volume engine)\nThe MCP server reaches MCP-aware agents only. The bigger distribution channel is a\n**local OpenAI-compatible proxy** any OpenAI-SDK app can use by flipping `base_url`.\nBlockRun's 15.45M tx came from exactly this (ClawRouter): each `npx` install\nauto-creates a self-custody buyer wallet that self-funds and pays our merchant\n`0xE816…2365` per call — that's what populates the x402scan \"buyers\" column.\nBuilt + verified as `@cortexcloud.org\u002Fproxy` (2026-07-15): esbuild build (NOT tsc —\n`ox`\u002F`viem` deep-types break tsc; the `paths` alias for `@x402\u002Fevm\u002Fexact\u002Fclient` also\nbreaks esbuild — see the recipe), runs on `:8402`, forwards `\u002Fv1\u002F*` + `\u002Fx402\u002Fv1\u002F*`,\nverified the full 402→sign→settle handshake live (failed only on unfunded wallet).\n**Route gotcha:** keyless paid endpoint is `\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`, NOT\n`\u002Fv1\u002Fchat\u002Fcompletions` (the latter needs a Bearer key). Full code, build fix,\nverification recipe, and the real-settlement options (incl. the gotcha that the\nfunded test buyer `0xCed8…374A` key is NOT persisted on CT) →\n**`references\u002Fproxy-build.md`**.\n\n### Bazaar SDK call-shape GOTCHAS (verified against x402 2.14.0 — easy to get wrong)\n- **`declare_discovery_extension` (POST\u002FJSON routes)** needs BOTH an example and a\n  schema, plus `body_type=\"json\"`:\n  ```python\n  declare_discovery_extension(\n      input={\"model\": \"gpt-4o-mini\", \"messages\": [{\"role\": \"user\", \"content\": \"hi\"}]},\n      input_schema={\"type\": \"object\", \"properties\": {\"model\": {\"type\": \"string\"}, \"messages\": {\"type\": \"array\", \"items\": {\"type\": \"object\"}}}, \"required\": [\"model\", \"messages\"]},\n      body_type=\"json\",\n      output=OutputConfig(example={\u003Cresponse shape>}),\n  )\n  ```\n  Omitting `body_type=\"json\"` produces a *query* extension (wrong for POST).\n- **`declare_mcp_discovery_extension` takes a CONFIG OBJECT, NOT kwargs.** This is\n  the #1 footgun — calling it with `tool_name=...` as kwargs FAILS (signature is\n  `(config: DeclareMcpDiscoveryConfig)`):\n  ```python\n  from x402.extensions.bazaar import DeclareMcpDiscoveryConfig, declare_mcp_discovery_extension\n  declare_mcp_discovery_extension(\n      DeclareMcpDiscoveryConfig(\n          tool_name=\"chat_completions\",\n          description=\"...\",\n          input_schema={\"type\": \"object\", \"properties\": {...}, \"required\": [...]},\n          transport=\"sse\",          # Literal[\"sse\",\"streamable-http\"] — plain string is fine\n          example={\"endpoint\": \"https:\u002F\u002F...\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions\", \"method\": \"POST\", \"payment\": \"x402 USDC on Base\"},\n      )\n  )\n  ```\n- **MCP SSE endpoint (minimal, discovery-focused):** serve `text\u002Fevent-stream`;\n  handle `initialize` → result, `tools\u002Flist` → list of `{name, description,\n  inputSchema}`, `tools\u002Fcall` → return the x402 endpoint URL + PaymentRequirements\n  (agent pays client-side; the MCP tool does NOT itself settle). `tools\u002Fcall`\n  yielding the endpoint + `maxAmountRequired`\u002F`payTo`\u002F`network` is the correct,\n  honest design for a pay-per-call gateway.\n- **Indexing requires a REAL on-chain USDC transaction** (even a tiny one). Per\n  user rule, CONFIRM before triggering the first settlement that puts a route in\n  Bazaar. **Decision record:** Jonathan chose **mainnet (`eip155:8453`) from the\n  start** for CortexCloud — do NOT default to Sepolia. Sepolia only if *he* later\n  asks for a dry-run. Set `X402_NETWORK=eip155:8453`.\n\n## Adding a provider (e.g. NVIDIA NIM) — wiring checklist\nNIM is OpenAI-compatible, so a provider is one file + 4 registry touches:\n1. `app\u002Fproviders\u002Fnvidia.py`: `class NvidiaProvider(OpenAIProvider): def __init__(self, base_url=\"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\"): super().__init__(base_url=base_url)`\n2. `app\u002Fproviders\u002F__init__.py`: import + add `\"NvidiaProvider\"` to `__all__`\n3. `app\u002Frouting\u002Frouter.py`: add `\"nvidia\": NvidiaProvider` to `PROVIDER_MAP`,\n   add `\"nvidia\": settings.NVIDIA_API_KEY` to `_get_provider_api_key`'s `key_map`,\n   and `from app.providers import ( NvidiaProvider,` at the import block.\n4. `app\u002Fcore\u002Fconfig.py`: add `NVIDIA_API_KEY: Optional[str] = Field(default=None, env=\"NVIDIA_API_KEY\")`\n5. `.env`: add `NVIDIA_API_KEY=` (empty — user pastes the real key; do NOT store it).\n- **Models are DB rows, not config.** `ModelRegistryService.create_model(name,\n  provider, provider_model_name, context_length, prompt_token_price,\n  completion_token_price, capabilities, is_active=True)` creates them. There is\n  **NO seed script** and **no admin user seeded**, so the admin REST route\n  (`\u002Fv1\u002Fadmin`) is unusable without auth. Insert model rows via a script that\n  calls `ModelRegistryService.create_model` directly. Open a session with\n  `app.database.session.AsyncSessionLocal` (NOT `async_session_factory` — that\n  name does NOT exist in this repo; the session module exports `AsyncSessionLocal`\n  and a `get_db()` generator, no `async_session_factory`). Run the script on the CT\n  with `PYTHONPATH=\u002Fopt\u002FCortexCloudAPI \u002Fopt\u002Fcortexcloud-venv\u002Fbin\u002Fpython script.py`\n  (the project root must be on sys.path or `app` won't import). This is a DB write\n  but NOT a migration (no schema change) — proportionate; verify via\n  `GET \u002Fx402\u002Fv1\u002Fmodels`.\n\n## Safe-edit pattern for a LIVE payment gateway (CT 105 via Proxmox)\n\nSee `proxmox-homelab-administration` for reaching the CT. The gateway runs under\nsystemd (`cortexcloud.service`, `uvicorn :8000`, `Restart=always`). After code\nchanges: `systemctl restart cortexcloud` — NEVER a foreground uvicorn (dies on\ndisconnect). Verify with a read-only `curl -X POST ...\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`\n→ expect HTTP 402 with the compliant JSON (no payment fires). Patch code via\nin-place Python `assert old in src; replace` (Pattern C in that skill) to avoid\nrewriting the whole file.\n\n## x402scan registration (verified against the x402scan source, 2026-07)\n\nRegistration is **not** a simple POST to a public API — read this before attempting.\n\n- The register route is `POST \u002Fapi\u002Fx402\u002Fregistry\u002Fregister` and is **protected by\n  SIWX (Sign-In with X)**. Direct API calls get rejected without a session. The\n  realistic path is the **web form** at `https:\u002F\u002Fwww.x402scan.com\u002Fresources\u002Fregister`\n  (user signs in with X, submits the origin URL). The agent can prepare everything\n  server-side but cannot complete the SIWX step.\n- x402scan uses **`@agentcash\u002Fdiscovery`** (OpenAPI-first). Its\n  `fetchDiscoveryDocument(origin)` fetches **`openapi.json` at the origin root**\n  and 404s if missing, then checks the submitted endpoint is listed in the spec.\n  So an `openapi.json` at the origin root is **mandatory** for registration.\n- **Ownership verification = `info.contact.email`** in `openapi.json`. x402scan\n  reads `contact.email` to verify origin ownership and to show a merchant contact\n  on Poncho pages. If it's absent you get a warning and can't verify. Set it to the\n  operator's real email (e.g. `ampwerajonathan50@gmail.com`).\n- The discovery lib reads the OpenAPI spec's **`x-payment-info`** per paid operation\n  (NOT a legacy `x402` extension). Required per op: `x-payment-info.price` as the\n  structured object `{mode:\"fixed\",currency:\"USD\",amount:\"0.005\"}` and\n  `x-payment-info.protocols: [{\"x402\": {}}]` (**ARRAY OF OBJECTS** — `[\"x402\"]` strings\n  triggers `L2_PROTOCOLS_MISSING_ON_PAID`), plus `responses[\"402\"]`. Free op →\n  `security: []`. The RUNTIME 402 response must be **x402 v2 with a Bazaar input\n  schema** or x402scan reports \"No valid x402 response found (HTTP 402)\". Exact body\n  shape + headless validator: see `mlops\u002Fx402-pay-per-call-gateway` →\n  `references\u002Fx402scan-v2-validator.md`.\n\n### FastAPI `\u002Fopenapi.json` SHADOWING pitfall (cost real debugging time)\nAdding `@app.get(\"\u002Fopenapi.json\")` does **NOT** override FastAPI's built-in\nauto-generated spec — FastAPI already registered `\u002Fopenapi.json` from\n`app.openapi()`, and the custom route is shadowed (the served JSON is the huge\nauto-spec listing every `\u002Fv1\u002Fdashboard\u002F*` route, NOT your curated one). Fix:\n**override the function**, don't add a route:\n```python\nimport json as _json\nwith open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), \"openapi.json\")) as _f:\n    _OPENAPI_SPEC = _json.load(_f)\napp.openapi = lambda: _OPENAPI_SPEC\n```\nPlace this right after `app = FastAPI(...)`.\n\n### Patching `main.py` tail — double-close `}` trap\nWhen appending to `main.py` by replacing the last real line (e.g. the\n`\"docs\": \"...\"` line of the `x402_discovery` return), do NOT also leave the\noriginal closing `}` in place — the file already ends with `    }` after that\nline, so inserting another `    }` before your new code leaves a **dangling\n`}`** → `SyntaxError: unmatched '}'` at startup. Either replace the whole trailing\n`\"docs\": ...\\n    }\\n` block, or post-trim any stray lone `}` at EOF. Always restart\nand `curl` the endpoint to confirm the curated spec (not the auto one) is served.\n\n## Hard rules for THIS project (user-mandated)\n\n- Ask before: DB migration, wallet\u002Fpayment-recipient change, docker-compose\n  Postgres creds, destructive git (force push \u002F history rewrite), first public\n  exposure.\n- `POSTGRES_PASSWORD` is the weak default `postgres` — FLAG it, never change\n  silently (must stay in sync with docker-compose).\n- Docker `iptables:false` is deliberate (default rules broke CT DNS). Don't\n  re-enable.\n- Home lab: no k8s \u002F service mesh \u002F heavy tooling for a single-container deploy.\n- When unsure about current x402\u002Fx402scan schema, FETCH the live docs — the\n  protocol is new and changing.\n\n## Build order (proven this session)\n\n1. **Reconcile** live container vs repo (read-only): `git status`,\n   `git log origin\u002Fmain..HEAD`, `docker ps`, `systemctl is-active cortexcloud`.\n2. **Verify x402 correctness** — 402 shape vs live spec (add `x402Version`,\n   `eip155:8453`, `resource`).\n3. **Bazaar discovery** — wrap routes with `declare_discovery_extension` + MCP.\n4. **Providers** — add NVIDIA (NIM) + confirm Groq; OpenRouter as broad fallback.\n5. **Public exposure (ask first)** — **Cloudflare Tunnel on the ninyi HOST**\n   (`\u002Fetc\u002Fcloudflared\u002Fconfig.yml`, ingress hostname-based with optional `path:`\n   matching; seen live: `\u002Fmcp*` → CT:3100 for the MCP server, default →\n   `192.168.1.15:8000` for the API). Reload with `systemctl reload cloudflared`\n   (or `restart`). User does the DNS CNAME to Cloudflare. NOT Caddy\u002Fnginx here —\n   verify the live proxy (`ss -ltnp`, `pgrep -af cloudflared`); an earlier build\n   wrongly assumed Caddy.\n6. **Listings** — x402scan.com\u002Fresources\u002Fregister (URL-based, auto-validates)\n   + Bazaar indexing (after go-ahead on the tx).\n7. **Gap analysis vs rival gateways** — benchmark against BlockRun \u002F jarvisclaw.ai\n   with `@agentcash\u002Fdiscovery` on their origin + reading their site via browser.\n   Method + BlockRun snapshot: `references\u002Fcompetitor-gap-analysis.md`.\n\n## Hardening & operations (Phase C — proven this session)\n\nAfter the gateway passes discovery, harden before adding surface area:\n\n1. **Keep `openapi.json` in sync with code.** The curated spec is a STATIC file\n   served via `app.openapi = lambda: _OPENAPI_SPEC`. If you add a route in code\n   (e.g. `\u002Fresponses`) it will NOT appear in discovery until you also add the path\n   to `openapi.json`. Re-run `npx -y @agentcash\u002Fdiscovery@latest discover` after\n   every route change to confirm the route count and zero warnings.\n2. **Per-IP rate limit on x402 routes** (protect paid endpoints from probe floods\n   without throttling legit paid traffic). Add a `BaseHTTPMiddleware` placed\n   BEFORE `X402PaymentMiddleware`, governing only `\u002Fx402\u002Fv1\u002F*`, reusing the existing\n   Redis `RateLimiter.is_rate_limited(key, limit=60, window=60)` (fail-open on Redis\n   error). Generous limit (60\u002Fmin) so a normal agent is never throttled.\n   ```python\n   class X402RateLimitMiddleware(BaseHTTPMiddleware):\n       async def dispatch(self, request, call_next):\n           if not request.url.path.startswith(\"\u002Fx402\u002Fv1\"):\n               return await call_next(request)\n           ip = request.client.host if request.client else \"127.0.0.1\"\n           try:\n               limited = await RateLimiter.is_rate_limited(f\"ratelimit:x402:ip:{ip}\", 60, 60)\n           except Exception:\n               limited = False\n           if limited:\n               return JSONResponse(status_code=429, content={\"error\": \"x402 gateway rate limit exceeded.\"})\n           return await call_next(request)\n   ```\n3. **Free `\u002Fx402\u002Fv1\u002Fstatus` monitoring endpoint** (no payment). Return gateway\n   health, `x402_enabled`, `network`, `merchant_wallet`, `models_available`\n   (from `ModelRegistryService.get_active_models`), Redis health, and a payment\n   tally from Redis keys. Free because `\u002Fstatus` is not in `ROUTE_PRICING` → the\n   paywall `call_next`s it. Useful for liveness probes + dashboards.\n4. **Verify after EACH change** with a read-only POST to a paid route (expect 402),\n   the `\u002Fstatus` (200), and `discover` (clean). Streaming (`StreamingResponse` SSE)\n   was already present for `\u002Fchat\u002Fcompletions` + `\u002Fresponses` — confirm it still\n   works post-change.\n\n### Adding a new paid route (S3\u002FS4\u002FS5) — THREE touches, not one\nA new paid `\u002Fx402\u002Fv1\u002F*` endpoint is NOT just a router. To be gated correctly:\n1. **Route module** in `app\u002Fx402\u002F*.py` + `app.include_router(...)` in `main.py`\n   (inside the `if settings.X402_ENABLED...` try-block, BEFORE `app.add_middleware\n   (X402Middleware)` so `call_next` ordering is right).\n2. **`app\u002Fx402\u002Fpricing.py` → `ROUTE_PRICING`** — key it by `\"POST \u002Fx402\u002Fv1\u002F\u003Cpath>\"` or\n   `\"GET \u002Fx402\u002Fv1\u002F\u003Cpath>\"`. Any new path MISSING a pricing key is served FREE (no 402) —\n   a silent revenue leak, the same class as the path-param bug below.\n3. **`app\u002Fmiddleware\u002Fx402.py` → `QUERY_ROUTES`** — ONLY for GET routes. If a paid\n   GET endpoint takes query params but is absent here, the 402 challenge emits a\n   `body` input (empty) instead of `queryParams`, and the paid call can't be made.\n   POST routes (JSON body) don't need this set.\nNew GET data routes landed this way: `data\u002Fnews`, `data\u002Feth\u002Fbalance`,\n`data\u002Fsolana\u002Fbalance`, `data\u002Fdefi\u002Fyields`, `data\u002Fgas` (prices $0.02\u002F$0.001\u002F…).\n\n### Section-2\u002F3\u002F4 full-pass hardening (2026-08-06 — input validation + AI abuse + rate limit)\nWhen asked to harden the gateway (or any FastAPI app), the proven full-pass\nshape is ONE outer input-validation middleware + key-based throttle, not a\nscatter of guards per route. All of the below were live-verified.\n\n**Middleware ordering:** FastAPI\u002FStarlette `app.add_middleware` LAST-added =\nOUTERMOST= runs FIRST. To make your validation\u002Frate-limit middleware short-\ncircuit BEFORE the payment middleware (X402) or rate-limiter return 402\u002F429,\nregister it AFTER them (e.g. right after `CortexHeadersMiddleware`). An inner\nguard never fires because the payment gate already returned 402. Verify the\nordering by sending a body-only probe: an outer form\u002FJSON guard gives 415 (your\nmiddleware), not 402 (payment gate).\n\n**One middleware file (`app\u002Fmiddleware\u002Fvalidate.py`) covering ALL of Section 2:**\n- 415 unless `Content-Type: application\u002Fjson` **BUT exempt\n  `application\u002Fx-www-form-urlencoded` and `multipart\u002Fform-data` first** —\n  a blanket 415 breaks `\u002Fauth\u002Flogin` (OAuth2 sends form-encoded) → every login\n  415s. Exempt BEFORE the JSON check.\n- 413 body > 1MB; 400 invalid JSON \u002F nesting depth > 10 (JSON bomb, recurse\n  with a `MAX_DEPTH` guard—a `RecursionError` must become 400, not 500).\n- Read the body ONCE (`await request.body()`, starlette buffers it so the\n  downstream X402 re-read is safe — NO `request._receive` re-injection, which\n  is what breaks SSE on this stack).\n- **`JSONResponse(status_code=400, content=...)`** — NOT `JSONResponse(400,\n  content=...)`. The positional int binds to `content` → `TypeError: got\n  multiple values for argument 'content'` → **500 on EVERY guarded request**.\n  This is the #1 \"my middleware 500s everything\" cause; use the keyword.\n- `GET \u002Fdata\u002F*` query sanitization: match with `\"\u002Fdata\u002F\" in path` or endswith,\n  NOT `startswith(\"\u002Fdata\u002F\")` — the real paths are `\u002Fx402\u002Fv1\u002Fdata\u002F...` and\n  `startswith` misses them (params pass straight to the payment gate = 402, and\n  you'll wrongly think the guard works). **Address params (`address\u002Faddr\u002F\n  pair\u002Ftoken`): accept ERC-55 checksummed hex `0x[0-9a-fA-F]{40}` OR a base58\n  Solana address** — a validators-only-ERC-55 guard makes `\u002Fdata\u002Fsolana\u002Fbalance`\n  permanently 400 (a Solana base58 address can never be checksum-med hex). Fix\n  pattern (live 2026-08-07): `re.fullmatch(r\"0x[0-9a-fA-F]{40}\", a)` → ERC-55\n  check; else `re.fullmatch(r\"[1-9A-HJ-NP-Za-km-z]{32,44}\", a)` → valid base58\n  (no EIP-55 equivalent exists for Solana; the on-chain RPC is the real gate).\n\n**Section-3 capability-consistent AI payloads (in the same chat path):** gate\non the DB model row, not the user's claim. Load active models once per ~60s\ninto a cache via `ModelRegistryService` + `AsyncSessionLocal` (field is\n`context_length`, NOT `context_window`; `get_models()` is a DEAD import — use\nthe async session query). Then: 400 if `tools` > 64, if the model lacks the\n`tool_calling` capability but the request sends `tools`, if `max_tokens` or\n`max_completion_tokens` > `context_length`, and if a token estimate (~4\nchars\u002Ftoken) of `messages` exceeds the window. Tools\u002Fcapability gating\nprevents tool-schema flooding (provider prompt-slot abuse).\n\n**Section 4 rate limit:** a transparent AI gateway's only real brute force \u002F\nDoS gap is usually a form-based login with NO limiter (every one else is\nalready covered: `\u002Fx402\u002Fv1` IP throttle, legacy `\u002Fv1\u002F*` key-based limits, '§1'\nnonce dedup). Fix = a per-IP throttle in the login handler itself reusing the\nexisting `RateLimiter.is_rate_limited(f\"ratelimit:login:ip:{ip}\", 10, 60)`,\nfail-open on Redis error, 429 on exceed. Do NOT add a global IP limiter for\npaths that already carry key-based limits.\n\nFailure mode to expect when you deploy a guard middleware: it can break a\nlegit route you didn't think about (the form-login 415). Always probe BOTH the\nguarded-fail case (bad input → expected 4xx) AND a happy-path pass-through\n(valid → 402 payment-gate or 200) after every restart, then commit per section.\n\n### ⚠️ Starlette `request.state` is a State, NOT a dict (500s everything)\nIn a `BaseHTTPMiddleware` (or anywhere reading `request.state`), do NOT call\n`request.state.get(\"key\")` — `.get` does not exist on a Starlette `State` and\nthat AttributeError surfaces as `500 Internal Server Error` on **every** route\nthe middleware wraps (including `\u002Fhealth`). Use\n`getattr(request.state, \"key\", default)`. Also prefer `request.state` over\ncontextvars for per-request data (Starlette clears request-scoped state per\nrequest; a contextvar in a task-group can leak across requests).\nReal pattern: my S3\u002FS6 headers middleware reads\n`getattr(request.state, \"request_id\", None) or req headers[\"x-correlation-id\"]`.\n\n### ⚠️ PATH-PARAM PRICING PITFALL (silent paywall bypass — real bug, Phase B)\nThe x402 middleware matches pricing by **request path verbatim** against\n`_PATH_PRICING` keys. A FastAPI **path param does NOT match** at runtime, so a\nroute like `GET \u002Fx402\u002Fv1\u002Fdata\u002Fdex\u002Fpairs\u002F{chain}` (keyed the same in\n`ROUTE_PRICING`) is hit as `\u002Fdata\u002Fdex\u002Fpairs\u002Fethereum` → **lookup MISS** →\n`price_str is None` → middleware `call_next`s → **served free, no 402, proxy\nfires**. Silent revenue leak. **Fix: NEVER use path params on x402-gated\nroutes — pass all dynamic values as QUERY params** (`?chain=ethereum&pair=0x…`),\nand key pricing by the constant path. Full pattern + ERC-20\u002F`eth_call` selector\n+ keyless upstream list: `references\u002Fdata-marketplace.md`.\n\n### Favicon \u002F x402scan merchant branding — TWO distinct problems\nThere are two unrelated \"logo\" issues; fix the right one. Full detail +\nPoncho page notes: **`references\u002Fx402scan-merchant-branding.md`**.\n\n**(a) Discovery-audit `FAVICON_MISSING` warning** — `@agentcash\u002Fdiscovery check`\ncomplains when `\u002Ffavicon.ico` isn't a real image. Fix: serve the logo via\n`FileResponse(\"static\u002Ffavicon.jpg\", media_type=\"image\u002Fjpeg\")`. Verify with a\n**cache-bust** `curl \"...\u002Ffavicon.ico?cb=1\"` (expect `200 image\u002Fjpeg ~47KB`), not a\nbare `curl` (stale Cloudflare `image\u002Fsvg+xml` until TTL). Also check\n`http:\u002F\u002F127.0.0.1:8000` to bypass Cloudflare.\n\n**(b) x402scan server-page shows a letter avatar (\"C\"), not your logo** — this is\nwhat the user actually notices (\"the favicon still looks the same\"). **Verified\nmechanism (x402scan source):**\n- The server card reads `origin.favicon` (`header\u002Findex.tsx`: `src={origin.favicon}`,\n  fallback = `\u003CServer>` icon). When `favicon` is null, x402scan renders a\n  **generated LETTER AVATAR** from the title — that's the \"C\". So avatar = `favicon` field, NOT `og:image` (og:image feeds `ogImages`, separate).\n- `register-origin.ts` calls `scrapeOriginData(origin)` at **registration time**,\n  which fetches the origin's **HTML homepage** and parses `\u003Clink rel=\"icon\">`\n  (regex `rel=[\"']...icon...[\"']`) + `og:image`. `scrapeFavicon` (from\n  `@agentcash\u002Fdiscovery`) probes `COMMON_FAVICON_PATHS = [\"\u002Ffavicon.ico\",\n  \"\u002Ffavicon.png\", \"\u002Ffavicon.svg\"]` and resolves `\u003Clink rel=\"icon\" href>` candidates.\n  For `api.` subdomains it falls back to the **base domain** (`cortexcloud.org`) if `api.` lacks data.\n\n**⚠️ RE-REGISTRATION DOES NOT RELIABLY REFRESH A CACHED FAVICON (proven this session).**\nWe added the homepage + re-registered, but x402scan STILL showed \"C\". Proof the\nscraper itself works: running `@agentcash\u002Fdiscovery`'s own\n`scrapeFavicon('https:\u002F\u002Fapi.cortexcloud.org')` returns\n`https:\u002F\u002Fapi.cortexcloud.org\u002Ffavicon.ico`. So the root cause is a **stale\n`favicon:null` cached in x402scan's DB from the FIRST registration** — `upsertOrigin`\ndoes not overwrite it on re-register, and there is **NO public deregister\u002Frefresh\nendpoint** (the API exposes no DELETE\u002Fremove-origin mutation; `developer.ts` only\nhas read-only `preview` + `batchTest`). **Correct action + expectation:**\n1. DO add the HTML homepage at `\u002F` served on both `api.` and base domain with\n   `\u003Clink rel=\"icon\" href=\"\u002Ffavicon.ico\">` + `\u003Cmeta property=\"og:image\"\n   content=\"https:\u002F\u002Fapi.cortexcloud.org\u002Ffavicon.ico\">` (verify: `curl \u002F | grep -iE\n   \"og:image|rel=.icon\"`). Serve via `HTMLResponse(CORTEXCLOUD_HOME_HTML)`.\n2. Re-register — NECESSARY but NOT SUFFICIENT; it may eventually refresh on a later\n   re-register or periodic re-scrape.\n3. If it persists, the logo is correctly deployed + scrapeable; this is a\n   x402scan-side display-cache issue, NOT a gateway bug. Only x402scan support can\n   force a re-scrape. **Tell the user this clearly** rather than re-churning code.\nServe via `HTMLResponse(CORTEXCLOUD_HOME_HTML)` from `main.py`.\n\n**(c) x402scan server NAME\u002FTITLE comes from the HTML homepage `\u003Ctitle>`, NOT\n`openapi.json` `info.title`.** When the listing showed\n\"CortexCloud API -- Agent-Native AI & Data Gateway\" we first checked\n`info.title` (already \"CortexCloud API\") — but x402scan renders the card title from\nthe origin's served HTML `\u003Ctitle>` element. Fix: edit the `CORTEXCLOUD_HOME_HTML`\nconstant's `\u003Ctitle>` in `main.py` (e.g. `\u003Ctitle>CortexCloud API\u003C\u002Ftitle>`), restart,\nand verify with `curl https:\u002F\u002Fapi.cortexcloud.org\u002F | grep -i '\u003Ctitle>'`. x402scan\nre-scrapes the title on its next crawl\u002Fre-register. `info.title` and `og:title` do\nNOT drive the card title.\n\n### Home-page route pitfall (the fix for (b))\nWhen adding the `\u002F` HTML route, define the `CORTEXCLOUD_HOME_HTML` constant\n**before** `app = FastAPI(...)` — referencing it inside `home()` without defining\nit first throws `NameError` at request time (500 on `\u002F`). Verify with\n`curl https:\u002F\u002Fapi.cortexcloud.org\u002F | grep -iE \"og:image|rel=.icon\"` after restart.\n\n### Poncho merchant page\nDriven by `info.contact.email` in `openapi.json` (set to\n`ampwerajonathan50@gmail.com`) — that verifies ownership + edits the card. The page\nexists once registered + email set, but its live fields (Transactions \u002F Volume \u002F\nunique buyers) populate ONLY after real on-chain USDC payments hit the merchant\nwallet (`0xE816...2365`). No payments -> \"0 \u002F $0.00\". First real payment =\n`references\u002Fe2e-payment-test.md`.\n\n### `pct mount` write-race\nWhen editing CT 105 files via `pct mount` + base64 + python, do the\nread-modify-write **and** the verification (`grep -c` \u002F `json.load`) in the\n**SAME** `pct mount … pct unmount` shell command — a verify in a separate mount\nsession can show a discarded overlay (an injection once printed \"injected:True\"\nbut didn't persist). See `references\u002Fdata-marketplace.md`.\n\n## Phase B — Data Marketplace (the differentiator vs jarvisclaw.ai)\n\nExtend the gateway beyond AI inference with **x402-gated proxy endpoints backed\nby KEYLESS upstreams** (no caller API key, no new secrets, pure margin). This\nis what separates CortexCloud from a bare AI gateway. Proven pattern:\n\n- **Market data** (CoinGecko + DEXScreener, keyless): `data\u002Fprices`,\n  `data\u002Fcoins\u002Fsearch`, `data\u002Fdex\u002Fsearch`, `data\u002Fdex\u002Fpairs` — each $0.001.\n- **On-chain Base** (public RPC, keyless): `data\u002Fbase\u002Fbalance`,\n  `data\u002Fbase\u002Ftoken-balance` (USDC\u002FWETH\u002FDAI\u002FUSDT + any addr), `data\u002Fbase\u002Fnonce`\n  — each $0.001. Use `https:\u002F\u002Fmainnet.base.org` (llamarpc was 521\u002Fdown); add\n  `base-rpc.publicnode.com` + `1rpc.io\u002Fbase` as fallbacks.\n- Each adds: a route module → `ROUTE_PRICING` key (QUERY params only!) →\n  `app.include_router` in `main.py` → a path in `openapi.json` → re-run\n  `discover` (route count +1, 0 warnings).\n- Full route inventory + reusable ERC-20 `balanceOf` selector + exact upstream\n  URLs: **`references\u002Fdata-marketplace.md`**.\n\n## S3\u002FS6 extension surface — audit, usage, receipts, ECDSA response signing (landed 2026-08-03)\n\nBeyond the paid routes, the gateway ships trust\u002Fauditability endpoints. Built\nlive on the Python gateway; reusable pattern:\n- **`GET \u002Fx402\u002Fv1\u002Fpubkey`** (free) — serves the response-signing server public key\n  as PEM. Backs `app\u002Fx402\u002Ftrust.py`: lazy-generates an **ECDSA P-256** keypair once\n  (`SECP256R1`, persisted to a PEM file, `chmod 600`), exposes `get_pubkey_pem()`,\n  `sign_payload(payload)` → base64 DER signature, `verify_payload(...)`.\n- **`GET \u002Fx402\u002Fv1\u002Fusage?address=0x…`** and **`GET \u002Fx402\u002Fv1\u002Freceipts?address=…`**\n  (both free) — the x402 payment middleware `RPUSH`es one append-only JSON receipt\n  per settled payment to `x402:rx:\u003Csha256(payer)>` (Redis LIST, `LTRIM` to cap ~2000;\n  fail-open on Redis error). `\u002Fusage` aggregates call count + total atomic spent\n  (+ `.usdc` human), `\u002Freceipts` paginates. Reading the SAME key as the write is the\n  lazy-correct design: no separate store.\n- **Response signing middleware** (`app\u002Fmiddleware\u002Fheaders.py`,\n  `CortexHeadersMiddleware(BaseHTTPMiddleware)`) emits `X-Cortex-Request-Id`,\n  `X-Cortex-Provider` (from `request.state.upstream_provider`), `X-Cortex-Latency-Ms`,\n  and `X-Cortex-Signature` = `ECDSA_sha256(request_id + body)`. Add it AFTER\n  `X402Middleware` (`add_middleware` order) so it wraps the paid path. Verify the\n  signature end-to-end by re-signing the returned body with `get_pubkey_pem()`.\n\n### ⚠️ ECDSA verify gotchas (cost a debugging loop)\n- Cryptography must run **inside the CT** (`\u002Fopt\u002Fcortexcloud-venv\u002Fbin\u002Fpython`) — the\n  host interpreter has no `cryptography`, and a stray `\u002Ftmp\u002Fhttp*.py` can shadow\n  stdlib `http`. Don't hand-verify with `urllib.request` locally.\n- The signing middleware reads `request_id` via `getattr(request.state,\n  \"request_id\", None) or headers[\"x-correlation-id\"]`. A **free\u002Fun-routed response\n  (e.g. the 402 challenge) has empty `request_id`, so the signature binds only the\n  body and recomputing it needs `rid=b\"\" + body`. Routed 200s are signed with the\n  real `request_id` — send an explicit `x-correlation-id` header on your test call\n  so the verification script can reconstruct the exact payload.\n\n## Verification (authoritative)\n\n- **Discovery audit:** `npx -y @agentcash\u002Fdiscovery@latest discover\n  \"https:\u002F\u002Fapi.cortexcloud.org\"` → 0 warnings, routes listed with `paid [x402]`.\n- **Live 402 body validation:** run x402scan's own `validatePaymentRequiredDetailed`\n  on the live 402 (exact recipe + issue table in `mlops\u002Fx402-pay-per-call-gateway`\n  → `references\u002Fx402scan-v2-validator.md`). A clean body prints\n  `valid: true | version: 2 | errorCount: 0`.\n- **End-to-end paid-path test (MANDATORY before \"production-ready\"):** a safe,\n  recoverable harness that generates an ephemeral buyer wallet on the CT, has the\n  user fund it with a few dollars of USDC, runs the x402 client to pay + get a 200,\n  then sweeps the leftover back to the merchant wallet and wipes the key. The\n  `discover`-clean audit is NECESSARY but NOT SUFFICIENT — the e2e test is what\n  catches real interop bugs (PAYMENT-SIGNATURE vs X-PAYMENT header, CDP\n  facilitator auth). **The harness in `references\u002Fe2e-payment-test.md` was REWRITTEN\n  this session with the verified-correct manual 402->pay->retry (do NOT use\n  `x402_httpx_transport`; use `x402HTTPClient` + `get_payment_required_response` +\n  `create_payment_payload` + `encode_payment_signature_header`).** This is also what\n  populates the x402scan merchant page with a live transaction.\n- x402scan's registry READ endpoints (`\u002Fapi\u002Fx402\u002Fresources`, `\u002Fregistry\u002Forigin`)\n  are themselves x402-PAID — you cannot read your registration back without paying;\n  the `discover`\u002F`check` CLI is the verification path instead.\n\n## References\n\n- `references\u002Fpayment-verify-inprocess.md` — S1 hardening: in-process EIP-712\n  `TransferAuthorization` verification module + eth_account sign\u002Frecover self-check.\n- `references\u002Fx402-schema.md` — exact verified V1\u002FV2 field tables, facilitator\n  payload shape, and the 402-response checklist.\n- `references\u002Fcortexcloud-layout.md` — confirmed container\u002Ffile map, env vars,\n  provider wiring, and the Phase-0 fixes already applied.\n- `references\u002Fx402scan-openapi.md` — x402scan registration flow (SIWX web-form,\n  OpenAPI-first discovery) + a working `openapi.json` template with the `x402`\n  operation extensions and `info.contact.email` ownership field.\n- `references\u002Fdata-marketplace.md` — Phase B data-marketplace + on-chain Base\n  extension: keyless upstreams (CoinGecko\u002FDEXScreener\u002Fpublic RPC), the\n  PATH-PARAM pricing pitfall, ERC-20 balanceOf selector, favicon cache-bust,\n  and the `pct mount` write-race gotcha.\n- `references\u002Fmcp-server-build.md` — building the client-side MCP server\n  (`@cortexcloud\u002Fmcp`, stdio) AND hosting it remotely over **Streamable HTTP**\n  (`createServer()` factory, per-session fresh McpServer — `connect()` one-shot,\n  pin the `sessionIdGenerator` UUID before `new`, the `mcp-session-id` HEADER,\n  esbuild MUST be `--format=cjs` unminified or tweetnacl throws `Dynamic require\n  of \"crypto\"`), + the cloudflared `path: \u002Fmcp*` ingress that exposes it\n  publicly. Verified live 2026-08-07.\n- `references\u002Fmcp-registry-submission.md` — getting the hosted server LISTED: official\n  Registry API (`\u002Fv0\u002Fvalidate`, `\u002Fv0\u002Fauth\u002Fgithub-at`, `\u002Fv0\u002Fpublish`) + server.json\n  schema (required `$schema`, desc ≤100 chars, `Repository` = `{source,id,url}` with\n  NO `type`), the `mcp-publisher login github` device-flow handoff, and the 4-registry\n  map (Official → auto PulseMCP → Smithery URL → mcp.so\u002FGlama repo). Live `valid:true`\n  verified 2026-08-07.\n- `references\u002Fweb3-7x-quirks.md` — web3.py 7.x API gotchas (cdp-sdk pulls it in):\n  no `async with`, keyword `address=`\u002F`abi=`, ERC-20 balanceOf + ETH balance\n  recipes, public Base RPC, and the gasless EIP-3009 sweep trick.\n- `references\u002Fcompetitor-gap-analysis.md` — how to benchmark CortexCloud against a\n  rival x402 gateway (BlockRun snapshot, 2026-07-12) using `@agentcash\u002Fdiscovery` on\n  the competitor's origin + reading their site via browser.\n- `references\u002Forigin-quantum-quafu.md` — Origin Quantum \u002F Wukong integration\n  (Quafu cloud, `quafu-runtime` SDK: Account token, upload_program → run →\n  job.result; hybrid classical\u002Fquantum runtime programs) — basis for the\n  Optimization pivot's quantum + QAOA\u002Fhybrid adapters. Verified 2026-08-08.\n\n## CortexCloud Optimization pivot — quantum adapter groundwork (planned 2026-08-08)\nThe user approved an inspection+plan phase for repositioning the repo as\n\"optimization infrastructure for AI agents\" (classical\u002Fhybrid\u002Fquantum solvers\nbehind one x402 API: `\u002Fv1\u002Festimate` free, `\u002Fv1\u002Foptimize` paid, `\u002Fv1\u002Fjobs\u002F{id}`\n+ `\u002Fv1\u002Fbackends` + `\u002Fv1\u002Fcapabilities` free). Verified facts for that build:\n- **Keep the x402 middleware machinery intact** (verify\u002Fsettle\u002Fproof cache\u002F\n  payverify); the change is ROUTE_PRICING keys + INPUT_SCHEMAS, not the payment\n  flow. New paid routes = the 3-touch rule above (router → pricing dict →\n  openapi.json).\n- **Redis removal is viable:** jobs→PG, nonce dedup→PG unique constraint\n  (must survive restarts — security), proof cache + rate limiter→in-process\n  (`ponytail:` single-worker ceiling). Live prod DB is lightly used (10 model\n  rows, 1 user\u002Fkey, 0 usage_logs) — old auth\u002Fbilling tables can be left in\n  place, not dropped.\n- **Origin Quantum = Quafu SDK (token auth, upload_program → run → poll)** —\n  full verified mechanism + adapter design: `references\u002Forigin-quantum-quafu.md`.\n- Node MCP server source (`cortex_*` tools live there) = local\n  `\u002Fhome\u002Fhermes\u002Fcortexcloud-mcp` (src\u002Findex.ts) matching the CT bundle.\n\n## TS gateway owning the x402 handshake (cross-stack split — decided 2026-07-16)\nA TypeScript\u002FFastify rewrite of the gateway can own the **HTTP 402 handshake +\n`\u002Fv1\u002Fsettle` + audit log** while leaving **on-chain settlement** in the legacy\nPython gateway. Pattern proven when building `~\u002Fcortexcloud-gateway`:\n- `verifyPayment(txHash, payer, amountUsd, projectId)` is a **pluggable hook** —\n  default logs + writes a `Payment` row (`status:\"settled\"`) but does NOT chain-\n  confirm. Wire real `viem`\u002FCDP confirmation here when this service owns settlement.\n- `MERCHANT_WALLET` env default = `0xE816eA741a0084748DC9f2BEeB86Be6705862365`\n  (the real CortexCloud wallet) so the 402 payload is correct even before on-chain\n  verify lands.\n- Mark the ceiling with `\u002F\u002F ponytail: no on-chain settle here; verifyPayment logs +\n  returns ok. Wire a real base RPC\u002Fviem check when this gateway owns settlement.`\nThis lets a TS MVP serve real 402s immediately without re-implementing CDP\nfacilitator auth (the #1 settlement blocker, above). Build the Fastify\u002FPrisma\nshell with `node-api-gateway`; keep this skill for the protocol\u002Fsettlement layer.\n\n## Live payment VERIFIED (2026-07-12)\nThe full loop ran end-to-end on **mainnet** and settled real USDC:\n402 challenge (with `extra` EIP-712 domain) -> buyer signed EIP-3009 ->\nCDP `\u002Fverify`+`\u002Fsettle` (per-request JWT auth) -> request routed to Groq ->\n200 + completion. Merchant wallet `0xE816...2365` balance rose on-chain\n(confirmed via balanceOf on `mainnet.base.org`). The three things that were\nWRONG before this worked: (1) facilitator auth was a static Bearer — must be\n`cdp.x402.x402.create_cdp_auth_headers` JWTs; (2) `accepts[]` lacked `extra`\nEIP-712 domain; (3) middleware imported `cdp.x402` instead of `cdp.x402.x402`.\nAll three fixed + verified. See `references\u002Fe2e-payment-test.md`.\n- The exact v2 402 body shape + headless `validatePaymentRequiredDetailed` recipe +\n  the 405 method-agnostic fix live in `mlops\u002Fx402-pay-per-call-gateway` →\n  `references\u002Fx402scan-v2-validator.md` (single source of truth for the validator).\n- **Upstream provider gotchas (Alchemy\u002FCoinGecko) for paid Data routes** live in\n  `references\u002Falchemy-integration.md`: correct host (`*.g.alchemy.com` not\n  `*.gateway.`), Bearer-header auth (not `?apiKey=`), and the JSON-RPC `\u002Fv2` vs\n  REST `\u002Fnft\u002Fv3` split — every Data endpoint 401\u002F400 I hit traced to one of these.\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002F.archive\u002Fx402-ai-gateway","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill x402-ai-gateway",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill x402-ai-gateway",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill x402-ai-gateway","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Fx402-ai-gateway\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",586,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Fx402-ai-gateway\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]