
# Enabling agents to discover and pay for your API

## Overview

GOAL: Help a user at any stage (from zero to production API) make their API discoverable, payable, and wallet-authorized for agents.

This prompt is designed for coding agents. It should gather context, pick the correct implementation path, and execute with minimal back-and-forth.

## Registration gate (hard rule)

Registration creates a public listing that agents will call and pay. **Do not register the API on mppscan, x402scan, or any other registry until BOTH of these are true:**

1. **The implementation is done and live.** The API is deployed at its final public origin, `/openapi.json` is served from that origin, and `discover` + `check` pass against the deployed URL — not localhost, not a preview deployment, not a partially-implemented route set.
2. **The user has explicitly approved registering that specific origin.** Ask for approval as a separate, final step. "Do everything automatically" authorizes implementation and validation; it does not authorize publishing a listing.

Until both conditions hold:
- Do the implementation, discovery, and validation work as normal.
- Do not call registration endpoints, submit registration forms, or use payment/auth tools to POST to a registry.

When implementation and validation are complete, present the user with:
- the origin that would be listed
- the routes that would be listed, with their prices and auth modes
- the validation output summary

Then ask: "Ready to register this on `<registry>`?" Register only on an explicit yes. If the user declines or does not answer, hand off the registration links instead and stop — an unregistered working API is a fine outcome; a surprise public listing is not.

## Important Context
- Open protocols like x402 and MPP enable agents to authorize and pay for API calls.
- x402 is part of the Linux Foundation and was originally created by Coinbase.
- MPP (Machine Payments Protocol) was created by Stripe and Tempo.
- An API can support both or only one of the protocols (through `@agentcash/router` or official SDKs).
- MPPscan and x402scan are popular tools for discovering and exploring agentic commerce activity, created by Merit Systems.
- `@agentcash/discovery` can be used to validate OpenAPI discovery and payment metadata before registration.

Primary docs:
- x402 docs: `https://docs.x402.org/`
- MPP docs: `https://mpp.dev/docs`
- AgentCash suggested frameworks (greenfield + proxy patterns): `https://agentcash.dev/docs/suggested-frameworks`
- AgentCash server discovery guide: `https://agentcash.dev/docs/discovery`
- @agentcash/router implementation guide: `https://agentcash.dev/agentcash-router.md` — fetch this before writing router code
- x402scan registration: `https://www.x402scan.com/resources/register`
- mppscan registration: `https://www.mppscan.com/register`

## Agent operating mode

Before implementing, classify the user into one of these stages:

1. `GREENFIELD`: no API yet, building net-new for agents.
2. `EXISTING_API`: production API exists and should be wrapped with payments/auth.
3. `HAS_X402`: x402 support exists; wants discovery and/or MPP expansion.
4. `HAS_MPP`: MPP support exists; wants discovery and/or x402 expansion.
5. `HAS_BOTH`: both protocols exist; needs discovery hardening and registration.

If unclear, ask exactly these questions first:
- Do you already have a running API origin?
- Which protocol(s) are live now (`x402`, `MPP`, both, neither)?
- Do you want paid routes, identity-only routes, or both?
- Are you willing to add a proxy layer in front of your existing backend?

## Decision tree workflow

Use this decision tree exactly. Follow the first matching branch.

```text
START
 |-- Q1: Does the user already have a running API?
 |   |-- NO  -> BRANCH A (GREENFIELD)
 |   +-- YES -> Q2
 |
 |-- Q2: Which payment protocol is already implemented?
 |   |-- NONE  -> BRANCH B (EXISTING API, NO PAYMENTS YET)
 |   |-- X402  -> Q3
 |   |-- MPP   -> Q4
 |   +-- BOTH  -> BRANCH E (DISCOVERY + REGISTRATION HARDENING)
 |
 |-- Q3: User has x402. Do they want MPP too?
 |   |-- YES -> BRANCH C (EXPAND X402 -> BOTH)
 |   +-- NO  -> BRANCH E (DISCOVERY + REGISTRATION HARDENING)
 |
 +-- Q4: User has MPP. Do they want x402 too?
     |-- YES -> BRANCH D (EXPAND MPP -> BOTH)
     +-- NO  -> BRANCH E (DISCOVERY + REGISTRATION HARDENING)
```

