Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add MCP annotation safety check and related tooling
nirholas102ab373d79c
diff --git a/data/pages.json b/data/pages.jsonindex 3446b266c..2783d33fa 100644--- a/data/pages.json+++ b/data/pages.json@@ -3037,6 +3037,216 @@"priority": 0.6,"changefreq": "monthly","added": "2026-07-21"+ },+ {+ "path": "/docs/payment-sessions",+ "title": "Docs: Payment Sessions",+ "description": "A Payment Session is a platform-managed spend envelope for agents. You fund a",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/developer-platform",+ "title": "Docs: Developer Platform",+ "description": "Everything you need to build against three.ws programmatically: API keys for",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/media-api",+ "title": "Docs: three.ws Media & Render API",+ "description": "Free media endpoints for agents and apps built around three.ws 3D assets:",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/forged",+ "title": "Docs: The Agent-Forged Gallery (/forged)",+ "description": "three.ws/forged is a public gallery of 3D props that",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/generation-watch",+ "title": "Docs: Generation Watch (/watch)",+ "description": "three.ws/watch is the live progress page for a single",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/kol-tracker",+ "title": "Docs: KOL Tracker: influencers ranked by what their wallets actually did",+ "description": "The KOL Tracker ranks Solana KOLs by realized P&L computed from their own wallets' on-chain trade history. Not screenshots, not self-reported win streaks: the board reads real trades, runs a FIFO cost-basis computation over them, and sorts by the realized USD result.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/character-library",+ "title": "Docs: Character Library: 106 rigged characters, ready to animate",+ "description": "The Character Library is a free, curated gallery of professionally rigged humanoid 3D characters. Every character ships as a web-ready GLB with a full skeleton, skin weights, and textures, so it drives the entire three.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/object-library",+ "title": "Docs: Object Library: free CC0 3D props for any scene",+ "description": "The Object Library is a free, curated gallery of CC0 3D objects and props: furniture, lighting, electronics, containers, tools, decor. Every object is public domain, free to use commercially with no attribution required.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/minted",+ "title": "Docs: Minted 3D Assets: the public gallery of on-chain avatars",+ "description": "three.ws/minted is the live, public gallery of every generated or owned avatar that a creator chose to mint as a Metaplex Core NFT through three.ws. It is the NFT counterpart of the /launches coin directory: real on-chain property, listed the moment it mints.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/reasoning-ledger",+ "title": "Docs: The Reasoning Ledger: hash-chained agent decisions you can audit",+ "description": "Every consequential call a three.ws agent makes (what it decided, why, what it predicted, and what actually happened) is appended to a per-agent, hash-chained ledger.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/timeline",+ "title": "Docs: The Story So Far: the 3D history timeline",+ "description": "/timeline tells three.ws's public history as a place you can explore rather",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/daily-match",+ "title": "Docs: Daily Match",+ "description": "/daily-match is a live standings board that answers one question: which",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/agent-symphony",+ "title": "Docs: Agent Symphony",+ "description": "three.ws/symphony plays the live agent economy as",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/notifications",+ "title": "Docs: Notifications: the bell, the /notifications center, and the inbox API",+ "description": "Everything that happens to your work on three.ws (a payment lands, a skill",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/creator-portfolio",+ "title": "Docs: Creator portfolio: /profile and /u/:username",+ "description": "Everything a creator makes on three.ws (avatars, agents, forged models,",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/agent-wallet-api",+ "title": "Docs: Agent wallet control API",+ "description": "Every three.ws agent owns one custodial Solana wallet. Seven owner-only HTTP surfaces hang off it, and this is their developer reference: exact routes, exact request and response JSON, exact error codes, and a working curl call for each.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/vaults",+ "title": "Docs: USDC agent vaults: the deep reference",+ "description": "A vault lets strangers put real USDC behind one trading agent, on terms the agent's owner publishes up front. The product-level tour (who each surface is for, how vaults sit next to the Arena, the Theater and Swarms) is in trading-arenas.md, under \"Back-an-Agent Vaults\". Read that first.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/user-wallet",+ "title": "Docs: Your master wallet: the per-user custodial hub",+ "description": "Every three.ws agent owns a wallet (agent-wallets.md). Separately, every user account can own one custodial wallet of its own: the master wallet. It is the financial hub for the person rather than the bot.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/copy-trading",+ "title": "Docs: Copy Trading",+ "description": "Copy trading on three.ws lets one wallet follow another wallet's real trades. There are two separate engines behind that sentence, they have different risk profiles, and it matters which one you are using:",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/deployments",+ "title": "Docs: On-chain Deployments",+ "description": "/deployments is the live, cross-chain feed of agent identities landing on-chain: every ERC-8004 Identity Registry registration on EVM and every Metaplex Core agent mint on Solana, in one chronological stream, as each one lands. It is a read-only public surface.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/ca2x402",+ "title": "Docs: CA to x402",+ "description": "Paste a token contract address, get back a live, agent-payable x402",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/agent-economy-volume",+ "title": "Docs: Agent Economy Volume",+ "description": "/agent-economy-volume is the public",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/viability",+ "title": "Docs: Viability",+ "description": "/viability answers one question about three.ws",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/press-kit",+ "title": "Docs: Press kit",+ "description": "Everything a journalist, analyst, conference organiser, or partner needs to write about three.ws: the marks, the announcement graphics, approved boilerplate at three lengths, the fast facts, and the rules that govern all of it.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/partners",+ "title": "Docs: Partner ecosystem",+ "description": "three.ws/partners is the public map of the cloud, AI, hardware, infrastructure, and media programmes three.ws takes part in.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/agent-identities",+ "title": "Docs: Agent Identity Studio: a brand brief becomes a 3D identity",+ "description": "Every AI agent deserves a face.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/avatar-engines",+ "title": "Docs: Avatar Engines Atlas",+ "description": "A factual map of the open-source and commercial systems that build high-quality and photoreal 3D human avatars: Gaussian-splat heads, single-photo humans, text-to-avatar generators, and the production rig formats three.ws already animates.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/stage",+ "title": "Docs: Living Stages",+ "description": "A Living Stage is a 3D venue where an embodied AI agent performs a live show for a co-present crowd. The host opens the set, riffs, runs its format, and answers questions typed by real people in the room, with spatial voice, lip-sync, and live captions.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/world-lines",+ "title": "Docs: World Lines: agent-signed proof of presence",+ "description": "A World Line is a quest an agent leaves at a real place.",+ "priority": 0.7,+ "changefreq": "monthly"+ },+ {+ "path": "/docs/walk-leaderboard",+ "title": "Docs: Walk Leaderboard",+ "description": "Every step your avatar takes on three.ws is measured, rolled up, and ranked. The Walk Leaderboard is the public board for it: walkers ordered by distance walked, sites visited, or time on their feet, over today, this week, or all time.",+ "priority": 0.7,+ "changefreq": "monthly"}]},diff --git a/docs/tutorials/agent-spending-envelope.md b/docs/tutorials/agent-spending-envelope.mdnew file mode 100644index 000000000..b7dbe535e--- /dev/null+++ b/docs/tutorials/agent-spending-envelope.md@@ -0,0 +1,549 @@+# Give an Agent a Spending Envelope (No Private Key)++By the end of this tutorial your agent will be able to buy things on the open internet, in real money, with a hard ceiling you set, and it will never touch a private key to do it. You create a budget from prepaid credits, get back a bearer token, and hand that token to the agent. The agent proposes a spend; the platform's spend governor decides whether to allow it, signs the payment with its own Solana wallet, and writes the result to a ledger you can read. Cancel the session and every unspent cent comes back to your credits.++This is the safe shape for autonomous spending. The usual alternative is to give an agent a funded wallet, which means giving it a key, which means the worst case is "the agent drained the wallet". Here the worst case is "the agent spent the budget you gave it, on hosts you allowed, in increments you capped".++> ## This spends real USDC+>+> Step 6 moves real money on Solana mainnet. It is not a sandbox and there is no undo on a settled payment. Every amount in this tutorial is deliberately tiny: a **$0.05** budget, a **$0.002** per-call cap, and one **$0.001** call. That is one twentieth of a cent per request. Keep those numbers until the whole loop works, then raise them once and watch the ledger.+>+> Steps 1 to 5 and step 7 cost nothing. Step 7 in particular is a full end-to-end wiring test against a free endpoint, so you can prove the plumbing before a single cent leaves your balance. Do it in that order.++**What you'll build:**++- A funded credit balance on three.ws, topped up from a Solana wallet you control+- A Payment Session: a spend envelope with a total budget, a per-call ceiling, a host allowlist, and an expiry+- An agent process holding nothing but a `pss_...` bearer token, calling paid x402 endpoints through `POST /api/pay/execute`+- A real settled payment with an on-chain transaction hash and an explorer link+- The audit trail: a per-session execution ledger showing every attempt, its price, its host, and its outcome+- A clean teardown: cancel the session, refund the remainder, verify the balance came back++**Prerequisites:**++- A three.ws account. Sign in at [three.ws/login](https://three.ws/login).+- A **Solana wallet linked to that account**, holding a little SOL or $THREE. Credits are funded by an on-chain transfer that the platform verifies, and it requires that one of the transaction's signers is a wallet linked to your account. Signing in with the wallet is the simplest way to link it.+- An API key for scripting, from `/dashboard` → **API Keys** → **Create Key**. The session and credits endpoints accept any authenticated bearer token; they do not require a special scope. A browser session cookie works too, and needs no CSRF token on these routes. See the [Authentication guide](/docs/authentication.md).+- `curl` and `jq`. Every command below is copy-pasteable.+- Optional but useful: read the [Payment Sessions reference](/docs/payment-sessions.md) first. This tutorial is the guided path through it; that page is the exhaustive field-by-field contract.++Set these once in your shell and the rest of the tutorial runs as written:++```bash+BASE=https://three.ws+AUTH='authorization: Bearer sk_live_replace_me'+```++---++## Step 1 - Understand what the token is, before you make one++Three things carry money in this system, and confusing them is the only way to get hurt:++| Thing | What it is | Blast radius if leaked |+|---|---|---|+| Your **Solana wallet key** | Actual custody of actual funds | Total. Never goes near an agent. The platform never asks for it. |+| Your **API key** (`sk_live_...`) | Your account identity | Can create sessions, which debits your credits. Treat as a password. Server-side only. |+| A **session token** (`pss_...`) | A time-bounded, capped, host-restricted spending grant | Limited to that session's remaining budget, on that session's allowed hosts, in increments under that session's per-call cap, until that session's expiry. |++Only the third one goes to the agent. That asymmetry is the entire point: the session token is designed to be handed to a process you do not fully trust, because the damage it can do is bounded by policy you wrote and the platform enforces.++The token is shown **exactly once**, at creation. The platform stores only an HMAC-SHA256 hash of it. If you lose it, you cannot recover it; cancel the session (which refunds the remainder) and create a new one.++---++## Step 2 - Check your credit balance++Credits are your prepaid balance, denominated in US dollars. A session's budget is debited from credits at creation and refunded to credits when the session ends.++```bash+curl -s $BASE/api/credits -H "$AUTH" | jq '{balance_usd, lifetime_deposited_usd, deposit}'+```++```json+{+ "balance_usd": 0,+ "lifetime_deposited_usd": 0,+ "deposit": {+ "wallet": "<the platform deposit address, read it from this response>",+ "network": "mainnet",+ "accepts": ["SOL", "THREE"],+ "three_mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "three_symbol": "THREE",+ "three_decimals": 6+ }+}+```++Read the deposit address out of this response rather than hardcoding it anywhere. It is served by the API precisely so that it can change without breaking your integration.++If `balance_usd` already covers the $0.05 you need, skip to Step 4.++Unauthenticated calls return `401 unauthorized` with `"sign in to view your credits"`. If you see that, your `AUTH` header is wrong or the key was revoked.++---++## Step 3 - Top up, if you need to++Funding is a two-part move, and the split matters: you send the transfer yourself, from your own wallet, and then you tell the platform to go look at it. The platform never initiates a transfer on your behalf and never needs your key.++1. **Send SOL or $THREE to the deposit wallet** from the Solana wallet linked to your account. Use whatever you normally use: a browser wallet, the CLI, an exchange withdrawal will *not* work because the signer must be your linked wallet. A dollar or two of SOL is plenty for this tutorial and leaves headroom to experiment.++2. **Verify the transfer** and get credited:++```bash+curl -s $BASE/api/credits/deposit \+ -H "$AUTH" \+ -H 'content-type: application/json' \+ -d '{ "asset": "SOL", "tx_signature": "<your transaction signature>", "network": "mainnet" }' | jq+```++```json+{+ "ok": true,+ "replay": false,+ "balance_usd": 2.14,+ "credited_usd": 2.14,+ "asset": "SOL",+ "amount": 0.0134,+ "price_usd": 160,+ "tx_signature": "..."+}+```++The platform reads the transaction on-chain, computes what actually arrived from the pre and post balances, prices it, and credits you. It is server-authoritative: you cannot inflate a deposit by claiming a bigger number, because no number you send is trusted.++Two responses to expect and handle:++- **`{ "ok": false, "pending": true, "status": "awaiting_finalization" }`** means the transaction is confirmed but not yet finalized. This is normal. Wait a few seconds and call again with the same signature.+- **`"replay": true` with `credited_usd: 0`** means that signature and asset were already credited. Crediting is idempotent per (signature, asset), so a retry after a network timeout is always safe.++The one error worth calling out is `403 wallet_not_linked`: the transfer was real but no signer on it is a wallet linked to your account. Sign in with the sending wallet to link it, then re-run the same verify call. The other codes (`tx_not_found`, `tx_failed`, `no_funds_received`, `amount_too_small`) are listed in the [Payment Sessions reference](/docs/payment-sessions.md).++---++## Step 4 - Read the price before you authorize a budget++Never size a budget from a guess. x402 endpoints publish their price in the `402` challenge they return to an unpaid request, and reading that challenge is free. Do it first.++```bash+curl -s $BASE/api/x402/rate-limit-probe | jq '{+ price: [.accepts[] | select(.network | startswith("solana")) | {network, amount, asset, feePayer: (.extra.feePayer != null)}],+ what: .resource.description+}'+```++```json+{+ "price": [+ {+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",+ "amount": "1000",+ "asset": "<the Solana USDC mint>",+ "feePayer": true+ }+ ],+ "what": "Rate-Limit Capacity Probe - pay $0.001 USDC to learn how many more calls the x402 autonomous loop can make to a target endpoint..."+}+```++Three things to read off that:++- **`amount` is in atomic units**, and USDC has 6 decimals, so `1000` is $0.001. A session's `max_per_tx_usd` is expressed in dollars, so the cap you want here is anything above `0.001`.+- **The accept must be on a `solana...` network** and must carry `extra.feePayer`. `POST /api/pay/execute` settles on Solana only. An endpoint that offers no Solana option fails with `no_solana_accept` and your budget is never touched.+- **The service fee payer covers the Solana transaction fee.** Your budget is charged the payment amount and nothing else.++This same endpoint answers a genuinely useful question (how much x402 capacity is left before a rate limit bites), which is why it makes a good first purchase instead of a throwaway. Browse more at [/bazaar](/bazaar), or read the [x402 protocol doc](/docs/x402.md) for how the challenge is constructed.++---++## Step 5 - Create the session++Now the envelope. Four policy fields do all the work:++```bash+CREATE=$(curl -s $BASE/api/pay/session \+ -H "$AUTH" \+ -H 'content-type: application/json' \+ -d '{+ "label": "capacity watcher",+ "budget_usd": 0.05,+ "max_per_tx_usd": 0.002,+ "allowed_hosts": ["three.ws"],+ "expiry_seconds": 3600,+ "metadata": { "purpose": "tutorial", "owner": "me" }+ }')++TOKEN=$(echo "$CREATE" | jq -r .token)+SID=$(echo "$CREATE" | jq -r .session.id)+echo "session $SID created"+```++The response is `201` and contains the token once:++```json+{+ "session": {+ "id": "0b2f...",+ "label": "capacity watcher",+ "budget_usd": 0.05,+ "spent_usd": 0,+ "remaining_usd": 0.05,+ "max_per_tx_usd": 0.002,+ "allowed_hosts": ["three.ws"],+ "network": "solana",+ "status": "active",+ "expires_at": "2026-07-30T05:00:00.000Z",+ "metadata": { "purpose": "tutorial", "owner": "me" },+ "created_at": "2026-07-30T04:00:00.000Z"+ },+ "token": "pss_0b2f..._4f8a...",+ "note": "Store this token securely - it is shown once and cannot be recovered."+}+```++Why each field matters:++| Field | This tutorial | How to think about it |+|---|---|---|+| `budget_usd` | `0.05` | The total the agent can ever spend on this token. Debited from credits **now**, refunded on cancel. Min $0.001, max $1000. |+| `max_per_tx_usd` | `0.002` | The ceiling on any single call. This is your defence against one expensive endpoint eating the whole envelope in one request. Set it just above the prices you expect, not at the budget. `null` removes the cap; do not do that on a first run. |+| `allowed_hosts` | `["three.ws"]` | Exact hostname or any subdomain of it. A call to any other host fails with `allowlist_blocked` before any money moves. An empty array means **any host**, which is almost never what you want. Max 50 entries. |+| `expiry_seconds` | `3600` | One hour. After this the session stops spending, and a sweep (`/api/cron/payment-session-sweep`, every 5 minutes) refunds the remainder automatically. Min 60, max 7776000 (90 days). |++Two more you did not set: `agent_id` associates the session with one of your agents, and `metadata` is arbitrary JSON stored and echoed back, which is where to put your own correlation IDs.++If your balance cannot cover the budget you get `402 insufficient_credits`, and the message includes both the required and available amounts. Out-of-range values give `400 invalid_budget` or `400 invalid_ttl`.++---++## Step 6 - Hand the token to the agent, and nothing else++The agent process gets one secret, by environment variable, and it is not your API key:++```bash+export THREE_WS_SESSION_TOKEN="$TOKEN"+```++That is the whole handoff. The agent needs no wallet, no seed phrase, no RPC endpoint, no API key, and no knowledge of Solana. If the agent runs on a different machine, in a container, or as a subprocess of an LLM loop, this is the only credential that crosses the boundary.++A useful mental check before you continue: **if this token leaked to a stranger right now, what could they do?** They could spend up to $0.05, in slices of at most $0.002, on `three.ws` only, for the next hour. That is the security model, and it is legible precisely because you wrote all four numbers yourself.++---++## Step 7 - Prove the wiring with a free call (costs nothing)++Before you spend anything, run the exact same code path against an endpoint that does not charge. `POST /api/pay/execute` probes the target first; if the target answers with anything other than `402`, the response comes straight back and the session is not touched at all.++`/api/x402/echo` is a free debug endpoint that reflects whatever you send it. Perfect for this:++```bash+curl -s $BASE/api/pay/execute \+ -H 'content-type: application/json' \+ -d '{+ "session_token": "'"$TOKEN"'",+ "url": "'"$BASE"'/api/x402/echo",+ "method": "GET"+ }' | jq+```++```json+{+ "ok": true,+ "paid": false,+ "note": "Endpoint served response without a 402 - no payment needed.",+ "status": 200,+ "result": { "ok": true, "method": "GET", "headers": { "...": "..." }, "body": null, "ts": "..." }+}+```++`"paid": false` is the signal you are looking for. Your token is valid, your JSON is well-formed, your network path works, and your budget is still exactly $0.05. Confirm that:++```bash+curl -s $BASE/api/pay/session/$SID -H "$AUTH" | jq '.session | {spent_usd, remaining_usd, status}'+```++While you are here, prove the allowlist works too. This is also free, because governance runs before anything is signed:++```bash+curl -s $BASE/api/pay/execute \+ -H 'content-type: application/json' \+ -d '{ "session_token": "'"$TOKEN"'", "url": "https://example.com/anything" }' | jq+```++```json+{+ "error": "allowlist_blocked",+ "error_description": "Host example.com is not in this session's allowlist",+ "detail": { "host": "example.com", "allowlist": ["three.ws"] }+}+```++Good. The policy is not decorative.++---++## Step 8 - Spend it++This is the step that moves money. One call, $0.001.++```bash+curl -s $BASE/api/pay/execute \+ -H 'content-type: application/json' \+ -d '{+ "session_token": "'"$TOKEN"'",+ "url": "'"$BASE"'/api/x402/rate-limit-probe",+ "method": "POST",+ "body": { "endpoint": "/api/x402/forge" },+ "idempotency_key": "envelope-tutorial-001"+ }' | jq '{paid, payment, session, duration_ms}'+```++```json+{+ "paid": true,+ "payment": {+ "session_id": "0b2f...",+ "amount_usd": 0.001,+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",+ "payer": "<platform payer wallet>",+ "pay_to": "<the service's receiving wallet>",+ "tx_hash": "5Kd...",+ "explorer": "https://solscan.io/tx/5Kd..."+ },+ "session": { "id": "0b2f...", "spent_usd": 0.001, "remaining_usd": 0.049 },+ "duration_ms": 1843+}+```++Open the `explorer` link. There is a real transfer there, on mainnet, for a tenth of a cent. That is the whole thesis of this tutorial made concrete: an agent bought something, and the only thing it was ever given was a policy-bounded token.++**Always send an `idempotency_key`.** The executions table is unique on it, so if your HTTP client retries after a timeout, the duplicate submission collapses to a single recorded execution instead of double-charging. Make it deterministic from the work you are doing (a job ID, a date plus a counter), not random.++What just happened inside the platform, in order:++1. **Token check** against the stored hash.+2. **Probe.** The endpoint is fetched with an SSRF-guarded client (20 second timeout, redirects not followed) to read its `402` challenge.+3. **Accept selection.** A Solana USDC accept with a `feePayer` is picked out of `accepts[]`.+4. **Governance.** Five checks in order: session active, not expired, host allowed, amount under `max_per_tx_usd`, remaining budget sufficient. The budget reservation is a single atomic SQL update, so concurrent calls can never collectively overspend the envelope. If two racing calls each fit individually but not together, exactly one wins and the other gets `insufficient_budget`.+5. **Sign and pay.** The platform's Solana payer wallet signs a USDC transfer matching the accept and re-requests the endpoint with an `X-PAYMENT` header.+6. **Record.** The execution lands in the session ledger with the settlement transaction hash and an explorer link.++Your agent's code did not participate in steps 2 through 6. It named a URL and a price ceiling. That is the division of labour: **the agent proposes spend; governance enforces policy.**++---++## Step 9 - Read the ledger++Two reads, both cheap, both worth wiring into whatever dashboard you already have.++The session's current state:++```bash+curl -s $BASE/api/pay/session/$SID -H "$AUTH" \+ | jq '.session | {status, budget_usd, spent_usd, remaining_usd, max_per_tx_usd, allowed_hosts, expires_at}'+```++And every payment attempt it made, newest first:++```bash+curl -s "$BASE/api/pay/session/$SID/executions" -H "$AUTH" | jq '.items'+```++```json+[+ {+ "id": "...",+ "endpoint_url": "https://three.ws/api/x402/rate-limit-probe",+ "endpoint_host": "three.ws",+ "method": "POST",+ "amount_usd": 0.001,+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",+ "tx_hash": "5Kd...",+ "payer_address": "...",+ "payee_address": "...",+ "status": "settled",+ "error_code": null,+ "duration_ms": 1843,+ "created_at": "2026-07-30T04:01:00.000Z"+ }+]+```++Failures are recorded here too, with `status: "failed"` and an `error_code`, which makes this the first place to look when an agent claims it could not buy something. Both endpoints paginate with `limit` (default 20, max 100) and `cursor`.++For the account-wide view, `GET /api/pay/session` lists all your sessions newest-first and adds aggregate `stats`: session counts by status, total budget, total spent, settled and failed execution counts, and how many distinct endpoints you have paid.++```bash+curl -s $BASE/api/pay/session -H "$AUTH" | jq .stats+```++---++## Step 10 - Tighten the policy without restarting the agent++An active session's policy is mutable. `label`, `allowed_hosts`, and `max_per_tx_usd` can all be changed in place, and the change applies to the next call the agent makes. The token does not rotate, so the agent never notices.++```bash+# Lower the per-call ceiling to $0.0015 and add a second allowed host.+curl -s -X PATCH $BASE/api/pay/session/$SID \+ -H "$AUTH" -H 'content-type: application/json' \+ -d '{ "max_per_tx_usd": 0.0015, "allowed_hosts": ["three.ws", "api.example.com"] }' \+ | jq '.session | {max_per_tx_usd, allowed_hosts}'+```++Budget, network, and expiry are immutable after creation. That is deliberate: those three are the guarantees you gave yourself, and a mutable budget is not a budget. If you need more headroom, cancel and create a new session, or run a second one alongside.++Pass `"max_per_tx_usd": null` to remove the cap entirely. `400 nothing_to_update` means none of the three recognized fields was present.++---++## Step 11 - Wire it into an agent loop++Everything above as the code an agent actually runs. Note what is absent: no wallet library, no key handling, no chain RPC, no retry-on-chain logic.++```js+// spender.js - the entire payment capability of an agent, in 40 lines.+const BASE = 'https://three.ws';+const TOKEN = process.env.THREE_WS_SESSION_TOKEN;+if (!TOKEN) throw new Error('THREE_WS_SESSION_TOKEN is required');++/**+ * Buy one thing. Returns { paid, result } on success.+ * Throws a labelled error the caller can branch on.+ */+async function buy(url, { method = 'GET', body = null, idempotencyKey } = {}) {+ const res = await fetch(`${BASE}/api/pay/execute`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ session_token: TOKEN,+ url,+ method,+ ...(body ? { body } : {}),+ ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),+ }),+ });+ const data = await res.json();++ if (res.ok) {+ return { paid: data.paid === true, result: data.result, payment: data.payment ?? null };+ }++ // Budget exhausted or policy refused: a normal, expected outcome. Stop cleanly.+ if (['insufficient_budget', 'per_tx_exceeded', 'allowlist_blocked',+ 'session_inactive', 'session_expired'].includes(data.error)) {+ const err = new Error(data.error_description || data.error);+ err.code = data.error;+ err.terminal = true;+ throw err;+ }++ // Chain state unknown: never retry blind. Read the ledger first.+ if (['settle_uncertain', 'upstream_error'].includes(data.error)) {+ const err = new Error(`${data.error}: check the session ledger before retrying`);+ err.code = data.error;+ err.terminal = true;+ throw err;+ }++ const err = new Error(data.error_description || data.error || `HTTP ${res.status}`);+ err.code = data.error;+ throw err;+}++// The agent's actual job: watch remaining x402 capacity, stop when the envelope runs out.+for (let i = 1; i <= 5; i++) {+ try {+ const { paid, result, payment } = await buy(`${BASE}/api/x402/rate-limit-probe`, {+ method: 'POST',+ body: { endpoint: '/api/x402/forge' },+ idempotencyKey: `capacity-check-${new Date().toISOString().slice(0, 10)}-${i}`,+ });+ console.log(`check ${i}:`, result, paid ? `(paid ${payment.amount_usd} USD, ${payment.tx_hash})` : '(free)');+ } catch (err) {+ console.error(`check ${i} stopped: ${err.code} - ${err.message}`);+ if (err.terminal) break;+ }+ await new Promise((r) => setTimeout(r, 5000));+}+```++Run it with a session token in the environment and it will buy until the envelope is empty, then stop with `insufficient_budget`. That is the behaviour you want from an autonomous spender: it hits a wall you built, and the wall holds.++The two `terminal` branches are the important design decision. `insufficient_budget` and friends mean "policy said no", which is not an error to retry. `settle_uncertain` and `upstream_error` mean "money may have moved and we cannot prove otherwise", which is emphatically not an error to retry. Both stop the loop; only one of them needs a human to look at the ledger.++---++## Step 12 - Cancel and get the refund++Teardown is one call, and it is the reason a tight expiry costs you nothing.++```bash+curl -s -X DELETE $BASE/api/pay/session/$SID -H "$AUTH" | jq+```++```json+{ "cancelled": true, "session_id": "0b2f...", "refunded_usd": 0.049 }+```++The unspent $0.049 is back in credits immediately. Verify:++```bash+curl -s $BASE/api/credits -H "$AUTH" | jq '{balance_usd, ledger: [.ledger[0]]}'+```++The refund is idempotent per session, so a repeated DELETE returns `404 not_found` rather than refunding twice. Sessions that pass their expiry while still active are refunded automatically by the 5-minute sweep, so there is nothing to clean up manually if you simply walk away.++Session `status` after teardown is one of:++| Status | Means |+|---|---|+| `active` | Spending allowed |+| `exhausted` | Budget fully spent. Can still be cancelled (refund will be $0). |+| `cancelled` | You called DELETE. Remainder refunded. |+| `expired` | Passed `expires_at`. The sweep refunded the remainder. |++---++## Troubleshooting++| Response | Meaning | Fix |+|---|---|---|+| `401 unauthorized` on `/api/credits` or `/api/pay/session` | Missing or bad bearer token | Check the `AUTH` header. Keys are shown once at creation; if you lost it, make a new one. |+| `400 missing_token` on execute | No `session_token` in the JSON body | Execute authenticates with the session token in the **body**, not an `Authorization` header. |+| `401 invalid_token` | Token malformed, unknown, or does not match its hash | The token is unrecoverable by design. Cancel the session and create a new one. |+| `402 insufficient_credits` on create | Balance below `budget_usd` | Top up (Step 3). The message states required and available. |+| `403 allowlist_blocked` | Target host not in `allowed_hosts` | `detail` carries the host and the allowlist. PATCH the session to add the host, or fix the URL. Subdomains of an allowed host are allowed. |+| `402 per_tx_exceeded` | Endpoint costs more than `max_per_tx_usd` | `detail` carries `amount_usd` and `cap_usd`. Raise the cap deliberately or pick a cheaper endpoint. |+| `402 insufficient_budget` | Remaining budget below the price | Expected end state. Create a new session, or note that a concurrent call won the race. |+| `422 no_solana_accept` | The endpoint offers no Solana option | Execute settles on Solana only. Endpoints that are Base-only cannot be paid through a session; pay those with your own client (see [x402 Buyer Client](/docs/x402-buyer.md)). |+| `422 unsupported_asset` / `missing_fee_payer` | The Solana accept is not USDC, or omits `extra.feePayer` | Not fixable from your side. Report it to the endpoint's operator. |+| `502 endpoint_unreachable` / `invalid_challenge` | Could not reach or parse the endpoint | Probe it yourself with a plain `curl` (Step 4). Budget untouched. |+| `502 settle_uncertain` | Network failure **after** signing | Do not retry. Read `GET /api/pay/session/:id/executions` and the payer wallet's activity first. Budget stays reserved on purpose. |+| `502 upstream_error` | Endpoint returned a non-402 error after payment | Same rule: check the ledger before retrying. Budget stays reserved. |+| `503 wallet_unconfigured` | Platform payer wallet is not configured in this environment | Nothing to fix client-side. Budget is rolled back. |+| `429` with `Retry-After` | Session and credits routes share a strict bucket (50 requests per 10 minutes per IP); `GET /api/credits` uses the read bucket (300 per 5 minutes) | Honour `Retry-After`. Do not poll the ledger in a tight loop. |++The two "budget stays reserved" cases are the only place the system deliberately declines to give money back, and it is the right call: funds may have moved on-chain, and the platform refuses to silently restore budget it cannot prove was unspent. Both are recorded as `failed` executions with the matching `error_code`, so the evidence is always in the ledger.++---++## What you learned++- The three-credential model, and why only the weakest one ever reaches an agent+- How to fund credits from a Solana wallet with a server-verified, idempotent deposit+- How to read an x402 price for free before authorizing any budget+- The four policy fields that define an envelope, and which of them are deliberately immutable+- How to prove the entire payment path against a free endpoint before spending a cent+- What the spend governor checks, in what order, and why the budget reservation is atomic+- How to read the execution ledger, and which two failure codes must never be retried blind+- Cancel-and-refund, plus the automatic sweep that makes short expiries free++## Next steps++- Build the other side of the trade: an endpoint that *charges* agents, in [Build a paid x402 endpoint](/docs/tutorials/paid-x402-endpoint.md).+- Pay from your own wallet instead of a platform-managed envelope, in [Discover and pay for an x402 service](/docs/tutorials/pay-for-x402-service.md).+- Debug a payment that misbehaved with the free echo, debug, and receipt-verification tools in [x402 Developer Tools](/docs/x402-dev-tools.md).+- Give the spending agent a body and a personality so a human can watch it work: [Give your agent a personality](/docs/tutorials/agent-personality.md).+- Read the full field-by-field contract in the [Payment Sessions reference](/docs/payment-sessions.md).diff --git a/docs/tutorials/render-avatar-images.md b/docs/tutorials/render-avatar-images.mdnew file mode 100644index 000000000..ca5637ec8--- /dev/null+++ b/docs/tutorials/render-avatar-images.md@@ -0,0 +1,485 @@+# Put a 3D Avatar in an `<img>` Tag++By the end of this tutorial you will be rendering live 3D avatars as ordinary images, from a URL, with no 3D engine anywhere in your stack. No three.js, no WebGL context, no GLB loader, no canvas. Just an `<img src>` that happens to point at a headless renderer.++That unlocks the places WebGL cannot go: Open Graph and Twitter cards, transactional email, a Notion page, a PDF, a React Server Component, a Discord bot, a print sheet, an e-ink display, a Rust service that has no business booting a browser. Anywhere an image works, a posed and expressive 3D character now works too.++**What you'll build:**++- A profile image for any public three.ws avatar, in four camera framings, any size up to 2048px, any background including transparent+- Posed renders: the same avatar waving, meditating, or landing like a superhero, driven by a pose ID from a live catalog+- Facial expressions: ARKit-52 morph targets driven from the query string, so one avatar produces a whole sheet of emotions+- A social card that renders the avatar as its `og:image`+- The same trick for any GLB on the internet, including models that were never saved as three.ws avatars, with a free camera orbit+- A real client-side viewer on your own domain, using the CORS-open GLB proxy+- Cache behaviour you can reason about, and the two headers that tell you what happened++**Prerequisites:**++- `curl` and a text editor. That is the entire toolchain.+- No account, no API key, no auth handshake. Every endpoint here is public and keyless.+- Optional: the [Media & Render API reference](/docs/media-api.md) is the exhaustive parameter contract. This tutorial is the guided path through it.++Every command below is real and runs as written against production. The avatar IDs are public featured avatars.++---++## Step 1 - Ask the endpoint to describe itself++Call `/api/avatar/render` with no parameters and it returns its own documentation: every parameter with its type, range, and default; every camera preset with its actual spherical angles; and the full pose catalog.++```bash+curl -s https://three.ws/api/avatar/render | jq 'keys'+```++```json+["endpoint", "description", "parameters", "poses", "scenes", "example"]+```++That response is the machine-readable source of truth, which matters more than it sounds: it means a code generator, an LLM tool definition, or a build script never has to hardcode a list that can drift. Look at the camera presets:++```bash+curl -s https://three.ws/api/avatar/render | jq .scenes+```++```json+{+ "full-body": { "phi": 80, "theta": 0 },+ "upper-body": { "phi": 82, "theta": 5 },+ "portrait": { "phi": 84, "theta": 8 },+ "headshot": { "phi": 86, "theta": 5 }+}+```++`phi` is pitch measured from straight down the top of the head, `theta` is yaw. The presets are not just crops: each one moves the camera, so a `headshot` has different perspective foreshortening than a cropped `full-body` would. That is why they look right instead of looking like zoomed screenshots.++And the poses:++```bash+curl -s https://three.ws/api/avatar/render | jq '.poses | length'+```++```+28+```++Grouped, the catalog is:++| Group | Pose IDs |+|---|---|+| Standing | `tpose`, `apose`, `relaxed`, `contrapposto`, `hands-up`, `wave`, `hands-on-hips`, `salute` |+| Action | `walk-step`, `run`, `jump`, `punch`, `archery`, `superhero-landing`, `fighting-stance` |+| Sitting & Floor | `sit-chair`, `sit-floor`, `kneel`, `crouch`, `thinker` |+| Expressive | `praying`, `meditate`, `warrior2`, `arabesque`, `flex`, `point`, `facepalm`, `bow` |++Fetch that list at build time rather than pasting it into your code. It grows.++---++## Step 2 - Pick a public avatar++You need an avatar ID (a UUID). The featured list is public:++```bash+curl -s https://three.ws/api/avatars/featured \+ | jq -r '.avatars[] | "\(.id) \(.name)"' | head -8+```++```+81a076b6-55ff-49a2-b007-1d88e7dce2aa ansem-with-animation+bea9f0b9-3442-4544-84df-912989e86211 Boss Vernington+13f259c7-7024-4d68-b1f0-dbbf52c06209 Michelle+9c192f82-059f-44b3-b21d-100583c743fd LittlestTokyo+a4bad2f5-8a07-43cf-82e5-b6ba1314441e Selfie Girl+```++Two of those get used throughout this tutorial, and the difference between them is the single most important practical fact on this page:++| Avatar | ID | Rig | Morph targets |+|---|---|---|---|+| **Michelle** | `13f259c7-7024-4d68-b1f0-dbbf52c06209` | Full humanoid skeleton, poses beautifully | **Zero.** Expressions are silently ignored. |+| **Selfie Girl** | `a4bad2f5-8a07-43cf-82e5-b6ba1314441e` | Full humanoid skeleton | **63**, including the full ARKit-52 set |++Poses come from the skeleton. Expressions come from morph targets. A model can have one without the other, and asking for a facial expression on a model with no morph targets returns a perfectly valid `200` with a completely unchanged face. Step 4 covers how to tell before you waste an afternoon.++Only **public** and **unlisted** avatars render. A private one returns `403 private`; one that does not exist returns `404 not_found`. Your own avatars appear at `/agents/<id>`, and their IDs work here as soon as their visibility is public or unlisted.++---++## Step 3 - The `<img>` tag++This is the whole feature:++```html+<img+ src="https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&scene=portrait&size=256"+ width="256"+ height="256"+ alt="Michelle, a 3D avatar, portrait framing"+/>+```++Paste it into any HTML file and open it. That is a real-time three.js render, produced server-side by headless chromium, arriving as 39KB of PNG.++The same thing from the command line, which is how you should verify anything before wiring it into a page:++```bash+curl -sL -o portrait.png \+ 'https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&scene=portrait&size=256&bg=transparent'++file portrait.png+# portrait.png: PNG image data, 256 x 256, 8-bit/color RGBA, non-interlaced+```++**Note the `-L`.** A cached render answers `302` with a `location` pointing at the CDN copy. Browsers and `<img>` tags follow that automatically; `curl` does not unless you tell it to. Omit `-L` and you get a zero-byte file and a confusing afternoon. Step 8 explains why the redirect exists.++Always set explicit `width` and `height` on the tag, matching the pixels you asked for. It costs nothing and it removes a layout shift.++---++## Step 4 - Control the frame: scene, size, background, format++Four parameters cover almost every real use.++```bash+A=13f259c7-7024-4d68-b1f0-dbbf52c06209+R=https://three.ws/api/avatar/render++# A tight headshot on a dark surface, sized for a comment avatar.+curl -sL -o comment-avatar.png "$R?avatar=$A&scene=headshot&size=128&bg=%23111827"++# Full body, transparent, tall rather than square: perfect for a hero column.+curl -sL -o hero.png "$R?avatar=$A&scene=full-body&width=640&height=960&bg=transparent"++# Lossy and small, for a feed where bytes matter more than edges.+curl -sL -o thumb.webp "$R?avatar=$A&scene=upper-body&size=192&format=webp&quality=72"+```++| Parameter | Values | Notes |+|---|---|---|+| `avatar` | UUID | Required. Omit it and you get the self-describing JSON from Step 1. |+| `scene` | `full-body`, `upper-body`, `portrait`, `headshot` | Default `upper-body`. An unknown value is a hard `400 invalid_scene`, and the error lists the valid ones. |+| `size` | 64 to 2048 | Square. Default 512. |+| `width`, `height` | 64 to 2048 | Override `size` per axis. Set both for a non-square frame. |+| `bg` | any CSS color, or `transparent` | Default `transparent`. URL-encode the `#`: `bg=%23111827`. |+| `format` | `png`, `jpeg`, `webp` | Default `png`. |+| `quality` | 1 to 100 | Default 90. Applies to `jpeg` and `webp` only. |++Two behaviours worth knowing because they differ:++- **Dimensions and quality are clamped, not rejected.** `size=9999` returns a valid 2048px image, not a `400`. That is friendly for a URL assembled by a template, and it means you cannot detect a mistake from the status code. Check the `x-render-size` response header if you need certainty.+- **`scene`, `pose`, and `expression` are validated strictly.** A typo in any of those three is a `400` with a specific code. That is also correct: silently substituting a default pose would produce a wrong image that looks right.++Transparent PNG is the default for a reason. It composites onto whatever your page already is, including a gradient or a photo, without you having to match a background color that will change next quarter. Reach for an opaque `bg` when the consumer cannot handle alpha, which in practice means JPEG and some email clients.++---++## Step 5 - Pose it, and drive the face++Two more parameters and the same endpoint stops producing profile pictures and starts producing characters.++`pose` takes any ID from the Step 1 catalog:++```bash+A=13f259c7-7024-4d68-b1f0-dbbf52c06209+R=https://three.ws/api/avatar/render++curl -sL -o waving.png "$R?avatar=$A&scene=full-body&size=768&pose=wave&bg=transparent"+curl -sL -o thinking.png "$R?avatar=$A&scene=full-body&size=768&pose=thinker&bg=transparent"+curl -sL -o landing.png "$R?avatar=$A&scene=full-body&size=768&pose=superhero-landing&bg=transparent"+```++A wrong pose ID fails loudly:++```bash+curl -s "$R?avatar=$A&pose=moonwalk" | jq+```++```json+{+ "error": "unknown_pose",+ "error_description": "Unknown pose \"moonwalk\". GET /api/avatar/render for the catalog."+}+```++`expression` takes a URL-encoded JSON object of ARKit-52 morph target names mapped to weights from 0 to 1. **Use an avatar that actually has morph targets**, which is where Selfie Girl comes in:++```bash+SG=a4bad2f5-8a07-43cf-82e5-b6ba1314441e+R=https://three.ws/api/avatar/render++# Neutral, for comparison.+curl -sL -o face-neutral.png "$R?avatar=$SG&scene=headshot&size=384&bg=%23111827"++# Delighted: mouth open, big smile, brows up, eyes wide.+EXP='{"jawOpen":0.5,"mouthSmile":1,"browInnerUp":0.8,"eyeWideLeft":0.6,"eyeWideRight":0.6}'+curl -sL -o face-delighted.png \+ "$R?avatar=$SG&scene=headshot&size=384&bg=%23111827&expression=$(jq -rn --arg e "$EXP" '$e|@uri')"+```++Open both. The second one is visibly, unmistakably delighted. That is five numbers in a query string.++Useful morph names on a model with the full set: `jawOpen`, `mouthSmile`, `mouthSmileLeft`, `mouthSmileRight`, `mouthFrownLeft`, `mouthFrownRight`, `mouthPucker`, `browInnerUp`, `browDownLeft`, `browDownRight`, `eyeBlinkLeft`, `eyeBlinkRight`, `eyeSquintLeft`, `eyeSquintRight`, `eyeWideLeft`, `eyeWideRight`. The [ARKit-52 canonical set](/docs/animations.md) is the full vocabulary.++### How to tell whether an avatar has morph targets++Lookup is by **exact name** against the GLB's own morph target dictionary, with a lowercase fallback. There is no alias resolution and no error when a name misses: an unknown morph is skipped, and the render returns `200` with that part of the face untouched. So "my expression did nothing" is nearly always "this model has no morph target by that name", not "the endpoint is broken".++The cheap test is a byte-size comparison between a neutral render and an extreme one:++```bash+A=13f259c7-7024-4d68-b1f0-dbbf52c06209 # Michelle: zero morph targets+R=https://three.ws/api/avatar/render+E=$(jq -rn '{jawOpen:1,mouthSmile:1}|tostring|@uri')++curl -sL -o /dev/null -w 'neutral %{size_download}\n' "$R?avatar=$A&scene=headshot&size=256"+curl -sL -o /dev/null -w 'extreme %{size_download}\n"' "$R?avatar=$A&scene=headshot&size=256&expression=$E"+```++Identical byte counts mean nothing moved, which means no matching morph targets. Run the same two commands against Selfie Girl and the numbers differ. Do this once per model and write the answer down.++A malformed `expression` value, on the other hand, is a real `400`:++```json+{ "error": "invalid_expression", "error_description": "expression must be a JSON object of morph targets" }+```++---++## Step 6 - A social card++Now the payoff. A rendered avatar as an `og:image` means every share of the page shows the character, and the character updates when the avatar does, with no image pipeline and no asset to regenerate.++```html+<head>+ <meta property="og:title" content="Meet Michelle" />+ <meta property="og:description" content="A live 3D agent you can talk to." />+ <meta+ property="og:image"+ content="https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&scene=upper-body&width=1200&height=630&bg=%230a0a0a&format=jpeg&quality=88"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:image" content="https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&scene=upper-body&width=1200&height=630&bg=%230a0a0a&format=jpeg&quality=88" />+</head>+```++Four decisions in that URL, all deliberate:++- **1200x630** is the standard large-card ratio. Set `og:image:width` and `og:image:height` to match so scrapers do not have to fetch the bytes to lay out the card.+- **`format=jpeg`** because several social scrapers handle alpha PNG badly, and a card is always composited onto an opaque surface anyway.+- **An opaque `bg`** for the same reason. Transparent alpha on a card usually renders as black on one platform and white on another.+- **`scene=upper-body`** because a headshot in a 1.9:1 frame leaves enormous dead space on both sides.++Scrapers are not patient and they do not follow long redirect chains happily. Fetch the URL yourself once with `-L` before you ship the tag, so the render is already cached and the scraper's first visit is a fast redirect to the CDN rather than a cold render.++---++## Step 7 - Render any GLB, from any URL, at any angle++`/api/avatar/render` needs a three.ws avatar ID. Its sibling `POST /api/render/avatar-clip` takes a raw GLB URL instead, so it works on models that were never saved as avatars: something you generated in the [Forge](/forge), a file on your own CDN, a character out of the [free character library](/character-library). It also exposes a free camera orbit, which the avatar endpoint deliberately does not.++`GET` the same URL for the catalog, so you never hardcode a pose ID or guess a range:++```bash+curl -s https://three.ws/api/render/avatar-clip | jq '{poses: (.poses|length), cameraOrbit, background}'+```++```json+{+ "poses": 28,+ "cameraOrbit": {+ "theta": "0..360 (degrees, yaw)",+ "phi": "0..180 (degrees, pitch from top)",+ "radius": "meters or null for auto-frame"+ },+ "background": ["transparent", "#0a0a0a", "any CSS color"]+}+```++Then `POST` a render:++```bash+curl -s -D headers.txt -X POST https://three.ws/api/render/avatar-clip \+ -H 'content-type: application/json' \+ -d '{+ "glbUrl": "https://three.ws/avatars/selfie-girl.glb",+ "posePresetId": "wave",+ "cameraOrbit": { "theta": 25, "phi": 78, "radius": null },+ "background": "transparent",+ "width": 768,+ "height": 768,+ "expression": { "jawOpen": 0.35, "mouthSmile": 0.9, "browInnerUp": 0.5 }+ }' -o wave.png++grep -i '^x-render' headers.txt+```++```+x-render-width: 768+x-render-height: 768+x-render-background: transparent+x-render-pose: wave+x-render-pose-label: Wave hello+```++Those headers are the endpoint telling you exactly what it did, which is worth logging: `x-render-pose` present means a pose was applied, absent means the model was rendered in its bind pose.++| Field | Default | Notes |+|---|---|---|+| `glbUrl` | required | Public http(s) URL, **max 10 MB**. SSRF-guarded: private hosts, link-local addresses, and non-http schemes are rejected with `400 bad_request`. |+| `width`, `height` | 1024 | 64 to 2048. |+| `background` | `#0a0a0a` | Any CSS color, or `transparent`. Note the different default from `/api/avatar/render`. |+| `posePresetId` | none | An unknown ID is `400 unknown_pose`. |+| `cameraOrbit` | auto | `{ theta, phi, radius }`. `radius: null` auto-frames the model, which is what you want unless you are building a turntable. |+| `expression` | none | Same ARKit-52 morph map, same exact-name matching. |++**The 10 MB cap is the constraint that bites.** Plenty of interesting characters are bigger. Two ways through it: pick a smaller model, or shrink one first with `GET /api/avatar/optimize`, which re-encodes a three.ws-hosted GLB down to a texture budget you name:++```bash+curl -sL -D - -o small.glb \+ 'https://three.ws/api/avatar/optimize?src=https%3A%2F%2Fthree.ws%2Favatars%2Fselfie-girl.glb&textureSize=512&morphs=arkit52' \+ | grep -i 'x-three-ws'+```++```+x-three-ws-source-bytes: 2235548+x-three-ws-output-bytes: 1120932+```++`textureSize` accepts `128`, `256`, `512`, `1024`, `2048`, and `morphs=arkit52` drops every morph target outside the standard set. `src` must be on a three.ws-controlled origin (the app origin or the CDN host); anything else is `400 untrusted_source`. Full parameter list in the [Media & Render API reference](/docs/media-api.md).++For a turntable, hold everything constant and step `theta`:++```bash+for T in 0 45 90 135 180 225 270 315; do+ curl -s -X POST https://three.ws/api/render/avatar-clip \+ -H 'content-type: application/json' \+ -d "{\"glbUrl\":\"https://three.ws/avatars/selfie-girl.glb\",\"posePresetId\":\"apose\",\"cameraOrbit\":{\"theta\":$T,\"phi\":80,\"radius\":null},\"background\":\"transparent\",\"width\":512,\"height\":512}" \+ -o "turn-$T.png"+done+```++Eight frames, one A-pose, eight yaw angles. Assemble them into a sprite sheet or an animated WebP and you have a spinning 3D product shot that plays anywhere, including in an email.++Keep that loop sequential. This endpoint allows **60 renders per 10 minutes per IP** (`/api/avatar/render` allows 120), and a `Promise.all` over fifty frames will collect a fistful of `429`s. A `429` carries `Retry-After`; honour it.++---++## Step 8 - Cache correctly++Understanding the cache is what makes this cheap enough to put on a high-traffic page.++The first request for a given parameter combination boots headless chromium, loads the GLB, renders, and returns the image bytes directly:++```+HTTP/2 200+content-type: image/png+cache-control: public, max-age=300, s-maxage=86400+x-render-cache: miss+x-render-scene: portrait+x-render-size: 256x256+```++The result is written to object storage under a key derived from the avatar ID, a hash of the parameters, and the avatar's `updated_at`. Every request after that answers with a redirect:++```+HTTP/2 302+location: https://<cdn>/renders/<avatar-id>/<param-hash>.png+cache-control: public, max-age=300, s-maxage=86400+x-render-cache: hit+```++Consequences, in order of how likely they are to matter to you:++1. **Follow redirects.** `<img>` and every browser do it for free. `curl` needs `-L`. Server-side fetches need whatever your HTTP client's follow-redirects flag is called, and some default to off.+2. **Editing the avatar busts the cache automatically**, because `updated_at` is part of the key. Change the avatar's appearance or swap its GLB and the next request re-renders. You never purge anything.+3. **Every distinct parameter combination is a distinct cache entry.** Standardize on a small set of sizes across your app. Six sizes is a warm cache; sixty randomly-computed sizes is a cold one, and cold means a chromium boot on your user's critical path.+4. **Warm the first render yourself** for anything on a landing page, a social card, or an email. One `curl -sL -o /dev/null` at deploy time per URL you know you will serve.+5. `POST /api/render/avatar-clip` returns bytes directly with `cache-control: public, max-age=300, s-maxage=86400` and no storage-backed cache, because its input is an arbitrary URL rather than a stable ID. If you need those cached, cache them yourself.++---++## Step 9 - A real viewer on your own page++Sometimes an image is not enough and you want the actual interactive model. Loading a GLB in the browser is a cross-origin `fetch`, which means CORS, and the CDN that hosts generated models answers cross-origin reads only for origins it recognizes (`three.ws` itself, and localhost dev servers). From `https://your-site.com`, a direct load fails with a CORS error and an empty canvas.++`GET /api/glb?src=<url>` exists exactly for this. It streams any public GLB back with `access-control-allow-origin: *`:++```bash+curl -sD - -o /dev/null -H 'Origin: https://your-site.com' \+ 'https://three.ws/api/glb?src=https%3A%2F%2Fthree.ws%2Favatars%2Fselfie-girl.glb' \+ | grep -iE 'access-control-allow-origin|content-type|cache-control'+```++```+access-control-allow-origin: *+content-type: model/gltf-binary+cache-control: public, max-age=86400, s-maxage=604800, immutable+```++Safe by construction: the upstream objects are already public and keyless, and the fetch runs through an SSRF-hardened client (scheme allowlist, DNS pinning, private-address blocklist, redirect re-validation, 30 MB cap, 20 second timeout). It is a CORS shim, not an open proxy.++Drop that into `<model-viewer>` and you have a real viewer with a rendered poster, which is the pattern worth copying: the image loads instantly and the interactive model replaces it when it is ready.++```html+<script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script>++<model-viewer+ src="https://three.ws/api/glb?src=https%3A%2F%2Fthree.ws%2Favatars%2Fselfie-girl.glb"+ poster="https://three.ws/api/avatar/render?avatar=a4bad2f5-8a07-43cf-82e5-b6ba1314441e&scene=full-body&size=768&bg=transparent"+ alt="Selfie Girl, an interactive 3D avatar"+ camera-controls+ auto-rotate+ style="width: 100%; height: 560px; background: transparent;"+></model-viewer>+```++The poster carries its weight here: 2.2 MB of GLB takes a moment on a phone, and a rendered PNG of the same character arrives in a fraction of that. The user sees the right thing immediately and gains interactivity when the model lands.++The same proxy makes GLBs loadable from a Jupyter or Colab notebook and from a `localhost` dev server on a port that is not in the CDN's allowlist, which is the other place this bites.++If you want a talking, animated agent rather than a viewer, that is the `<agent-3d>` web component instead. See [From the character library to a live embed](/docs/tutorials/character-library-to-embed.md).++---++## Troubleshooting++| Symptom | Cause | Fix |+|---|---|---|+| Zero-byte file from `curl` | The render was cached and answered `302`; `curl` did not follow it | Add `-L`. Browsers and `<img>` already do this. |+| `404 not_found` | Avatar does not exist | Check the UUID against `GET /api/avatars/featured` or the avatar's page at `/agents/<id>`. |+| `403 private` | Avatar visibility is `private` | Only `public` and `unlisted` avatars render. Change its visibility or use a different avatar. |+| `400 invalid_scene` | Typo in `scene` | The error lists the four valid values. |+| `400 unknown_pose` | Pose ID not in the catalog | `GET /api/avatar/render` or `GET /api/render/avatar-clip` for the live list. |+| `400 invalid_expression` | `expression` is not a JSON object | It must be a URL-encoded JSON **object**, not an array or a bare string. |+| Expression renders but the face never changes | The GLB has no morph target by that name | Exact-name matching, no aliases, no error. Run the byte-size comparison in Step 5. Michelle has zero morph targets; Selfie Girl has 63. |+| Image is 2048px when you asked for 4096 | Dimensions are clamped, not rejected | Read `x-render-size` to see what you actually got. Max is 2048 per axis. |+| `400 bad_request` from `avatar-clip` | `glbUrl` is missing, non-public, or not http(s) | Private hosts and non-http schemes are blocked by design. Use a public https URL. |+| `502 render_failed` on `avatar-clip` | GLB over 10 MB, unreachable, or unparseable | Shrink it with `/api/avatar/optimize` (Step 7), or verify the URL returns a real GLB with `curl -sL -o m.glb <url> && head -c 4 m.glb`. |+| `429` with `Retry-After` | 120 renders per 10 min per IP on `/api/avatar/render`, 60 on `avatar-clip` | Keep batches sequential and honour `Retry-After`. It is a rolling window, not a ban. |+| Empty canvas in `<model-viewer>`, CORS error in console | Loading a CDN GLB directly from your own origin | Route it through `/api/glb?src=...` (Step 9). |+| Social card shows a blank or black box | Scraper hit a cold render, or choked on PNG alpha | Warm the URL once with `curl -sL`, and use `format=jpeg` with an opaque `bg`. |++---++## What you learned++- That the render endpoint documents itself, so nothing about scenes or poses needs hardcoding+- The four camera presets, and that they move the camera rather than crop the frame+- Which parameters clamp silently and which fail loudly, and why that split is correct+- The pose-versus-morph distinction, and a two-command test for whether a model supports expressions+- How to build a social card that stays correct as the avatar changes+- `POST /api/render/avatar-clip` for arbitrary GLBs, free camera orbits, and turntables+- The 10 MB cap and how `/api/avatar/optimize` gets you under it+- The `302`-to-CDN cache, its `updated_at`-keyed invalidation, and the five things that follow from it+- Why the CDN blocks your origin's direct GLB reads and how `/api/glb` fixes it in one attribute++## Next steps++- Put a live, animated, controllable avatar on the page instead of an image: [From the character library to a live embed](/docs/tutorials/character-library-to-embed.md).+- Generate the model you want to render, from a text prompt: [Generate 3D models from code](/docs/tutorials/generate-3d-api.md).+- Turn a photo into an avatar and render that: [Turn a selfie into an avatar](/docs/tutorials/selfie-to-avatar.md).+- Drive real motion instead of static poses: [Animate your avatar](/docs/tutorials/animate-your-avatar.md).+- Read the exhaustive parameter contract for every endpoint used here: [Media & Render API](/docs/media-api.md).diff --git a/packages/marketplace-mcp/examples/README.md b/packages/marketplace-mcp/examples/README.mdnew file mode 100644index 000000000..8ebe2ef4f--- /dev/null+++ b/packages/marketplace-mcp/examples/README.md@@ -0,0 +1,122 @@+# Examples: @three-ws/marketplace-mcp++Two runnable examples. Both spawn this package's own MCP server over stdio (the+same `node src/index.js` entry point the README documents), speak real MCP+JSON-RPC to it, and read the live public marketplace.++| File | What it does | Run |+|---|---|---|+| [`list-tools.mjs`](list-tools.mjs) | Prints all 5 tools with titles, annotation hints, and full input schemas. | `node examples/list-tools.mjs` |+| [`browse-marketplace.mjs`](browse-marketplace.mjs) | Categories, then a page of popular agents, then one agent's full record, then the skills catalog. | `node examples/browse-marketplace.mjs` |++Run them from the package directory:++```bash+cd packages/marketplace-mcp+node examples/list-tools.mjs+node examples/browse-marketplace.mjs+```++Nothing to install and nothing to configure: every tool on this server is+read-only and keyless. The server prints a one-line banner to stderr on connect+(`[[email protected]] connected over stdio with 5 tools`), which is normal.++## list-tools.mjs++Runs the MCP `initialize` handshake, then `tools/list`, and formats every tool.+Expected output (abridged):++```+server: marketplace-mcp v0.1.1 (stdio)+capabilities: tools+tools: 5++1. browse_agents+ title: Browse the agent marketplace+ hints: read-only, open-world+ params:+ - category (optional; string)+ - q (optional; string)+ - sort (optional; string, one of recommended | recent | popular | top_rated, default "recommended")+ - limit (optional; integer, min 1, max 48)+ - cursor (optional; string)++2. agent_detail+ params:+ - id (required; string, minLength 1)++3. agent_categories+ params: none++4. browse_skills+ params:+ - q, category, sort (popular | new | az), limit (1 to 50), cursor++5. skill_categories+ params: none+```++Every tool reports `read-only, open-world`. There is no write tool on this+server to accidentally reach for.++## browse-marketplace.mjs++Four live calls chained the way an agent would actually chain them: discover the+categories, page the biggest one, expand a card into its full record, then look+at the skills side of the catalog.++```+agent_categories: 14 categories, 2779 published agents+ 794 general+ 56 design+ 56 programming+ 33 marketing+ 31 education++browse_agents: category=general q=none sort=popular limit=5+ 5 card(s), next_cursor=5+ - Event Scanner 8 [general] 791 views, unrated+ Scans mempool for sandwich opportunities and MEV patterns.+ ...++agent_detail: 3a485095-9c48-4847-a8a2-837c1b4387d8+ name: Event Scanner 8+ category: general+ tags: token-price, wallet-scan+ skills: token-price, wallet-scan+ avatar: https://pub-....r2.dev/u/.../mq02t7ea.glb++browse_skills: sort=popular limit=5+ - whale-wallet-tracking [analysis] 10 installs, free+ - Wallet Balance [crypto] 6 installs, $0.005/call+ ...++All four calls were read-only. Nothing was published, purchased, or modified.+```++The catalog is live, so counts, names, and ids all move between runs. What stays+stable is the shape: `browse_agents` returns cards plus a `next_cursor`, and+feeding that cursor back as `cursor` walks the next page.++### Arguments++```bash+node examples/browse-marketplace.mjs "<category slug>" "<free-text query>"+```++Both optional. With no category the example picks the one with the most agents.+A filter that matches nothing is a normal outcome, and the example says so+instead of failing:++```+browse_agents: category=programming q=code sort=popular limit=5+ 0 card(s), next_cursor=null++agent_detail: skipped, that filter returned no cards+```++### Environment++Optional, forwarded to the server if set: `THREE_WS_BASE` (default+`https://three.ws`) and `THREE_WS_TIMEOUT_MS`. Point `THREE_WS_BASE` at your own+deployment to browse its catalog instead.diff --git a/packages/marketplace-mcp/examples/browse-marketplace.mjs b/packages/marketplace-mcp/examples/browse-marketplace.mjsnew file mode 100644index 000000000..1915d4643--- /dev/null+++ b/packages/marketplace-mcp/examples/browse-marketplace.mjs@@ -0,0 +1,129 @@+// browse-marketplace.mjs: walk the public three.ws marketplace end to end with+// three free, read-only tools.+//+// 1. agent_categories which categories exist, and how many agents in each+// 2. browse_agents page the most popular agents in the biggest category+// 3. agent_detail expand the first card into its full record+// 4. browse_skills the skills catalog side of the same catalog+//+// Every call hits the live public /api/marketplace and /api/skills endpoints.+// Nothing here needs a key, a signer, or a payment, and nothing here writes:+// publishing an agent or a skill is the authenticated HTTP write path, which+// this MCP server deliberately does not expose.+//+// node examples/browse-marketplace.mjs+// node examples/browse-marketplace.mjs programming+// node examples/browse-marketplace.mjs "" "code review"+//+// Arg 1 pins a category slug (default: the category with the most agents).+// Arg 2 adds a free-text query.++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));+const FORWARDED_ENV = ['THREE_WS_BASE', 'THREE_WS_TIMEOUT_MS'];++const [categoryArg, queryArg] = process.argv.slice(2);++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** Unwrap an MCP tool result's JSON payload from its text content block. */+function payload(result) {+ const text = result?.content?.find((c) => c.type === 'text')?.text ?? '';+ try {+ return JSON.parse(text);+ } catch {+ return { ok: false, raw: text };+ }+}++/** Call a tool and fail loudly rather than continuing on half-data. */+async function call(client, name, args) {+ const data = payload(await client.callTool({ name, arguments: args }));+ if (!data.ok) {+ throw new Error(`${name} failed: ${data.message || data.error || data.raw || 'unknown error'}`);+ }+ return data;+}++function truncate(text, max) {+ const one = String(text ?? '').replace(/\s+/g, ' ').trim();+ return one.length > max ? `${one.slice(0, max - 3)}...` : one;+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'marketplace-mcp-browse-example', version: '1.0.0' });+await client.connect(transport);++try {+ // ── 1. agent_categories ────────────────────────────────────────────────+ const cats = await call(client, 'agent_categories', {});+ const ranked = [...cats.categories].sort((a, b) => (b.count ?? 0) - (a.count ?? 0));+ console.log(`\nagent_categories: ${ranked.length} categories, ${cats.total} published agents`);+ for (const cat of ranked.slice(0, 5)) {+ console.log(` ${String(cat.count).padStart(5)} ${cat.slug}`);+ }++ const category = categoryArg || ranked[0]?.slug;++ // ── 2. browse_agents ───────────────────────────────────────────────────+ const browseArgs = { sort: 'popular', limit: 5 };+ if (category) browseArgs.category = category;+ if (queryArg) browseArgs.q = queryArg;+ const page = await call(client, 'browse_agents', browseArgs);+ console.log(+ `\nbrowse_agents: category=${category ?? 'any'} q=${queryArg || 'none'} sort=popular limit=5`,+ );+ console.log(` ${page.items.length} card(s), next_cursor=${page.next_cursor ?? 'null'}`);+ for (const agent of page.items) {+ const rating = agent.rating_count ? `${agent.rating_avg} from ${agent.rating_count}` : 'unrated';+ console.log(` - ${agent.name} [${agent.category}] ${agent.views_count} views, ${rating}`);+ console.log(` ${truncate(agent.description, 90)}`);+ }++ // ── 3. agent_detail ────────────────────────────────────────────────────+ const first = page.items[0];+ if (!first) {+ console.log('\nagent_detail: skipped, that filter returned no cards');+ } else {+ const detail = await call(client, 'agent_detail', { id: first.id });+ const agent = detail.agent;+ console.log(`\nagent_detail: ${agent.id}`);+ console.log(` name: ${agent.name}`);+ console.log(` category: ${agent.category}`);+ console.log(` tags: ${(agent.tags ?? []).join(', ') || 'none'}`);+ console.log(` skills: ${(agent.skills ?? []).join(', ') || 'none'}`);+ console.log(` avatar: ${agent.avatar_glb_url ?? 'none'}`);+ console.log(` greeting: ${truncate(agent.greeting, 90) || 'none'}`);+ }++ // ── 4. browse_skills ───────────────────────────────────────────────────+ const skills = await call(client, 'browse_skills', { sort: 'popular', limit: 5 });+ console.log(`\nbrowse_skills: sort=popular limit=5`);+ for (const skill of skills.skills) {+ const price = skill.price_per_call_usd ? `$${skill.price_per_call_usd}/call` : 'free';+ console.log(` - ${skill.name} [${skill.category}] ${skill.install_count ?? 0} installs, ${price}`);+ }++ console.log('\nAll four calls were read-only. Nothing was published, purchased, or modified.');+} finally {+ await client.close();+}diff --git a/packages/marketplace-mcp/examples/list-tools.mjs b/packages/marketplace-mcp/examples/list-tools.mjsnew file mode 100644index 000000000..98b7dc9d4--- /dev/null+++ b/packages/marketplace-mcp/examples/list-tools.mjs@@ -0,0 +1,103 @@+// list-tools.mjs: print every tool @three-ws/marketplace-mcp advertises, with+// its input schema.+//+// Spawns this package's own MCP server over stdio the way the README runs it+// (`node src/index.js`), performs the MCP initialize handshake, calls+// tools/list, and prints each tool's title, annotation hints, and parameters.+//+// node examples/list-tools.mjs+//+// Read-only: no key, no signer, no payment.++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++// The README's "Run standalone" entry point. Swap for+// { command: 'npx', args: ['-y', '@three-ws/marketplace-mcp'] } to exercise the+// published package instead of this checkout.+const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));++// Env this server reads (see src/config.js). getDefaultEnvironment() drops+// everything else, so an example never leaks unrelated secrets to the child.+const FORWARDED_ENV = ['THREE_WS_BASE', 'THREE_WS_TIMEOUT_MS'];++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** One-line summary of a tool's MCP annotation hints. */+function hints(annotations) {+ if (!annotations) return 'no hints';+ const flags = [];+ if (annotations.readOnlyHint) flags.push('read-only');+ if (annotations.destructiveHint) flags.push('destructive');+ if (annotations.idempotentHint) flags.push('idempotent');+ if (annotations.openWorldHint) flags.push('open-world');+ return flags.length ? flags.join(', ') : 'no hints';+}++/** Render a JSON Schema property as one readable constraint string. */+function constraints(prop) {+ const parts = [prop.type ?? 'any'];+ if (Array.isArray(prop.enum)) parts.push(`one of ${prop.enum.join(' | ')}`);+ if (prop.default !== undefined) parts.push(`default ${JSON.stringify(prop.default)}`);+ if (prop.minimum !== undefined) parts.push(`min ${prop.minimum}`);+ if (prop.maximum !== undefined) parts.push(`max ${prop.maximum}`);+ if (prop.minLength !== undefined) parts.push(`minLength ${prop.minLength}`);+ if (prop.maxLength !== undefined) parts.push(`maxLength ${prop.maxLength}`);+ return parts.join(', ');+}++function printTool(tool, index) {+ const schema = tool.inputSchema ?? {};+ const properties = schema.properties ?? {};+ const required = new Set(schema.required ?? []);+ const names = Object.keys(properties);++ console.log(`\n${index}. ${tool.name}`);+ if (tool.title) console.log(` title: ${tool.title}`);+ console.log(` hints: ${hints(tool.annotations)}`);+ if (tool.description) console.log(` ${tool.description}`);+ if (names.length === 0) {+ console.log(' params: none');+ return;+ }+ console.log(' params:');+ for (const name of names) {+ const prop = properties[name];+ const flag = required.has(name) ? 'required' : 'optional';+ console.log(` - ${name} (${flag}; ${constraints(prop)})`);+ if (prop.description) console.log(` ${prop.description}`);+ }+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'marketplace-mcp-list-tools-example', version: '1.0.0' });++await client.connect(transport);++const server = client.getServerVersion();+console.log(`server: ${server?.name} v${server?.version} (stdio)`);+console.log(`capabilities: ${Object.keys(client.getServerCapabilities() ?? {}).join(', ') || 'none'}`);++const { tools } = await client.listTools();+console.log(`tools: ${tools.length}`);++tools.forEach((tool, i) => printTool(tool, i + 1));++await client.close();diff --git a/packages/pumpfun-mcp/examples/list-tools.mjs b/packages/pumpfun-mcp/examples/list-tools.mjsnew file mode 100644index 000000000..56780f3f1--- /dev/null+++ b/packages/pumpfun-mcp/examples/list-tools.mjs@@ -0,0 +1,112 @@+// list-tools.mjs: print every tool @three-ws/pumpfun-mcp advertises, with its+// input schema.+//+// Spawns this package's own MCP server over stdio the way the README runs it+// (`node src/index.js`), performs the MCP initialize handshake, calls+// tools/list, and prints each tool's title, annotation hints, and parameters.+//+// node examples/list-tools.mjs+//+// Read-only: no key, no signer, no payment.+//+// Worth knowing: this server asks its backend for the authoritative tool list at+// startup, so the count reflects what the backend can actually serve right now.+// The six indexer-backed discovery tools (search_tokens, get_trending_tokens,+// get_new_tokens, get_graduated_tokens, get_king_of_the_hill,+// get_creator_profile) are filtered out of tools/list when the backend has no+// PUMPFUN_BOT_URL configured, which is the case on the public backend today.+// They reappear with no client change once an indexer is wired up. Run+// pumpfun_bot_status (see token-report.mjs) to see that state directly.++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++// The README's "Run standalone" entry point. Swap for+// { command: 'npx', args: ['-y', '@three-ws/pumpfun-mcp'] } to exercise the+// published package instead of this checkout.+const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));++// Env this server reads (see src/index.js). getDefaultEnvironment() drops+// everything else, so an example never leaks unrelated secrets to the child.+const FORWARDED_ENV = ['PUMPFUN_MCP_URL'];++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** One-line summary of a tool's MCP annotation hints. */+function hints(annotations) {+ if (!annotations) return 'no hints';+ const flags = [];+ if (annotations.readOnlyHint) flags.push('read-only');+ if (annotations.destructiveHint) flags.push('destructive');+ if (annotations.idempotentHint) flags.push('idempotent');+ if (annotations.openWorldHint) flags.push('open-world');+ return flags.length ? flags.join(', ') : 'no hints';+}++/** Render a JSON Schema property as one readable constraint string. */+function constraints(prop) {+ const parts = [prop.type ?? 'any'];+ if (Array.isArray(prop.enum)) parts.push(`one of ${prop.enum.join(' | ')}`);+ if (prop.default !== undefined) parts.push(`default ${JSON.stringify(prop.default)}`);+ if (prop.minimum !== undefined) parts.push(`min ${prop.minimum}`);+ if (prop.maximum !== undefined) parts.push(`max ${prop.maximum}`);+ if (prop.minLength !== undefined) parts.push(`minLength ${prop.minLength}`);+ if (prop.maxLength !== undefined) parts.push(`maxLength ${prop.maxLength}`);+ return parts.join(', ');+}++function printTool(tool, index) {+ const schema = tool.inputSchema ?? {};+ const properties = schema.properties ?? {};+ const required = new Set(schema.required ?? []);+ const names = Object.keys(properties);++ console.log(`\n${index}. ${tool.name}`);+ if (tool.title) console.log(` title: ${tool.title}`);+ console.log(` hints: ${hints(tool.annotations)}`);+ if (tool.description) console.log(` ${tool.description}`);+ if (names.length === 0) {+ console.log(' params: none');+ return;+ }+ console.log(' params:');+ for (const name of names) {+ const prop = properties[name];+ const flag = required.has(name) ? 'required' : 'optional';+ console.log(` - ${name} (${flag}; ${constraints(prop)})`);+ if (prop.description) console.log(` ${prop.description}`);+ }+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'pumpfun-mcp-list-tools-example', version: '1.0.0' });++await client.connect(transport);++const server = client.getServerVersion();+console.log(`server: ${server?.name} v${server?.version} (stdio)`);+console.log(`capabilities: ${Object.keys(client.getServerCapabilities() ?? {}).join(', ') || 'none'}`);++const { tools } = await client.listTools();+console.log(`tools: ${tools.length}`);++tools.forEach((tool, i) => printTool(tool, i + 1));++await client.close();diff --git a/packages/pumpfun-mcp/examples/token-report.mjs b/packages/pumpfun-mcp/examples/token-report.mjsnew file mode 100644index 000000000..ba01b611d--- /dev/null+++ b/packages/pumpfun-mcp/examples/token-report.mjs@@ -0,0 +1,139 @@+// token-report.mjs: build a live on-chain report for one pump.fun token using+// five free, read-only tools.+//+// 1. pumpfun_bot_status which lanes the backend can serve right now+// 2. get_token_details SPL mint facts: decimals, supply, authorities+// 3. get_bonding_curve graduation progress, or confirmation it graduated+// 4. get_token_holders top holders and top-holder concentration+// 5. get_token_trades the most recent real buys and sells+//+// Every number comes from Solana mainnet through the canonical three.ws backend.+// No API key, no RPC URL, no wallet, and no payment: this server has no write+// tool at all, so nothing here can sign or send a transaction.+//+// node examples/token-report.mjs+// node examples/token-report.mjs <MINT_ADDRESS>+//+// The default mint is $THREE, the three.ws platform token. Pass any pump.fun+// mint as the first argument to report on it instead.++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));+// PUMPFUN_MCP_URL repoints the bridge at a self-hosted backend.+const FORWARDED_ENV = ['PUMPFUN_MCP_URL'];++// $THREE on Solana mainnet, the one coin this platform promotes.+const MINT = process.argv[2] || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/**+ * Call a tool and return its structured payload. This server returns+ * structuredContent alongside the text mirror, so prefer the structured form+ * and fall back to parsing the text block.+ */+async function call(client, name, args) {+ const result = await client.callTool({ name, arguments: args });+ if (result.isError) {+ const text = result.content?.find((c) => c.type === 'text')?.text ?? 'tool error';+ throw new Error(`${name} failed: ${text}`);+ }+ if (result.structuredContent !== undefined) return result.structuredContent;+ const text = result.content?.find((c) => c.type === 'text')?.text ?? 'null';+ return JSON.parse(text);+}++/** Raw base units to a human amount using the mint's decimals. */+function fromBaseUnits(raw, decimals) {+ const n = Number(raw);+ if (!Number.isFinite(n)) return 'unknown';+ return (n / 10 ** decimals).toLocaleString('en-US', { maximumFractionDigits: 2 });+}++function ago(unixSeconds) {+ const seconds = Math.max(0, Math.floor(Date.now() / 1000 - Number(unixSeconds)));+ if (seconds < 60) return `${seconds}s ago`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;+ return `${Math.floor(seconds / 86400)}d ago`;+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'pumpfun-mcp-token-report-example', version: '1.0.0' });+await client.connect(transport);++try {+ // ── 1. pumpfun_bot_status ──────────────────────────────────────────────+ // The indexer-backed discovery tools (search_tokens, get_trending_tokens,+ // and friends) only exist when the backend has PUMPFUN_BOT_URL set. The+ // on-chain tools this example uses never depend on it.+ const status = await call(client, 'pumpfun_bot_status', {});+ console.log('\npumpfun_bot_status:');+ console.log(` indexer configured: ${status.configured}`);+ console.log(` indexer healthy: ${status.healthy}`);+ if (status.message) console.log(` ${status.message}`);++ // ── 2. get_token_details ───────────────────────────────────────────────+ const details = await call(client, 'get_token_details', { mint: MINT });+ const decimals = Number(details.decimals) || 0;+ console.log(`\nget_token_details: ${MINT}`);+ console.log(` decimals: ${decimals}`);+ console.log(` supply: ${fromBaseUnits(details.supply, decimals)}`);+ console.log(` mint authority: ${details.mintAuthority ?? 'revoked (no further minting)'}`);+ console.log(` freeze authority: ${details.freezeAuthority ?? 'revoked (accounts cannot be frozen)'}`);++ // ── 3. get_bonding_curve ───────────────────────────────────────────────+ const curve = await call(client, 'get_bonding_curve', { mint: MINT });+ console.log('\nget_bonding_curve:');+ if (curve.complete) {+ console.log(' curve complete: yes, this token graduated off the bonding curve');+ console.log(' price now comes from the PumpSwap pool, so use pumpfun_quote_swap');+ } else {+ console.log(` curve complete: no, ${Number(curve.graduationPercent).toFixed(2)}% of the way to graduation`);+ console.log(` real reserves: ${curve.solReserves} SOL`);+ console.log(` virtual quote: ${curve.virtualSolReserves} lamports`);+ console.log(` virtual tokens: ${curve.virtualTokenReserves} base units`);+ }++ // ── 4. get_token_holders ───────────────────────────────────────────────+ const holders = await call(client, 'get_token_holders', { mint: MINT, limit: 5 });+ console.log('\nget_token_holders: top 5');+ console.log(` top-holder share: ${Number(holders.topHolderPercent).toFixed(2)}%`);+ for (const holder of holders.holders ?? []) {+ console.log(+ ` ${Number(holder.percent).toFixed(2).padStart(6)}% ${holder.address} ${holder.uiAmount.toLocaleString('en-US', { maximumFractionDigits: 0 })}`,+ );+ }++ // ── 5. get_token_trades ────────────────────────────────────────────────+ const trades = await call(client, 'get_token_trades', { mint: MINT, limit: 5 });+ console.log(`\nget_token_trades: last ${trades.count} on-chain`);+ for (const trade of trades.trades ?? []) {+ const side = trade.isBuy ? 'BUY ' : 'SELL';+ const usd = Number(trade.usdValue).toFixed(4);+ console.log(` ${side} $${usd.padStart(10)} ${trade.solAmount} SOL ${ago(trade.timestamp)}`);+ }++ console.log('\nEvery call was a read. Nothing was signed, sent, or paid for.');+} finally {+ await client.close();+}diff --git a/packages/vanity-mcp/examples/README.md b/packages/vanity-mcp/examples/README.mdnew file mode 100644index 000000000..c1036502e--- /dev/null+++ b/packages/vanity-mcp/examples/README.md@@ -0,0 +1,116 @@+# Examples: @three-ws/vanity-mcp++Two runnable examples. Both spawn this package's own MCP server over stdio (the+same `node src/index.js` entry point the README documents), speak real MCP+JSON-RPC to it, and read the live grind-bounty market.++| File | What it does | Run |+|---|---|---|+| [`list-tools.mjs`](list-tools.mjs) | Prints all 8 tools with titles, annotation hints, and full input schemas. | `node examples/list-tools.mjs` |+| [`quote-and-appraise.mjs`](quote-and-appraise.mjs) | Market config, then a pattern's difficulty and honest bounty price, then one address's rarity, then live market totals. | `node examples/quote-and-appraise.mjs` |++Run them from the package directory:++```bash+cd packages/vanity-mcp+node examples/list-tools.mjs+node examples/quote-and-appraise.mjs+```++Nothing to install and nothing to configure: every tool on this server is+read-only and keyless. Posting a bounty and claiming one are x402-paid writes on+the HTTP API, and this server does not expose them, so these examples cannot+spend anything. The server prints a one-line banner to stderr on connect+(`[[email protected]] connected over stdio with 8 tools`), which is normal.++## list-tools.mjs++Runs the MCP `initialize` handshake, then `tools/list`, and formats every tool.+Expected output (abridged):++```+server: vanity-mcp v0.1.1 (stdio)+capabilities: tools+tools: 8++1. vanity_quote+ title: Quote the bounty price for a vanity pattern+ hints: read-only, idempotent, open-world+ params:+ - prefix (optional; string)+ - suffix (optional; string)+ - ignoreCase (optional; boolean)++2. vanity_appraise+ hints: read-only, idempotent, open-world+ params:+ - address (required; string, minLength 32, maxLength 44)+ - prefixLen (optional; integer, min 0)+ - suffixLen (optional; integer, min 0)++3. vanity_board 4. vanity_open 5. vanity_stats+6. vanity_leaderboard 7. vanity_config 8. vanity_gallery+```++Note which two carry `idempotentHint`: `vanity_quote` and `vanity_appraise` are+pure functions of their input, so the same pattern or address always scores the+same. The six market reads are not idempotent, because the market moves.++## quote-and-appraise.mjs++Four live calls. The interesting pair is the difficulty oracle and the+appraiser: the first tells you what a pattern should cost to have ground, the+second tells you what an address you already hold was worth grinding.++```+vanity_config:+ payouts configured: true+ settlement asset: USDC (6 decimals)+ escrow networks: base, solana+ pricing band: 0.050000 to 5000.000000 USDC+ protocol: three-vanity-bounty/v1++vanity_quote: prefix "THREE", case-sensitive+ tier: Mythic (39 bits of rarity)+ expected attempts: 11,308,763,834+ expected grind: 2.1h on the reference rig+ suggested bounty: 2.094216 USDC+ generous bounty: 5.235540 USDC++vanity_appraise: FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+ detected pattern: prefix "FeMb", suffix "none"+ tier: Epic (score 2166)+ expected attempts: 3,304,724+ grind time: under a second+ scoring model: base58-exact/v2++vanity_stats:+ open bounties: 0 (0.000000 USDC escrowed)+ settled: 0 (0.000000 USDC paid out)+ total ever: 0++All four calls were read-only. No bounty was posted, claimed, or paid.+```++The quote is deterministic, so a rerun with the same prefix reproduces those+numbers exactly. `vanity_stats` is live and moves with the market.++Difficulty is exponential in pattern length, which the two runs make obvious: a+3-character prefix is ~3.4 million attempts and prices at the 0.05 USDC floor,+while a 5-character case-sensitive prefix is ~11.3 billion attempts and prices+at ~2.09 USDC. Quote before you escrow.++### Arguments++```bash+node examples/quote-and-appraise.mjs "<base58 prefix>" "<solana address>"+```++Both optional. The default prefix is `THREE`; the default address is the $THREE+mint, a real mainnet address. Any Base58 public key of 32 to 44 characters can be+appraised, and nothing about it is stored.++### Environment++Optional, forwarded to the server if set: `THREE_WS_BASE` (default+`https://three.ws`) and `THREE_WS_TIMEOUT_MS`.diff --git a/packages/vanity-mcp/examples/list-tools.mjs b/packages/vanity-mcp/examples/list-tools.mjsnew file mode 100644index 000000000..c40ed192d--- /dev/null+++ b/packages/vanity-mcp/examples/list-tools.mjs@@ -0,0 +1,103 @@+// list-tools.mjs: print every tool @three-ws/vanity-mcp advertises, with its+// input schema.+//+// Spawns this package's own MCP server over stdio the way the README runs it+// (`node src/index.js`), performs the MCP initialize handshake, calls+// tools/list, and prints each tool's title, annotation hints, and parameters.+//+// node examples/list-tools.mjs+//+// Read-only: no key, no signer, no payment.++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++// The README's "Run standalone" entry point. Swap for+// { command: 'npx', args: ['-y', '@three-ws/vanity-mcp'] } to exercise the+// published package instead of this checkout.+const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));++// Env this server reads (see src/config.js). getDefaultEnvironment() drops+// everything else, so an example never leaks unrelated secrets to the child.+const FORWARDED_ENV = ['THREE_WS_BASE', 'THREE_WS_TIMEOUT_MS'];++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** One-line summary of a tool's MCP annotation hints. */+function hints(annotations) {+ if (!annotations) return 'no hints';+ const flags = [];+ if (annotations.readOnlyHint) flags.push('read-only');+ if (annotations.destructiveHint) flags.push('destructive');+ if (annotations.idempotentHint) flags.push('idempotent');+ if (annotations.openWorldHint) flags.push('open-world');+ return flags.length ? flags.join(', ') : 'no hints';+}++/** Render a JSON Schema property as one readable constraint string. */+function constraints(prop) {+ const parts = [prop.type ?? 'any'];+ if (Array.isArray(prop.enum)) parts.push(`one of ${prop.enum.join(' | ')}`);+ if (prop.default !== undefined) parts.push(`default ${JSON.stringify(prop.default)}`);+ if (prop.minimum !== undefined) parts.push(`min ${prop.minimum}`);+ if (prop.maximum !== undefined) parts.push(`max ${prop.maximum}`);+ if (prop.minLength !== undefined) parts.push(`minLength ${prop.minLength}`);+ if (prop.maxLength !== undefined) parts.push(`maxLength ${prop.maxLength}`);+ return parts.join(', ');+}++function printTool(tool, index) {+ const schema = tool.inputSchema ?? {};+ const properties = schema.properties ?? {};+ const required = new Set(schema.required ?? []);+ const names = Object.keys(properties);++ console.log(`\n${index}. ${tool.name}`);+ if (tool.title) console.log(` title: ${tool.title}`);+ console.log(` hints: ${hints(tool.annotations)}`);+ if (tool.description) console.log(` ${tool.description}`);+ if (names.length === 0) {+ console.log(' params: none');+ return;+ }+ console.log(' params:');+ for (const name of names) {+ const prop = properties[name];+ const flag = required.has(name) ? 'required' : 'optional';+ console.log(` - ${name} (${flag}; ${constraints(prop)})`);+ if (prop.description) console.log(` ${prop.description}`);+ }+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'vanity-mcp-list-tools-example', version: '1.0.0' });++await client.connect(transport);++const server = client.getServerVersion();+console.log(`server: ${server?.name} v${server?.version} (stdio)`);+console.log(`capabilities: ${Object.keys(client.getServerCapabilities() ?? {}).join(', ') || 'none'}`);++const { tools } = await client.listTools();+console.log(`tools: ${tools.length}`);++tools.forEach((tool, i) => printTool(tool, i + 1));++await client.close();diff --git a/packages/vanity-mcp/examples/quote-and-appraise.mjs b/packages/vanity-mcp/examples/quote-and-appraise.mjsnew file mode 100644index 000000000..552c3de61--- /dev/null+++ b/packages/vanity-mcp/examples/quote-and-appraise.mjs@@ -0,0 +1,134 @@+// quote-and-appraise.mjs: price a vanity pattern and appraise an address with+// four free, read-only tools.+//+// 1. vanity_config is the market able to pay out, and in what asset+// 2. vanity_quote difficulty and honest suggested bounty for a pattern+// 3. vanity_appraise rarity of an existing address (pure math, nothing stored)+// 4. vanity_stats live market pulse: open, escrowed, paid out+//+// Every call hits the live public /api/vanity endpoints. Nothing here needs a+// key, a signer, or a payment: posting a bounty and claiming one are the+// x402-paid HTTP write paths, which this MCP server deliberately does not+// expose, so this example cannot spend anything.+//+// node examples/quote-and-appraise.mjs+// node examples/quote-and-appraise.mjs THREE+// node examples/quote-and-appraise.mjs abc <SOLANA_ADDRESS>+//+// Arg 1 is the Base58 prefix to quote (default THREE). Arg 2 is the address to+// appraise (default: the $THREE mint, a real mainnet address).++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));+const FORWARDED_ENV = ['THREE_WS_BASE', 'THREE_WS_TIMEOUT_MS'];++const [prefixArg, addressArg] = process.argv.slice(2);+const PREFIX = prefixArg || 'THREE';+// The $THREE mint on Solana mainnet: a real address, and the one coin this+// platform promotes. Any Base58 public key works here.+const ADDRESS = addressArg || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** Unwrap an MCP tool result's JSON payload from its text content block. */+function payload(result) {+ const text = result?.content?.find((c) => c.type === 'text')?.text ?? '';+ try {+ return JSON.parse(text);+ } catch {+ return { ok: false, raw: text };+ }+}++/** Call a tool and fail loudly rather than continuing on half-data. */+async function call(client, name, args) {+ const data = payload(await client.callTool({ name, arguments: args }));+ if (!data.ok) {+ throw new Error(`${name} failed: ${data.message || data.error || data.raw || 'unknown error'}`);+ }+ return data;+}++/** Atomic units to a human amount, using the decimals the market advertises. */+function human(atomics, decimals) {+ if (atomics === undefined || atomics === null) return 'unstated';+ return (Number(atomics) / 10 ** decimals).toFixed(Math.min(decimals, 6));+}++/** Seconds to a compact duration, for grind-time estimates. */+function duration(seconds) {+ const s = Number(seconds);+ if (!Number.isFinite(s)) return 'unknown';+ if (s < 1) return 'under a second';+ if (s < 60) return `${s.toFixed(1)}s`;+ if (s < 3600) return `${(s / 60).toFixed(1)}m`;+ if (s < 86400) return `${(s / 3600).toFixed(1)}h`;+ return `${(s / 86400).toFixed(1)}d`;+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'vanity-mcp-quote-appraise-example', version: '1.0.0' });+await client.connect(transport);++try {+ // ── 1. vanity_config ───────────────────────────────────────────────────+ const config = await call(client, 'vanity_config', {});+ const decimals = Number(config.decimals) || 6;+ console.log('\nvanity_config:');+ console.log(` payouts configured: ${config.payoutConfigured}`);+ console.log(` settlement asset: ${config.asset} (${decimals} decimals)`);+ console.log(` escrow networks: ${(config.networks ?? []).join(', ') || 'none'}`);+ console.log(+ ` pricing band: ${human(config.band?.floorAtomics, decimals)} to ${human(config.band?.maxAtomics, decimals)} ${config.asset}`,+ );+ console.log(` protocol: ${config.protocol}`);++ // ── 2. vanity_quote ────────────────────────────────────────────────────+ const quote = await call(client, 'vanity_quote', { prefix: PREFIX });+ const d = quote.difficulty ?? {};+ console.log(`\nvanity_quote: prefix "${PREFIX}", case-sensitive`);+ console.log(` tier: ${d.tierLabel} (${d.rarityBits} bits of rarity)`);+ console.log(` expected attempts: ${Number(d.expectedAttempts).toLocaleString('en-US')}`);+ console.log(` expected grind: ${duration(d.expectedGrindSeconds)} on the reference rig`);+ console.log(` suggested bounty: ${human(quote.oracle?.suggestedAtomics, decimals)} ${config.asset}`);+ console.log(` generous bounty: ${human(quote.oracle?.generousAtomics, decimals)} ${config.asset}`);++ // ── 3. vanity_appraise ─────────────────────────────────────────────────+ const appraisal = (await call(client, 'vanity_appraise', { address: ADDRESS })).appraisal ?? {};+ console.log(`\nvanity_appraise: ${ADDRESS}`);+ console.log(` detected pattern: prefix "${appraisal.prefix ?? 'none'}", suffix "${appraisal.suffix ?? 'none'}"`);+ console.log(` tier: ${appraisal.tierLabel} (score ${appraisal.rarityScore})`);+ console.log(` expected attempts: ${Number(appraisal.expectedAttempts).toLocaleString('en-US')}`);+ console.log(` grind time: ${appraisal.grindHuman}`);+ console.log(` scoring model: ${appraisal.model}`);++ // ── 4. vanity_stats ────────────────────────────────────────────────────+ const stats = await call(client, 'vanity_stats', {});+ console.log('\nvanity_stats:');+ console.log(` open bounties: ${stats.open} (${human(stats.openEscrowAtomics, decimals)} ${config.asset} escrowed)`);+ console.log(` settled: ${stats.settled} (${human(stats.paidOutAtomics, decimals)} ${config.asset} paid out)`);+ console.log(` total ever: ${stats.total}`);++ console.log('\nAll four calls were read-only. No bounty was posted, claimed, or paid.');+} finally {+ await client.close();+}diff --git a/packages/x402-mcp/examples/README.md b/packages/x402-mcp/examples/README.mdnew file mode 100644index 000000000..c70c4fbdb--- /dev/null+++ b/packages/x402-mcp/examples/README.md@@ -0,0 +1,115 @@+# Examples: @three-ws/x402-mcp++Two runnable examples. Both spawn this package's own MCP server over stdio (the+same `node src/index.js` entry point the README documents), speak real MCP+JSON-RPC to it, and hit live data. Neither one pays for anything.++| File | What it does | Run |+|---|---|---|+| [`list-tools.mjs`](list-tools.mjs) | Prints all 4 tools with titles, annotation hints, and full input schemas. | `node examples/list-tools.mjs` |+| [`inspect-price.mjs`](inspect-price.mjs) | Searches the live x402 bazaar with `find_services`, then reads one endpoint's 402 price with `inspect_endpoint`, without paying. | `node examples/inspect-price.mjs` |++Run them from the package directory:++```bash+cd packages/x402-mcp+node examples/list-tools.mjs+node examples/inspect-price.mjs+```++Nothing to install and nothing to configure: `find_services` and+`inspect_endpoint` need no key, no signer, and no funds. The server prints a+one-line banner to stderr on connect (`[[email protected]] connected over stdio+with 4 tools`), which is normal.++## list-tools.mjs++Runs the MCP `initialize` handshake, then `tools/list`, and formats every tool.+Expected output (abridged):++```+server: x402-mcp v0.2.1 (stdio)+capabilities: tools+tools: 4++1. x402_wallet+ title: The agent's x402 spending wallet (address + balance)+ hints: read-only, open-world+ params:+ - address (optional; string, minLength 32, maxLength 64)++2. find_services+ hints: read-only, open-world+ params:+ - query (required; string, minLength 1)+ - type (optional; string, one of http | mcp, default "http")+ - network (optional; string)+ - max_price_usdc (optional; number, min 0)+ - limit (optional; integer, min 1, max 100)++3. inspect_endpoint+ hints: read-only, open-world++4. pay_and_call+ hints: destructive, open-world+```++`pay_and_call` is the only tool that carries `destructiveHint`. That is the flag+annotation-aware clients use to prompt before spending.++## inspect-price.mjs++Two live, free calls in sequence.++`find_services` merges the public facilitator discovery feeds and ranks them+against your query, so you see what an agent could actually buy:++```+find_services: searching the live bazaar for "3d model"+ 5 service(s) matched+ - 0.001 USDC https://three.ws/api/mcp+ - 0.001 USDC https://three.ws/api/mcp-3d+ - 0.001 USDC https://three.ws/api/x402/model-check+ - 0.25 USDC https://three.ws/api/x402/remix-asset+ - 0.05 USDC https://three.ws/api/x402/pipeline-rig+```++`inspect_endpoint` then probes one of those endpoints and decodes its real 402+challenge. This is the whole point of the tool: you learn the price, the asset,+and the recipient before any money moves.++```+inspect_endpoint: probing https://three.ws/api/x402/model-check?url=https://three.ws/avatars/mannequin.glb+ 402 payment required, 3 way(s) to settle:+ - solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp exact+ price: 1000 atomic (0.001 USDC)+ asset: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v+ pay to: wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU+ - eip155:8453 exact+ price: 1000 atomic (0.001 USD Coin)+ ...++ this wallet could settle it: yes, a solana:* accept is offered++No payment was made. Nothing was signed, no key was read.+```++Prices come from the live endpoint, so the exact numbers and the set of+discovered services will differ from the transcript above.++### Arguments++```bash+node examples/inspect-price.mjs "<search query>" "<url to probe>"+```++Both are optional. Pass a `resource` printed by the `find_services` step as the+second argument to probe that service instead. Some paid routes take their input+as a query param, so include it (the default target does).++### Environment++Optional, and forwarded to the server if set: `THREE_WS_BASE` (default+`https://three.ws`), `THREE_WS_TIMEOUT_MS`, `SOLANA_RPC_URL`. Neither example+reads `SOLANA_SECRET_KEY` or calls `pay_and_call`, so no key is ever loaded and+no transaction is ever signed.diff --git a/packages/x402-mcp/examples/inspect-price.mjs b/packages/x402-mcp/examples/inspect-price.mjsnew file mode 100644index 000000000..0a175676c--- /dev/null+++ b/packages/x402-mcp/examples/inspect-price.mjs@@ -0,0 +1,119 @@+// inspect-price.mjs: discover real paid x402 services, then read one+// endpoint's price WITHOUT paying for it.+//+// Exercises the two free, read-only tools on this server against live data:+// 1. find_services searches the live x402 bazaar (PayAI + Coinbase CDP)+// 2. inspect_endpoint probes a 402 challenge and reports every accepted+// scheme, network, asset, atomic price, and pay-to address+//+// This example NEVER calls pay_and_call and never signs anything. It is the+// honest way to learn what a call would cost before committing money: the+// output is exactly the challenge pay_and_call would settle.+//+// node examples/inspect-price.mjs+// node examples/inspect-price.mjs "image upscale"+// node examples/inspect-price.mjs "3d model" https://your-endpoint.example/paid+//+// No key, no signer, no funds required.++import { fileURLToPath } from 'node:url';++import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import {+ StdioClientTransport,+ getDefaultEnvironment,+} from '@modelcontextprotocol/sdk/client/stdio.js';++const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));+const FORWARDED_ENV = ['THREE_WS_BASE', 'THREE_WS_TIMEOUT_MS', 'SOLANA_RPC_URL'];++const [queryArg, urlArg] = process.argv.slice(2);+const QUERY = queryArg || '3d model';++// A live three.ws x402 route. Model Check charges per call and takes its input+// as a query param, so the probe URL carries one; the value is the endpoint's+// own documented example asset. Pass a second CLI arg to probe anything else,+// including a `resource` printed by step 1.+const TARGET_URL =+ urlArg || 'https://three.ws/api/x402/model-check?url=https://three.ws/avatars/mannequin.glb';++function childEnv() {+ const env = getDefaultEnvironment();+ for (const key of FORWARDED_ENV) {+ const value = process.env[key];+ if (value) env[key] = value;+ }+ return env;+}++/** Unwrap an MCP tool result's JSON payload from its text content block. */+function payload(result) {+ const text = result?.content?.find((c) => c.type === 'text')?.text ?? '';+ try {+ return JSON.parse(text);+ } catch {+ return { ok: false, raw: text };+ }+}++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [SERVER_PATH],+ env: childEnv(),+ stderr: 'inherit',+});+const client = new Client({ name: 'x402-mcp-inspect-price-example', version: '1.0.0' });+await client.connect(transport);++// ── 1. find_services: what can this agent buy? ─────────────────────────────+console.log(`\nfind_services: searching the live bazaar for "${QUERY}"`);+const found = payload(+ await client.callTool({+ name: 'find_services',+ arguments: { query: QUERY, type: 'http', limit: 5 },+ }),+);+if (!found.ok) {+ console.error('find_services failed:', found.message || found.error || found.raw);+ await client.close();+ process.exit(1);+}+console.log(` ${found.count} service(s) matched`);+for (const service of found.services) {+ console.log(` - ${service.price ?? 'price unlisted'} ${service.resource}`);+ if (service.name) console.log(` ${service.name}`);+}++// ── 2. inspect_endpoint: what does one of them charge? ─────────────────────+console.log(`\ninspect_endpoint: probing ${TARGET_URL}`);+const probe = payload(+ await client.callTool({+ name: 'inspect_endpoint',+ arguments: { url: TARGET_URL, method: 'GET' },+ }),+);+if (!probe.ok) {+ console.error('inspect_endpoint failed:', probe.message || probe.error || probe.raw);+ await client.close();+ process.exit(1);+}++if (!probe.paid) {+ console.log(` not paywalled (HTTP ${probe.status}); call it directly, no x402 needed`);+} else {+ console.log(` 402 payment required, ${probe.accepts.length} way(s) to settle:`);+ for (const accept of probe.accepts) {+ console.log(` - ${accept.network} ${accept.scheme}`);+ console.log(` price: ${accept.price ?? 'unstated'} atomic (${accept.price_display ?? 'no decimals advertised'})`);+ console.log(` asset: ${accept.asset ?? 'unstated'}`);+ console.log(` pay to: ${accept.pay_to ?? 'unstated'}`);+ }+ console.log(+ `\n this wallet could settle it: ${probe.payable_with_this_wallet ? 'yes, a solana:* accept is offered' : 'no solana:* accept offered'}`,+ );+}++console.log('\nNo payment was made. Nothing was signed, no key was read.');+console.log('To actually buy the result, call pay_and_call with confirm: true and a funded SOLANA_SECRET_KEY.');++await client.close();diff --git a/packages/x402-mcp/src/tools/inspect-endpoint.js b/packages/x402-mcp/src/tools/inspect-endpoint.jsindex f70bc4a5a..ec2abf062 100644--- a/packages/x402-mcp/src/tools/inspect-endpoint.js+++ b/packages/x402-mcp/src/tools/inspect-endpoint.js@@ -31,14 +31,27 @@ export const def = {result: probe.result,};}- const accepts = probe.accepts.map((a) => ({- scheme: a.scheme,- network: a.network,- price: a.price ?? a.maxAmountRequired ?? undefined,- asset: a.asset ?? a.extra?.asset ?? undefined,- pay_to: a.payTo ?? undefined,- max_timeout_seconds: a.maxTimeoutSeconds ?? undefined,- }));+ const accepts = probe.accepts.map((a) => {+ // x402 v2 advertises the atomic charge as `amount`; v1 called it+ // `maxAmountRequired`, and some servers emit a bare `price`. Read all+ // three or the price silently disappears from the answer.+ const atomic = a.amount ?? a.maxAmountRequired ?? a.price ?? undefined;+ const decimals = Number(a.extra?.decimals);+ const assetName = String(a.extra?.name ?? '').trim();+ const display =+ atomic !== undefined && Number.isFinite(decimals)+ ? `${Number(atomic) / 10 ** decimals}${assetName ? ` ${assetName}` : ''}`+ : undefined;+ return {+ scheme: a.scheme,+ network: a.network,+ price: atomic,+ price_display: display,+ asset: a.asset ?? a.extra?.asset ?? undefined,+ pay_to: a.payTo ?? undefined,+ max_timeout_seconds: a.maxTimeoutSeconds ?? undefined,+ };+ });return {ok: true,url,diff --git a/public/features.json b/public/features.jsonindex bafbc7bab..a91ebe68b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T05:05:28.622Z",+ "generated_at": "2026-07-30T05:07:26.151Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 96c9bc257..2fa9ac781 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -2692,6 +2692,12 @@ URL: https://three.ws/news/Product launches, integrations, and announcements from three.ws.+### How to Monetize an MCP Server: Paid Tools with x402++URL: https://three.ws/news/monetize-mcp-server-x402-paid-tools++The seller-side guide to agent payments: choose work worth charging for, price it in atomic USDC units, answer unpaid calls with a real 402, verify then work then settle, charge per tool inside an MCP tools/call, and get indexed where agents shop for paid services.+### three.ws Joins the Quicknode Startup ProgramURL: https://three.ws/news/quicknode-startup-program@@ -2804,7 +2810,7 @@ URL: https://three.ws/news/cmc-memecoin-3d-worldURL: https://three.ws/news/aws-builder-center-blog-three.ws's contribution is live on the official AWS Builder Center Blog: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3" — covering ResolveCustomer, MeterUsage, entitlements, SNS lifecycle webhooks, and bridging to an on-chain x402 paywall.+three.ws's contribution is live on the official AWS Builder Center Blog: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3". It covers ResolveCustomer, MeterUsage, entitlements, SNS lifecycle webhooks, and bridging to an on-chain x402 paywall.### three.ws Is Now Officially Live on AWS Marketplacediff --git a/public/llms.txt b/public/llms.txtindex 9d2a9638d..39d4ef303 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -464,6 +464,7 @@ Long-form announcements, launches, and writing from three.ws.Product launches, integrations, and announcements from three.ws.- [News & Announcements](https://three.ws/news/): Product launches, integrations, and announcements from three.ws.+- [How to Monetize an MCP Server: Paid Tools with x402](https://three.ws/news/monetize-mcp-server-x402-paid-tools): The seller-side guide to agent payments: choose work worth charging for, price it in atomic USDC units, answer unpaid calls with a real 402, verify then work then settle, charge per tool inside an MCP tools/call, and get indexed where agents shop for paid services.- [three.ws Joins the Quicknode Startup Program](https://three.ws/news/quicknode-startup-program): three.ws has been accepted into the Quicknode Startup Program and approved for free infrastructure credits: more RPC headroom for the Solana-first agent economy, provider redundancy, and Quicknode's founder network.- [three.ws Publishes "Build Autonomous AI Agents with 3D Bodies and On-Chain Payments" on the AWS Builder Center](https://three.ws/news/aws-builder-center-3d-agents-onchain-payments): Our second article on the official AWS Builder Center: how to build browser-native 3D AI agents with memory, on-chain wallets, and autonomous x402 payments, available through AWS Marketplace and embeddable in one line of HTML.- [Text to 3D Is Live — Type a Prompt, Download a 3D Model](https://three.ws/news/text-to-3d-is-live): Forge is live at three.ws/forge: type a description, get a textured, interactive 3D model you can orbit, view in AR, and download as a GLB. Image to 3D from photos works too — and agents can call the same pipeline over MCP.@@ -482,7 +483,7 @@ Product launches, integrations, and announcements from three.ws.- [three.ws Showcases IBM Partnership: Embedding a 3D Agent as Easily as a YouTube Video](https://three.ws/news/ibm-showcase-may31): three.ws showcased the IBM partnership publicly: embedding a persistent, on-chain 3D avatar into any platform is now as easy as embedding a YouTube video — powered by IBM watsonx.ai and Granite, onboarding the next millions of developers and users.- [Introducing three.ws/play: Live 3D Virtual Townhalls for Any Coin](https://three.ws/news/threews-play-coin-communities): three.ws/play launches as a live 3D virtual townhall for any pump.fun coin, powered by the CoinComms API & SDK. 100% multiplayer, custom 3D avatars, real-time on-chain events — the community is the asset, and now it has a home.- [CoinMarketCap: Every Memecoin Is Now a 3D World You Can Walk Into](https://three.ws/news/cmc-memecoin-3d-world): "Every Memecoin Is Now a 3D World You Can Walk Into" — three.ws guest post on CoinMarketCap. The community is the asset, so why does it live in a chat box? With three.ws/play, every coin gets a live 3D world its holders can walk into.-- [three.ws Publishes on the AWS Builder Center Blog](https://three.ws/news/aws-builder-center-blog): three.ws's contribution is live on the official AWS Builder Center Blog: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3" — covering ResolveCustomer, MeterUsage, entitlements, SNS lifecycle webhooks, and bridging to an on-chain x402 paywall.+- [three.ws Publishes on the AWS Builder Center Blog](https://three.ws/news/aws-builder-center-blog): three.ws's contribution is live on the official AWS Builder Center Blog: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3". It covers ResolveCustomer, MeterUsage, entitlements, SNS lifecycle webhooks, and bridging to an on-chain x402 paywall.- [three.ws Is Now Officially Live on AWS Marketplace](https://three.ws/news/aws-marketplace-live-may29): three.ws is now officially live on AWS Marketplace as an AWS Partner — delivering the open 3D layer for the internet. Embed fully embodied, browser-native 3D AI agents on any webpage. The first enterprise platform for on-chain 3D AI agents available through AWS.- [HUGE revamp coming to the landing page + dashboard](https://three.ws/news/2060186881636422038): HUGE revamp coming to the landing page + dashboard I have completely renovated the site making the entire site more user friendly + tons of new features to be announced over the next couple of days. Will be pushing these new features to the site three.ws- [We still have plenty of time to make it to #1 spot on ProductHunt, I need everyone in…](https://three.ws/news/2060178868305326413): We still have plenty of time to make it to #1 spot on ProductHunt, I need everyone in full force helping to spread our page and share thoughts on the page what you like, dislike, anything you can to help us get the word out! producthunt.com/products/three-ws-2?launch=three-wsdiff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 65dbde33f..25d41aead 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -79,7 +79,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 542 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 543 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -91,7 +91,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 542 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 543 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -3309,7 +3309,7 @@<section class="sm-section" id="news"><header>- <h2>News<span class="sm-count" data-count>109</span></h2>+ <h2>News<span class="sm-count" data-count>110</span></h2><p class="sm-section-desc">Product launches, integrations, and announcements from three.ws.</p></header><ul class="sm-list">@@ -3320,6 +3320,13 @@<span class="sm-desc">Product launches, integrations, and announcements from three.ws.</span></a></li>+ <li>+ <a href="/news/monetize-mcp-server-x402-paid-tools">+ <span class="sm-title">How to Monetize an MCP Server: Paid Tools with x402</span>+ <span class="sm-path">/news/monetize-mcp-server-x402-paid-tools</span>+ <span class="sm-desc">The seller-side guide to agent payments: choose work worth charging for, price it in atomic USDC units, answer unpaid calls with a real 402, verify then work then settle, charge per tool inside an MCP tools/call, and get indexed where agents shop for paid services.</span>+ </a>+ </li><li><a href="/news/quicknode-startup-program"><span class="sm-title">three.ws Joins the Quicknode Startup Program</span>@@ -3450,7 +3457,7 @@<a href="/news/aws-builder-center-blog"><span class="sm-title">three.ws Publishes on the AWS Builder Center Blog</span><span class="sm-path">/news/aws-builder-center-blog</span>- <span class="sm-desc">three.ws's contribution is live on the official AWS Builder Center Blog: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3" — covering ResolveCustomer, MeterUsage, entitlements, SNS lifecycle webhooks, and bridging to an on-chain x402 paywall.</span>+ <span class="sm-desc">three.ws's contribution is live on the official AWS Builder Center Blog: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3". It covers ResolveCustomer, MeterUsage, entitlements, SNS lifecycle webhooks, and bridging to an on-chain x402 paywall.</span></a></li><li>diff --git a/scratch-call.mjs b/scratch-call.mjsnew file mode 100644index 000000000..d78626ad5--- /dev/null+++ b/scratch-call.mjs@@ -0,0 +1,11 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+const [target, name, argsJson] = process.argv.slice(2);+const t = new StdioClientTransport({ command: process.execPath, args: [target] });+const c = new Client({ name: 'probe', version: '0.0.0' });+await c.connect(t);+const r = await c.callTool({ name, arguments: JSON.parse(argsJson || '{}') });+console.log('isError:', r.isError);+const txt = r.content?.[0]?.text ?? '';+console.log(txt.slice(0, 2500));+await c.close();diff --git a/scratch-probe.mjs b/scratch-probe.mjsnew file mode 100644index 000000000..889711de8--- /dev/null+++ b/scratch-probe.mjs@@ -0,0 +1,11 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';++const target = process.argv[2];+const t = new StdioClientTransport({ command: process.execPath, args: [target], stderr: 'inherit' });+const c = new Client({ name: 'probe', version: '0.0.0' });+await c.connect(t);+const { tools } = await c.listTools();+console.log(target, '->', tools.length, 'tools');+for (const x of tools) console.log(' -', x.name, JSON.stringify(Object.keys(x.inputSchema?.properties||{})));+await c.close();diff --git a/scratch-schema.mjs b/scratch-schema.mjsnew file mode 100644index 000000000..876edc5cf--- /dev/null+++ b/scratch-schema.mjs@@ -0,0 +1,9 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+const t = new StdioClientTransport({ command: process.execPath, args: [process.argv[2]] });+const c = new Client({ name: 'p', version: '0' });+await c.connect(t);+const { tools } = await c.listTools();+const one = tools.find((x) => x.name === process.argv[3]);+console.log(JSON.stringify(one, null, 2));+await c.close();