Counterparty MCP
# Counterparty MCP
Pay-per-call counterparty due-diligence tools for AI agents, served as a stateless MCP server on Cloudflare Workers. Agents pay in USDC per tool call using the [x402 MCP transport](https://github.com/coinbase/x402/blob/main/specs/transports-v2/mcp.md), with no account or API key needed.
| Tool | Price | What it returns |
| --- | --- | --- |
| `resolve_company` | free | Name, ticker or CIK to SEC CIK candidates |
| `lei_lookup` | $0.01 | GLEIF LEI status, jurisdiction, address, direct and ultimate parent |
| `screen_sanctions` | $0.02 | Fuzzy OFAC SDN matches (aliases included), programs, Treasury links |
| `sec_filings` | $0.02 | Company profile and recent filings, with 8-K items decoded and red flags marked |
| `financial_snapshot` | $0.03 | Latest annual XBRL financials and ratios |
| `counterparty_brief` | $0.15 | Everything above in one call, with risk flags and evidence links |
Prices live in `src/pricing.ts`, the single source of truth that also generates `llms.txt` and `pricing.json`. Basic tools allow `FREE_TRIAL_CALLS_PER_DAY` unpaid calls per client per day.
> Informational screening from public government data. Not legal advice and not a substitute for a regulated KYC/AML program.
## Architecture
```
AI agent / MCP client Cloudflare Worker (stateless) External
───────────────────── ───────────────────────────── ────────
tools/list ───────────────────────────▶ /mcp (MCP SDK, Streamable HTTP, JSON mode)
tools/call (no payment) ───────────────▶ paywall ──▶ isError + x402 PaymentRequired
sign EIP-3009 for exact amount
tools/call + _meta["x402/payment"] ────▶ paywall
1. precheck: amount, payTo, network, expiry window
2. KV ledger (network:payer:nonce)
settled+same args → cached result, no charge
settled+other args → payment_already_used
3. per-payer daily spend cap (KV)
4. facilitator /verify ───────────────────────▶ x402 facilitator
5. run tool ──────────────────────────────────▶ OFAC / SEC / GLEIF
tool error → no settle → not charged (edge-cached)
6. facilitator /settle ───────────────────────▶ USDC on Base
settle fails → output withheld
7. store result in ledger (7 days), meter
result + _meta["x402/payment-response"] ◀─ Analytics Engine data point + Workers Logs
```
There is no database. KV holds the idempotency ledger, counters, and the OFAC sanctions index, which a cron trigger refreshes every 6 hours. Analytics Engine records usage and revenue. The Rate Limiting binding caps each client at 60 requests a minute. The server never holds a private key; it only receives payments to a public address.
### Security model
- **Payment before work.** The facilitator `/verify` call (read-only, moves no funds) runs before any tool executes. Settlement runs only after the tool succeeds.
- **Replay protection, layered.** (1) The EIP-3009 nonce is single-use on-chain, so the facilitator cannot settle it twice. (2) The payment must match this tool's exact amount, our `payTo`, network and asset. (3) Authorizations valid for more than about 3 minutes are rejected. (4) The KV ledger rejects a used payment on a different request.
- **Idempotency.** Retrying the same tool and arguments with the same payment returns the stored result and does not charge again. That covers network timeouts.
- **No double charge, even under races.** KV is eventually consistent, so two simultaneous duplicates can both run the tool. Only one can settle; the other gets a settlement error and no output.
- **Spending limits.** `PAYER_DAILY_SPEND_CAP_USD` per payer address per UTC day protects agents from runaway loops.
- **Abuse and validation.** Zod schemas on every input, a 64 KB body limit, a rate limit on hashed client IPs (raw IPs are never stored), and a guard against truncated sanctions downloads.
- **Secrets.** `X402_PAY_TO` is a public address. The only other secrets are facilitator API credentials (`CDP_API_KEY_*` or `X402_FACILITATOR_AUTH`), which cannot move funds. Never put a private key or seed phrase anywhere in this project.
## Quick start (local)
```bash
npm install
cp .dev.vars.example .dev.vars # set X402_PAY_TO to your receiving address
npm test # 29 tests: payments, replay, idempotency, tools
npm run dev # http://localhost:8787
```
Smoke test:
```bash
curl -s localhost:8787/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
curl -s localhost:8787/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"counterparty_brief","arguments":{"query":"AAPL"}}}'
# -> isError: true with x402 PaymentRequired (amount "150000" = $0.15 USDC)
curl -s localhost:8787/llms.txt
```
## Deploy
### 1. Testnet (Base Sepolia), the default config
```bash
npx wrangler login
npx wrangler kv namespace create LEDGER # paste the id into wrangler.jsonc
# Requires the Workers Paid plan ($5/mo): sanctions screening needs more than the Free plan's 10 ms CPU per request.
npx wrangler secret put X402_PAY_TO # your receiving wallet address (public)
# edit wrangler.jsonc: PUBLIC_BASE_URL, SEC_USER_AGENT (real contact email, required by SEC)
npm run deploy:testnet
```
Get test USDC from the Circle faucet, then pay for a call with any x402-capable MCP client. Examples include the `@x402/mcp` client wrappers and Cloudflare Agents' `withX402Client`. Confirm the transaction on Base Sepolia's explorer.
### 2. Mainnet (Base)
The mainnet values are already in `wrangler.jsonc` under `env.mainnet` (same worker name, so the same URL switches over). The whole switch is:
```bash
npx wrangler secret put CDP_API_KEY_ID --env mainnet
npx wrangler secret put CDP_API_KEY_SECRET --env mainnet
npm run deploy:mainnet
```
First real payment: `npm run pay:test` (see `scripts/pay-test.ts`) signs one $0.02 call with a payer key you set in `PAYER_PRIVATE_KEY`, locally, and prints the BaseScan link.
`npm run deploy` now also deploys mainnet. To go back to testnet, run `npm run deploy:testnet`. For reference, the mainnet values are:
| Var | Mainnet value |
| --- | --- |
| `X402_NETWORK` | `eip155:8453` |
| `X402_ASSET` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (USDC on Base) |
| `X402_ASSET_NAME` | `USD Coin` (the token's EIP-712 domain name on Base mainnet) |
| `X402_FACILITATOR_URL` | A mainnet facilitator, such as Coinbase CDP |
For the Coinbase CDP facilitator (1,000 free settlements a month, then $0.001 each), set `X402_FACILITATOR_URL` to `https://api.cdp.coinbase.com/platform/v2/x402`. Then store a CDP API key as secrets:
```bash
npx wrangler secret put CDP_API_KEY_ID
npx wrangler secret put CDP_API_KEY_SECRET # base64 Ed25519 (CDP default) or PKCS#8 PEM EC key
```
The server signs a fresh 120-second JWT for every `/verify` and `/settle` call (`src/payments/cdp-auth.ts`). It uses the same header and claims as Coinbase's `@coinbase/cdp-sdk` `generateJwt`, checked against the official SDK's output. This API key only authorizes facilitator calls; it cannot move funds. Before taking real money, verify the USDC address and EIP-712 name against the facilitator's `/supported` response and Circle's docs.
Then regenerate discovery files for your domain:
```bash
npm run gen:docs -- https://YOUR_DOMAIN eip155:8453
```
### Environment variables
| Name | Kind | Purpose |
| --- | --- | --- |
| `X402_PAY_TO` | secret | Receiving wallet address (public address only) |
| `CDP_API_KEY_ID`, `CDP_API_KEY_SECRET` | secret, mainnet | Coinbase CDP facilitator API key; signs a JWT per request |
| `X402_FACILITATOR_AUTH` | secret, optional | Static `Authorization` header for another authenticated facilitator |
| `X402_NETWORK`, `X402_ASSET`, `X402_ASSET_NAME`, `X402_ASSET_VERSION` | var | Chain and token (CAIP-2 network id) |
| `X402_FACILITATOR_URL` | var | Facilitator base URL (`/verify`, `/settle`) |
| `PUBLIC_BASE_URL` | var | Used in llms.txt and registry metadata |
| `FREE_TRIAL_CALLS_PER_DAY` | var | Unpaid basic-tool calls per client per day (0 disables) |
| `PAYER_DAILY_SPEND_CAP_USD` | var | Per-payer daily cap (0 disables) |
| `SEC_USER_AGENT` | var | Required by SEC fair-access policy: "App name contact@email" |
## Revenue reporting
Analytics Engine is optional: enable it in the Cloudflare dashboard, then uncomment `analytics_engine_datasets` in `wrangler.jsonc`. When enabled, every call writes one data point: `blob1`=tool, `blob2`=outcome, `blob3`=payer, `blob4`=tx hash, `double1`=USD. Query it with the [Analytics Engine SQL API](https://developers.cloudflare.com/analytics/analytics-engine/sql-api/):
```sql
SELECT blob1 AS tool,
SUM(_sample_interval) AS paid_calls,
SUM(_sample_interval * double1) AS revenue_usd,
COUNT(DISTINCT blob3) AS payers
FROM counterparty_mcp_usage
WHERE blob2 = 'paid' AND timestamp > NOW() - INTERVAL '30' DAY
GROUP BY tool ORDER BY revenue_usd DESC
```
Conversion funnel: compare `payment_required` against `paid` and `trial` counts. Settled revenue is also visible on-chain at your `payTo` address.
## Distribution assets
- `GET /llms.txt`, `/llms-full.txt`: agent-readable docs generated from `src/pricing.ts`. Static copies are in `public/`.
- `GET /pricing.json`: machine-readable prices.
- `GET /.well-known/mcp/server.json` and `server.json`: official MCP Registry metadata. Set your `io.github.<user>` name, then `mcp-publisher publish`.
- `docs/LISTING.md`: marketplace copy for MCPize, MCP-Hive, Smithery, Glama and others.
## Other payment rails
- **MCPize** (80% to you, hosting included, Stripe Connect payouts): list this server with its x402 per-call option, plus a subscription tier for card buyers.
- **MCP-Hive** (70% to you): register the remote endpoint; subscribers pay from monthly credits.
- **Stripe MPP**: add `mppx` + `stripe` for fiat settlement into a Stripe balance. Stablecoins have a 0.01 USDC minimum; cards through SPTs have a $0.50 minimum, so sell card buyers prepaid bundles, not $0.02 calls. Stripe also accepts x402 on Base.
## Project layout
```
src/index.ts Worker entry: routing, rate limit, CORS, MCP transport
src/mcp.ts Tool definitions (Zod schemas) wired through the paywall
src/payments/x402.ts x402 v2 types, requirements, precheck, facilitator client
src/payments/cdp-auth.ts Per-request JWT for the Coinbase CDP facilitator
src/payments/paywall.ts Verify → execute → settle, idempotency ledger, trial, spend cap
src/data/*.ts OFAC SDN parser + matcher, SEC EDGAR, GLEIF
src/discovery.ts llms.txt, pricing.json, server.json generators
test/ Vitest suite with fixtures and a fake facilitator
```
## Known limits
- Live upstream calls to SEC, OFAC and GLEIF were not exercised in the build sandbox (its network blocks those hosts). Unit tests use fixtures built from the documented formats. Run a live check on testnet before launch.
- Sanctions coverage is OFAC SDN only. The EU, UK and UN lists are free to add; OpenSanctions needs a commercial license.
- Financials and filings cover SEC registrants only. For other companies, the brief still runs sanctions and LEI checks.
TDQS
Scored across 6 tools
Most tools target distinct lookups: company resolution, sanctions screening, SEC filings, XBRL financials, and LEI/GLEIF data. The main overlap is counterparty_brief, which bundles all of the above and could tempt an agent away from the cheaper single-purpose tools, but the descriptions make the distinction and pricing clear.
All names are lowercase snake_case, which is consistent and readable. They are not uniform verb_noun (two verb-led names alongside noun-led ones like sec_filings and financial_snapshot), but each name still clearly signals the resource or action.
Six tools is well-scoped for a counterparty due-diligence server. Each tool covers a distinct data source or aggregation workflow, and the free resolver plus paid specialized lookups form a sensible set.
Coverage is strong for the inferred domain: entity resolution, OFAC screening, SEC filings, financials, LEI/parent data, and a bundled risk brief. Minor gaps include non-OFAC sanctions lists, adverse media/litigation, and ongoing monitoring, but core workflows are covered.