When asking the user questions, tailor the presumed knowledge level based on their context. For example, for greenfield users, you can assume they don't know about x402 or MPP and you should focus on the capabilities these tools (x402, MPP) provide, and how they can be used to monetize their API and be found by agents.

Do not mention the specific branch names, just focus on the capabilities and the paths to get there.

## Branch playbooks

### Branch A: Greenfield (no API yet)

Recommended path:
1. Scaffold a new API service (commonly Next.js route handlers).
2. Use `@agentcash/router` from day one.
3. Build one minimal paid route first, then add auth-only routes if needed.
4. Emit `/openapi.json` with full schemas and payment metadata.
5. Validate with `@agentcash/discovery`.
6. Deploy to the final public origin and re-validate against it.
7. Only then, per the registration gate, ask the user to approve registering on `mppscan` and/or `x402scan`.

Why this path:
- Lowest integration complexity.
- Native support for both protocols without later migration.

### Branch B: Existing API, no payment protocol yet

Recommended path:
1. Create a thin proxy in front of production API.
2. Put `x402`/`MPP` verification, wallet identity, rate limiting, and discovery in proxy.
3. Keep production backend unchanged; call it with internal API key from proxy.
4. Start with one protocol or both depending on requirement:
   - single protocol: official SDK or router
   - dual protocol: use `@agentcash/router`
5. Publish discovery from proxy origin (`/openapi.json`), not the private upstream.
6. Preserve payment challenge headers through the proxy, rewrite upstream `Location` redirects to the public origin, and enforce body limits against bytes read rather than only `Content-Length`.

Why this path:
- Fastest way to monetize existing APIs without risky backend rewrites.

### Branch C: Already x402, expand to both

Recommended path:
1. Add MPP compatibility on payable operations.
2. Normalize OpenAPI `x-payment-info.protocols` to include both protocol objects.
3. Re-run discovery validation and runtime 402 checks against the deployed origin.
4. Once those pass, ask the user to approve registering/updating the listing in both ecosystems (see registration gate).

Implementation note:
- If dual-protocol support is uneven across routes, prioritize top revenue routes first.

### Branch D: Already MPP, expand to both

Recommended path:
1. Add x402 support on payable operations.
2. Normalize OpenAPI `x-payment-info.protocols` to include both protocol objects.
3. Re-run discovery validation and runtime 402 checks against the deployed origin.
4. Once those pass, ask the user to approve registering/updating the listing in both ecosystems (see registration gate).

### Branch E: Discovery + registration hardening (already monetized)

Recommended path:
1. Validate `GET /openapi.json` shape and completeness.
2. Validate every payable operation has:
   - `x-payment-info`
   - `responses.402`
   - request schema and response schema
3. Validate identity-only routes:
   - SIWX routes use `security` declaration and no `x-payment-info`
   - MPP identity mode uses zero-amount challenge flow
4. Validate runtime challenge behavior:
   - unauthenticated probes reach `402` before body/query validation rejects the request
   - x402 runtime `accepts[].amount` uses token atomic units (for USDC, `0.01` => `"10000"`)
   - MPP routes return `WWW-Authenticate` and use the public-origin realm
5. Run discovery checks until clean.
6. Only then, per the registration gate, ask the user to approve registering or refreshing the listing on the relevant registries.

## Implementation standards for all branches

If using `@agentcash/router`, fetch `https://agentcash.dev/agentcash-router.md` before writing code. Current router defaults to remember:
- `createRouterFromEnv` derives `BASE_URL` from `VERCEL_PROJECT_PRODUCTION_URL`, then `VERCEL_URL`, when `BASE_URL` is unset. Set `BASE_URL` explicitly for custom domains or reverse proxies.
- Keep Vercel one-click deploys focused on required x402 env vars. Add Vercel KV / Upstash from the Storage tab before production traffic instead of gating first deploy on an integration step.
- Create Coinbase Developer Platform keys for x402 in the generous CDP free tier at `https://portal.cdp.coinbase.com/projects/api-keys`.

## Starting from scratch

Recommended default: `@agentcash/router` with Next.js route handlers. Fetch `https://agentcash.dev/agentcash-router.md` for the API reference and gotchas.

## Integrating with an existing API

Recommended default: a proxy service that wraps existing endpoints with `x402`, `MPP`, or both.

## Protocol selection

### x402 only

- Use official x402 SDKs or `@agentcash/router`.

### MPP only

- Use official MPP SDK (`mppx`) or `@agentcash/router`.
- **Realm must match the public origin.** On custom domains or reverse proxies, do not rely on auto-detected deployment hosts like `VERCEL_URL`; set `MPP_REALM` or pass `realm` explicitly, e.g. `Mppx.create({ realm: "api.example.com", ... })`.

### Both x402 + MPP

- Use `@agentcash/router`.

## Publishing a discovery specification

Implement discovery for this server and make it pass.

Discovery strategy:
Your API should expose an OpenAPI document at `/openapi.json`, which abides by OpenAPI and includes discovery fields.
Use `@agentcash/discovery` to validate.

Validation commands:
npx -y @agentcash/discovery@latest discover "$TARGET_URL"
npx -y @agentcash/discovery@latest check "$TARGET_URL"


This will yield warnings regarding the discovery document and how it can be improved.

Schema guidance (important):
- Each invocable route should expose an input schema.
- In OpenAPI, define requestBody.content["application/json"].schema.
- This is required for reliable agent invocation and robust listing behavior.
- Add high-level guidance in info.x-guidance for agent-friendly discovery. This document should explain to an agent how to use your API at a high level.

Contact email (recommended):
- Ask the user for their contact email and add it as info.contact.email in the openapi.json.
- This lets them verify ownership of their origin, allows users to contact them, and lets them customize their merchant pages on Poncho.

OpenAPI payable operation must include ALL:
- `x-payment-info` with:
  - `protocols`: protocol objects, for example `[{ "x402": {} }, { "mpp": { "method": "", "intent": "", "currency": "" } }]`
  - `price` object:
    - fixed: `{ price: { mode: "fixed", currency: "USD", amount: "<amount>" } }`
    - dynamic: `{ price: { mode: "dynamic", currency: "USD", min: "<min>", max: "<max>" } }`
  - Legacy flat format still works: `{ pricingMode: "fixed", price: "<amount>" }`
  - IMPORTANT: fixed pricing should use `amount` (not `value`)
  - IMPORTANT: OpenAPI `price.amount` is decimal USD; runtime x402 `accepts[].amount` is token atomic units (for USDC, `0.01` => `"10000"`)
- `responses`: `{ "402": { "description": "Payment Required" } }`

Identity-only (authorized, not paid) endpoints:
- For x402 ecosystems: declare `siwx` in `components.securitySchemes` and reference it on each identity-gated operation via `security: [{ "siwx": [] }]`.
- Do not add `x-payment-info` to SIWX-only routes.
- For MPP identity mode: use zero-amount pricing challenges per MPP identity guidance.

Minimal valid example:
{
  "openapi": "3.1.0",
  "info": {
    "title": "My API",
    "version": "1.0.0",
    "description": "example demo server",
    "x-guidance": "Use POST /api/search for neural web search. Accepts a JSON body with a 'query' field.",
    "contact": {
      "email": "you@example.com"
    }
  },
  "x-discovery": {
    "ownershipProofs": ["<proof-1>"]
  },
  "paths": {
    "/api/search": {
      "post": {
        "operationId": "search",
        "summary": "Search - Neural search across the web",
        "tags": ["Search"],
        "x-payment-info": {
          "price": { "mode": "fixed", "currency": "USD", "amount": "0.010000" },
          "protocols": [{ "x402": {} }, { "mpp": { "method": "", "intent": "", "currency": "" } }]
        },
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "query": { "type": "string", "minLength": 1, "description": "The query string for the search" }
                },
                "required": ["query"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "results": { "type": "array", "items": { "type": "object" } }
                  },
                  "required": ["results"]
                }
              }
            }
          },
          "402": { "description": "Payment Required" }
        }
      }
    }
  }
}

## Completion Checklist

1. Correct branch selected from the decision tree.
2. Protocol implementation complete for target branch.
3. API deployed at its final public origin.
4. `/openapi.json` published and valid at that origin.
5. `discover` and `check` commands run against the deployed origin without blocking errors.
6. User receives final handoff with:
   - implemented architecture
   - supported protocols
   - validation output summary
   - the exact origin and routes that would be listed
   - next recommended step (e.g., add second protocol, add SIWX routes, tighten rate limits)
7. Registration explicitly offered as the last step — never done before steps 1-6 are complete and the user has said yes:
   - `https://www.x402scan.com/resources/register`
   - `https://www.mppscan.com/register`
   If the user has not approved, leave these as links and stop.
