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
docs(custody): state the honest anchoring limits and cover MCP catalog performance
nirholas3237758b71b7
diff --git a/docs/custody.md b/docs/custody.mdindex 0083fae33..22b2488c5 100644--- a/docs/custody.md+++ b/docs/custody.md@@ -44,16 +44,18 @@ Every six hours, an attestation epoch runs:1. Every custodial wallet's **live mainnet balance** is read.2. Each wallet becomes a leaf: agent, address, balance, and the current head of its custody event trail, hashed together.3. The leaves build a Merkle tree; the epoch and leaves are persisted.-4. The root is anchored on Solana as a signed SPL-Memo transaction.+4. The root is anchored on Solana as a signed SPL-Memo transaction, when an attester key is configured and funded (see **Honest limits** below).Two public surfaces:-- **[/integrity](https://three.ws/integrity)** — the aggregate view, no sign-in: latest epoch, Merkle root, the anchor transaction, wallet count, total SOL, recent epochs. API: `GET /api/custody/integrity`, `GET /api/custody/anchor?epoch=latest`.-- **[/proof](https://three.ws/proof)** — your wallet's inclusion proof (owner-only, since it reveals a per-wallet balance). The page fetches your proof and then **re-verifies it in your browser** with an independent verifier: it recomputes your leaf hash from the public fields, walks the Merkle path, and checks the root against the anchor. The prover and verifier share one hashing module, so they cannot silently drift.+- **[/integrity](https://three.ws/integrity)** is the aggregate view, no sign-in: latest epoch, Merkle root, the anchor transaction (once an epoch is anchored), wallet count, total SOL, recent epochs. API: `GET /api/custody/integrity`, `GET /api/custody/anchor?epoch=latest`.+- **[/proof](https://three.ws/proof)** is your wallet's inclusion proof (owner-only, since it reveals a per-wallet balance). The page fetches your proof and then **re-verifies it in your browser** with an independent verifier: it recomputes your leaf hash from the public fields, walks the Merkle path, and checks the result against the epoch's published root. The prover and verifier share one hashing module, so they cannot silently drift. Where the epoch is anchored, that same root is what the on-chain memo commits to.Epochs also run a reconciliation pass: any balance drop since the previous epoch must be explained by authorized withdraw/spend events (plus fee tolerance), or it's flagged. "No unexplained outflows" is a checked property, not a slogan.-**Honest limits.** The anchor transaction's network is deployment-configurable and may be Solana devnet rather than mainnet — the anchor reference returned by the API states its network; check it before treating an anchor as mainnet-final. Anchoring is best-effort: if the attester key is unavailable, the epoch's root still exists and is served, with its anchor status marked pending. Balance reads are mainnet regardless.+**Honest limits.** Anchoring is best-effort and is the one step in this pipeline that can fail on its own. Steps 1 to 3 (balance snapshot, leaf hashing, Merkle tree, persistence) always run; step 4 needs a configured, funded attester key, and when it does not have one the epoch is still recorded and served with `anchor_status` set to `anchor_failed` rather than `anchored`, and a null `anchor_sig`. A root in that state is a real, reproducible commitment you can verify your inclusion against, but it is not yet timestamped on a public chain, so it does not prove the platform published it before you asked.++Check the epoch you are relying on rather than assuming: `GET /api/custody/integrity` reports `epochs_total` against `epochs_anchored`, and `GET /api/custody/anchor?epoch=latest` returns that epoch's `anchor_status`, `anchor_sig`, and `anchor_network`. The anchor network is deployment-configurable and may be Solana devnet rather than mainnet, so read `anchor_network` before treating any anchor as mainnet-final. Balance reads are mainnet regardless of where the anchor lands.## Social recovery & inheritance@@ -71,7 +73,7 @@ A funded agent shouldn't die with a lost password — or with its owner. The mod**Inheritance (dead-man's switch):** the owner enables it with an inactivity threshold (7–365 days) and a grace window. "Alive" is inferred from sessions, custody events, usage, or an explicit check-in. When inactivity crosses the line, an inheritance request opens to the beneficiary; it needs guardian confirmation (or the beneficiary's own, if no guardians are set) *and* the grace window; a daily sweep arms, reminds (about a week ahead), and completes; any owner check-in cancels the whole thing.-**The guardian console — [/guardian](https://three.ws/guardian)** — is the inbox for the *other* side: agents where you are the guardian or beneficiary, the active request's story, approval counts, countdowns, and the approve / decline / confirm actions. (Not to be confused with the Guardian *content-safety* model — `@three-ws/guardian` — which is an unrelated AI-moderation surface.)+**The guardian console, [/guardian](https://three.ws/guardian)**, is the inbox for the *other* side: agents where you are the guardian or beneficiary, the active request's story, approval counts, countdowns, and the approve / decline / confirm actions. (Not to be confused with the Guardian *content-safety* model, `@three-ws/guardian`, which is an unrelated AI-moderation surface.)Every step of recovery and inheritance writes to the custody trail and the audit log, and notifies everyone involved.diff --git a/docs/tutorials/agent-reputation.md b/docs/tutorials/agent-reputation.mdindex 8d7f677a4..153a2c157 100644--- a/docs/tutorials/agent-reputation.md+++ b/docs/tutorials/agent-reputation.md@@ -1,71 +1,89 @@# Tutorial: Read an Agent's On-Chain Reputation (ERC-8004)-Look up any registered agent's trust record — its score, its vouches, and the money staked behind them — from the UI, a single API call, the MCP tool, the SDK, or straight off the contract.+Look up any registered agent's trust record: who vouched for it, what they scored it, and what the platform's own behavioral synthesis says. Read it from an API call, straight off the contract, or through a paid x402 endpoint.-**What you'll build:** a reputation read on any registered agent, on-chain and via API — the same lookup an autonomous agent runs before it decides whether to trust a counterparty.+**What you'll build:** a reputation read on any ERC-8004 agent, on-chain and via API, the same lookup an autonomous agent runs before it decides whether to trust a counterparty.---## Why read reputation at all?-Reading reputation is the half of the system everyone uses and nobody talks about. Writing a review happens once; reading it happens every time someone — or some *agent* — has to decide whether to trust a counterparty they've never met.+Reading reputation is the half of the system everyone uses and nobody talks about. Writing a review happens once; reading it happens every time someone (or some *agent*) has to decide whether to trust a counterparty they have never met.-That decision is the whole point. When an autonomous agent is about to pay another agent for a dataset, a render, or a sub-task, it has no brand to recognize and no human to ask. The only thing it can do is look up the counterparty's on-chain track record and decide if it clears a bar. Reputation reads are **trust gates** — and because they're on-chain, the same read works from a webpage, a server, an AI tool call, or another smart contract, with no API key and no permission.--By the end of this tutorial you'll have run that read five different ways and know which one fits which situation.+That decision is the whole point. When an autonomous agent is about to pay another agent for a dataset, a render, or a sub-task, it has no brand to recognize and no human to ask. The only thing it can do is look up the counterparty's on-chain track record and decide if it clears a bar. Reputation reads are **trust gates**, and because they are on-chain, the same read works from a webpage, a server, an AI tool call, or another smart contract, with no API key and no permission.---## What you'll need-Reading reputation is **free and permissionless** for most paths — no wallet, no gas, no account:+Reading reputation is **free and permissionless** on every path but the last one:-- **An agent identifier.** Any of: a numeric ERC-8004 `agentId` (e.g. `42`), an EVM wallet that owns an agent (`0x…`), a CAIP-10 string (`eip155:8453:0x…`), or a three.ws agent UUID for the REST/x402 paths.-- **Nothing else** for Paths 1, 2, 4, and 5.-- **A funded wallet** *only* for Path 3 (the paid MCP tool costs $0.01 USDC per call) — useful when an AI agent needs the read as a billable, on-chain-verified tool.+- **An agent identifier.** A numeric ERC-8004 `agentId` (e.g. `1`), or a three.ws agent UUID for the platform trust score.+- **Nothing else** for Paths 1, 2, and 3.+- **A funded wallet** *only* for Path 4, the paid x402 behavioral endpoint ($0.01 USDC).-Don't have an agent in mind? Use the [Reputation Explorer](/reputation) to find one, or register your own first with [Register your agent on-chain](/tutorials/register-onchain).+Don't have an agent in mind? Path 1 lists them.---## The data model in 60 seconds-Everything below reads the same three ERC-8004 contracts, so it's worth knowing the shape of the data first:--- **Identity Registry** — each agent is an NFT. The `agentId` is its token ID. This is how a wallet resolves to an agent.-- **Reputation Registry** — stores feedback. Scores are signed `int8` in the range **−100 to +100**; the UI collects them as **1–5 stars** and maps them into that range. The contract keeps a running `(sum, count)`, so the average is a single O(1) read — no indexing required.-- **Validation Registry** — third-party attestations (e.g. "this agent's 3D model passed glTF validation"). Separate from scores.+Two different registries are in play, and telling them apart saves a lot of confusion:-Three rules enforced on-chain shape what you read:+- **Identity Registry** (`0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` on every supported mainnet). Each agent is an ERC-721 token. The `agentId` is its token ID, `ownerOf(agentId)` gives its owner, and `tokenURI(agentId)` returns the agent's ERC-8004 card (a `data:application/json;base64` document, so the card needs no server to resolve).+- **Reputation Registry** (`0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`). Stores feedback as **per-client lists**, not one running average.-1. **One review per wallet per agent** — fake reviews cost one funded wallet each.-2. **No self-review** — an agent's owner can't pump its own score.-3. **Append-only** — a submitted review can never be edited or deleted.+The Reputation Registry's shape matters for anyone reading it:-A review can also be **staked**: the reviewer locks ≥0.001 ETH behind their vouch (refundable). Total stake is a second, harder-to-fake trust signal you can read alongside the score.+- Feedback is grouped **by client**. `getClients(agentId)` returns every address that has ever left feedback, and `getLastIndex(agentId, client)` gives that client's highest feedback index.+- A single entry is `readFeedback(agentId, client, index)`, returning `(uint8 score, bytes32 tag1, string tag2, string fileuri, bool isRevoked)`.+- **Scores are `uint8`, on a 0 to 100 scale.** Not 1 to 5 stars, and not a signed range.+- **Entries are revocable, not deletable.** A revoked entry still exists; it comes back with `isRevoked: true`, and an honest reader filters it out.+- **There is no on-chain average and no on-chain stake.** The contract does not aggregate for you. Any average you see was computed off-chain by whoever read the list, which is exactly what Path 3 does.-> Full reference: [ERC-8004](/docs/erc8004) for identity, [Reputation System](/docs/reputation) for the contract interface, and [Agent Reputation](/docs/agent-reputation) for why the whole stack exists.+> Background reading: [ERC-8004](/docs/erc8004) for the identity standard, [Reputation System](/docs/reputation) for how three.ws uses it, and [Agent Reputation](/docs/agent-reputation) for why the whole stack exists.----## Path 1 — The Reputation Explorer (no code)+## Path 1: The ERC-8004 index (find an agent, no code)++Registered agents are indexed and served free, no key and no payment. Search by name or list the newest:++```bash+curl "https://three.ws/api/agents/8004/search?chain=8453&q=ClawNews&limit=5"+```++```jsonc+{+ "chainId": 8453,+ "query": "ClawNews",+ "count": 1,+ "agents": [+ {+ "agentId": "8453:1", // CAIP-style <chainId>:<agentId>+ "chainId": 8453,+ "owner": "0x89e9e1ab11dd1b138b1dce6d6a4a0926aafd5029",+ "name": "ClawNews",+ "description": "…",+ "registrationUri": "data:application/json;base64,…"+ }+ ]+}+```-The fastest read is the visual one.+Omit `q` to page through the registry (`limit` up to 50, `skip` for pagination). Once you have a numeric id, pull the full record:-1. Open the [Reputation Explorer](/reputation).-2. Paste an identifier: an Ethereum wallet address or an ENS name (resolved automatically). For an ERC-8004 agent, deep-link with `?agent=<chainId>:<agentId>` (e.g. `/reputation?agent=8453:42`).-3. Pick the chain (Base is the default; the registries live at the same address on every supported chain).-4. Read the panel:- - **Average score** (shown as stars out of 5) and **total review count**- - **Recent reviews**: each with the reviewer's address, score, optional comment, and a link to the attestation or transaction on the explorer+```bash+curl "https://three.ws/api/agents/8004/agent?chain=8453&id=1"+```-If the agent has no reviews yet, you'll see a clean empty state rather than a blank: a brand-new agent reads as *unknown*, not *bad*.+`chain` defaults to Base (8453). Both endpoints read the indexed registry, so they answer in one round trip instead of the many RPC calls a raw contract walk needs.----## Path 2 — The REST API (one `fetch`)+## Path 2: The three.ws trust score (one `fetch`)-For a three.ws agent (identified by its platform UUID), hit the REST endpoint. No key, no payment. It returns the agent's **unified wallet trust score**: a 0-100 credibility signal computed from real ledger and on-chain activity, with the ERC-8004 registry read as one of its inputs:+For an agent that lives on three.ws (identified by its platform UUID), the REST endpoint returns a **unified wallet trust score**: a 0-100 credibility signal computed from real ledger and on-chain activity. No key, no payment.```jsconst res = await fetch('https://three.ws/api/agents/<agent-uuid>/reputation');@@ -73,218 +91,169 @@ const rep = await res.json();// {// agent_id: "…",// name: "…",-// score: 62, // 0-100 credit-style score+// score: 4.8, // out of `max`// max: 100,-// tier: "…", tierLabel: "…",-// pillars: [ … ], // per-factor breakdown (tenure, volume, reliability, …)-// evidence: { … }, // links to the on-chain facts behind the score+// tier: "new", tierLabel: "New",+// pillars: [ … ], // per-factor breakdown (tenure, volume, tips, reliability, …)+// evidence: { wallet, ledger, lineage },// computed_at: "2026-…"// }console.log(`${rep.name}: ${rep.score}/${rep.max} (${rep.tierLabel})`);```-The score is cached for ~3 minutes (look for an `X-Cache: HIT|MISS` header), and the same computation feeds the reputation badges on discovery surfaces. Note this endpoint takes the **three.ws agent UUID**, not a raw on-chain `agentId`; for the raw ERC-8004 star aggregate, use the SDK module (Path 4), the contract (Path 5), or the MCP tool (Path 3).-------## Path 3 — The `agent_reputation` MCP tool (for AI agents)--When the *reader* is itself an AI agent — and you want the read to be a metered, on-chain-verified tool call — use the paid MCP tool. It costs **$0.01 USDC**, settled via x402 on Solana, and reads directly from the canonical ERC-8004 deployments with no third-party indexer in the path.--It accepts the same flexible identifier and returns the richest payload of any path:--```jsonc-// tool: agent_reputation-// input:-{- "address": "eip155:8453:0xAbCd…", // agentId, wallet, or CAIP-10 ID- "chain": "base" // optional: name or numeric chainId; default base-}--// output:-{- "chain": "Base",- "chainId": 8453,- "agentId": "42",- "agentRegistry": "eip155:8453:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",- "reputationRegistry": "0x8004BAa17C55a88189AE136b182e5fdA19dE9b63",- "identity": {- "owner": "0x…",- "agentWallet": "0x…",- "uri": "ipfs://…" // the agent's ERC-8004 card- },- "reputation": {- "averageX100": "450", // the contract's average, multiplied by 100- "average": 4.5, // averageX100 / 100; null when count is 0- "count": "6",- "totalStakeWei": "0"- },- "events": { // the scanned log window, plus the latest 25 vouches + stakes- "windowBlocks": 200000,- "fromBlock": 21145678,- "toBlock": 21345678,- "events": [- { "kind": "submitted", "score": 5, "submitter": "0x…", "comment": "fast and accurate", "txHash": "0x…", "blockNumber": 21345678 }- ]- },- "rpc": ["https://mainnet.base.org"],- "fetchedAt": "2026-06-22T18:00:00.000Z"-}-```--Notable behavior:--- **Pass a wallet and it resolves the agent for you** — the tool calls the Identity Registry's `balanceOf` / `tokenOfOwnerByIndex` to find the agent the wallet owns, so you don't need to know the `agentId` up front.-- **`chain` accepts a name or a numeric chainId**, and a CAIP-10 `address` overrides it. Ten EVM chains are supported, defaulting to Base.-- **RPC failover is built in** — an operator override is tried first, then redundant public endpoints, each with a 12-second timeout, so one RPC outage doesn't fail your paid call.-- If no agent is registered for a wallet, you get a clean `no_agent_registered_for_wallet` error, not a misleading zero score.--This is the path to wire into an agent that needs to gate its own spending: read first, then decide whether to pay.-------## Path 4: The reputation module (JavaScript)--Inside a JavaScript app, the in-repo module `src/erc8004/reputation.js` wraps the contract reads with an `ethers` provider (the same module the register-onchain flow and the Reputation Explorer use):--```js-import { getReputation, getRecentReviews, getTotalStake } from './src/erc8004/reputation.js';-import { JsonRpcProvider } from 'ethers';--const provider = new JsonRpcProvider('https://mainnet.base.org');--// Aggregate — already averaged for you-const { count, average } = await getReputation({- chainId: 8453,- agentId: 42,- runner: provider,-});-console.log(`${average.toFixed(1)} average across ${count} reviews`);--// The ETH staked behind those vouches (returns a bigint, in wei)-const stakeWei = await getTotalStake({ chainId: 8453, agentId: 42, runner: provider });--// Recent vouches, decoded from FeedbackSubmitted event logs-const reviews = await getRecentReviews({- chainId: 8453,- agentId: 42,- runner: provider,- fromBlock: 0, // or (latestBlock - 50000) for recent-only-});-reviews.forEach(r => console.log(r.from, r.score, r.comment, r.txHash));-```+Each entry in `pillars` carries its own `points`, `max`, a plain-language `detail`, and the `facts` behind it, so you can show a user *why* a score is what it is rather than just the number. Responses are cached (look for an `X-Cache: HIT|MISS` header).-`getReputation` returns `{ count, average }` with `average` pre-computed (`0` when there are no reviews). `getRecentReviews` returns an array of `{ agentId, from, score, comment, blockNumber, txHash }`. On free-tier RPCs that reject wide `eth_getLogs` queries, narrow `fromBlock` to the last ~50,000 blocks (≈7 days on most L2s), the aggregate read always works regardless.+This endpoint takes the **three.ws agent UUID**, not a raw on-chain `agentId`. For the on-chain feedback list, use Path 3.----## Path 5 — Read the contract directly (`ethers`)+## Path 3: Read the contract directly (`ethers`)-No SDK, no server — just the chain. The Reputation Registry sits at the **same address on every supported EVM chain** (CREATE2 deterministic deployment):+No SDK, no server, just the chain. The Reputation Registry sits at the **same address on every supported EVM chain** (CREATE2 deterministic deployment), so this code works unchanged across all of them:```jsimport { Contract, JsonRpcProvider } from 'ethers';-const REPUTATION_REGISTRY = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63'; // mainnet, all chains+const REPUTATION_REGISTRY = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63';const ABI = [- 'function getReputation(uint256 agentId) view returns (int256 avgX100, uint256 count)',- 'function getTotalStake(uint256 agentId) view returns (uint256)',- 'function getFeedbackCount(uint256 agentId) view returns (uint256)',+ 'function getClients(uint256 agentId) view returns (address[])',+ 'function getLastIndex(uint256 agentId, address client) view returns (uint64)',+ 'function readFeedback(uint256 agentId, address client, uint64 index) view returns (uint8 score, bytes32 tag1, string tag2, string fileuri, bool isRevoked)',+ 'function getIdentityRegistry() view returns (address)',];-const provider = new JsonRpcProvider('https://mainnet.base.org');+const provider = new JsonRpcProvider('https://base-rpc.publicnode.com');const rep = new Contract(REPUTATION_REGISTRY, ABI, provider);-const [avgX100, count] = await rep.getReputation(42);-const average = count === 0n ? 0 : Number(avgX100) / 100; // avgX100 is average × 100-const staked = await rep.getTotalStake(42);+async function readAgentFeedback(agentId) {+ const clients = await rep.getClients(agentId);+ const feedback = [];++ for (const client of clients) {+ const last = await rep.getLastIndex(agentId, client);+ for (let i = 1n; i <= last; i++) {+ try {+ const f = await rep.readFeedback(agentId, client, i);+ if (!f.isRevoked) {+ feedback.push({ client, score: Number(f.score), tag: f.tag2, uri: f.fileuri });+ }+ } catch {+ // A client's index range can be sparse. Skip the gaps rather than aborting.+ }+ }+ }++ const scores = feedback.map((f) => f.score);+ const average = scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : null;+ return { clients: clients.length, count: feedback.length, average, feedback };+}-console.log(`avg ${average} over ${count} reviews, ${staked} wei staked`);+const r = await readAgentFeedback(1);+console.log(`${r.count} live reviews from ${r.clients} clients, average ${r.average}/100`);```-The contract returns the average **multiplied by 100** (`avgX100`) so you can divide client-side without losing precision to integer truncation — divide by 100 to get the real average. It returns `(0, 0)` for an agent with no reviews. The testnet registry lives at `0x8004B663056A597Dffe9eCcC1965A193B7388713`.+Run against Base today, agent 1 (ClawNews) returns real feedback like `{ score: 100, tag: 'tip', uri: 'agent' }` and `{ score: 78, tag: 'worker_rating', uri: 'e2e_2026-02-11' }`.++Two practical notes:++- **The walk is O(clients x entries).** A popular agent means a lot of `eth_call`s, and free public RPCs rate-limit hard. Pace the loop, use a keyed provider, or read the indexed record from Path 1 instead.+- **`average` is yours, not the chain's.** The contract stores raw entries; the mean above is computed client-side, so you can weight it however your trust model wants.++Confirm you are pointed at the right pair of contracts with `await rep.getIdentityRegistry()`. On mainnet it returns `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`.----## Resolve a wallet or ENS to an agent+## Resolve a wallet to an agent-You often start from a wallet or a name, not an `agentId`. Resolve through the Identity Registry:+You often start from a wallet, not an `agentId`. The Identity Registry is an ERC-721, so `ownerOf` and `balanceOf` work:```jsconst IDENTITY_REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';-const idAbi = [+const id = new Contract(IDENTITY_REGISTRY, [+ 'function ownerOf(uint256 agentId) view returns (address)','function balanceOf(address owner) view returns (uint256)',- 'function tokenOfOwnerByIndex(address owner, uint256 i) view returns (uint256)',-];-const id = new Contract(IDENTITY_REGISTRY, idAbi, provider);+ 'function tokenURI(uint256 agentId) view returns (string)',+], provider);-if (await id.balanceOf(wallet) > 0n) {- const agentId = await id.tokenOfOwnerByIndex(wallet, 0n); // → read reputation for this-}+console.log(await id.ownerOf(1)); // 0x89E9E1ab11dD1B138b1dcE6d6A4a0926aaFD5029+console.log(await id.balanceOf(owner)); // how many agents that wallet owns```-For ENS-named agents, three.ws resolves `eip155:<chainId>:<registry>/<agentId>` records — see [ERC-8004 → ENS and DNS integration](/docs/erc8004). The `agent_reputation` MCP tool (Path 3) does this wallet→agent resolution for you automatically.+Going the other way, wallet to `agentId`, has **no on-chain resolver**: the deployment does not implement the ERC-721 enumerable extension, so `tokenOfOwnerByIndex` and `totalSupply` revert. Use the indexed search from Path 1 and match on `owner`, which is one request instead of a log scan.++`tokenURI(agentId)` returns the agent's ERC-8004 card inline as a base64 data URI, so you can decode it without any gateway:++```js+const uri = await id.tokenURI(1);+const card = JSON.parse(atob(uri.split(',')[1]));+```----## Read the behavioral signal too+## Path 4: The behavioral signal (paid, x402)-Star reviews are one signal. For a three.ws agent, you can also read its **behavior** — did it actually get paid, did its payouts succeed, did anyone dispute it — via the paid x402 synthesis endpoint (`$0.01 USDC`):+Feedback entries are what people *said*. For a three.ws agent you can also read what it *did*: whether it actually got paid, whether its payouts succeeded, whether anyone disputed it. That synthesis is a paid x402 endpoint ($0.01 USDC):```GET /api/x402/agent-reputation?subject=<identifier>```-`subject` accepts any identifier (a three.ws agent UUID, a wallet, or a mint); the type is auto-detected.+`subject` accepts any identifier (a three.ws agent UUID, a wallet, or a mint); the type is auto-detected. Called without payment it answers `402` with the payment requirements, which is the handshake an x402 client completes automatically.-It returns confirmed payment count and distinct payers, payout/distribution success rates, failure rates, and attestation counts — reputation derived from what an agent *did*, not just what people *said*. Combine it with the star score for a fuller trust picture; it's the same data the Agent Passport's A–D grade is built from.+It returns confirmed payment count and distinct payers, payout and distribution success rates, failure rates, and attestation counts: reputation derived from behavior rather than from opinion. It is the same data the Agent Passport's A-D grade is built from.---## Putting it together: a trust gate-Here's the pattern that makes reputation worth reading — refuse to transact below a bar:+Here is the pattern that makes reputation worth reading, refusing to transact below a bar:```js-async function trustGate(agentId, { minScore = 4, minReviews = 3 } = {}) {- const { average, count } = await getReputation({ chainId: 8453, agentId, runner: provider });- if (count < minReviews) return { ok: false, reason: 'not enough history' };- if (average < minScore) return { ok: false, reason: `score ${average.toFixed(1)} below ${minScore}` };+async function trustGate(agentId, { minScore = 70, minClients = 3 } = {}) {+ const { average, count, clients } = await readAgentFeedback(agentId);+ if (clients < minClients) return { ok: false, reason: 'not enough distinct reviewers' };+ if (count === 0) return { ok: false, reason: 'no live feedback' };+ if (average < minScore) return { ok: false, reason: `score ${average.toFixed(0)} below ${minScore}` };return { ok: true };}-const gate = await trustGate(42);+const gate = await trustGate(1);if (gate.ok) {- // …proceed to pay / delegate via x402+ // proceed to pay / delegate via x402} else {console.warn('skipping agent:', gate.reason);}```-This is exactly the bouncer pattern three.ws's own Pole Club uses at its door — read a wallet's history, assign it a tier, admit or refuse — except an on-chain read works for *any* agent on *any* platform, not just inside one venue's private database. That portability is the entire reason reputation lives on-chain. ([Why it matters →](/docs/agent-reputation))+Gate on **distinct clients**, not on the entry count. One address can leave many entries, so a raw count is the easiest number for a bad actor to inflate; the number of independent wallets willing to vouch is not.++This is the same bouncer pattern three.ws's own Pole Club uses at its door, read a wallet's history, assign it a tier, admit or refuse, except an on-chain read works for *any* agent on *any* platform rather than inside one venue's private database. That portability is the entire reason reputation lives on-chain. ([Why it matters](/docs/agent-reputation))---## Troubleshooting-**`getReputation` returns `(0, 0)`**-- The agent has no reviews yet, or you're querying the wrong chain. Reputation is per-chain — an agent registered on Base has no reviews on Arbitrum. Confirm the `chainId`.+**Every contract read reverts with "missing revert data"**+- You are calling a function the deployment does not have. The live registries implement `getClients` / `getLastIndex` / `readFeedback`; a call to an aggregate helper like `getReputation` or `getTotalStake` reverts with empty returndata, which `ethers` surfaces as this message. Use the ABI in Path 3 verbatim.++**`getClients` returns an empty array**+- The agent has no feedback yet on that chain, or you are on the wrong chain. Feedback is per-chain: an agent registered on Base has none on Arbitrum. A brand-new agent reads as *unknown*, not *bad*.-**Average looks 100× too big**-- You read `avgX100` directly. Divide by 100 — the contract returns the average multiplied by 100 on purpose (Path 5).+**`readFeedback` reverts partway through a client's range**+- Index ranges can be sparse. Wrap the read in a `try` and skip the gap, as Path 3 does, rather than treating it as a failure.-**`total_stake_wei` parses wrong / shows as a rounded number**-- It's a string holding a wei value that overflows `Number`. Parse with `BigInt(rep.total_stake_wei)`, then format to ETH by dividing by `10n ** 18n`.+**Scores look 20x too small**+- Scores are `uint8` on a 0-100 scale, not 1-5 stars. A `78` is a good review, not a broken one.-**Recent vouches are empty but the count is non-zero**-- A free-tier RPC rejected the `eth_getLogs` query for the block window. The aggregate (score + count) still reads correctly; narrow `fromBlock` or use a provider that allows wider log ranges to recover the individual reviews.+**`over rate limit` from the RPC**+- The per-client walk makes a lot of `eth_call`s. Pace the loop, switch to a keyed provider, or read the indexed record from Path 1.-**The MCP tool returns `no_agent_registered_for_wallet`**-- That wallet doesn't own an ERC-8004 agent on the chosen chain. Pass a numeric `agentId` directly, or switch chains — the same wallet may own an agent elsewhere.+**`tokenOfOwnerByIndex` reverts**+- The Identity Registry does not implement the ERC-721 enumerable extension. Resolve wallet to agent through the Path 1 search API instead.-**`fetch` to the REST endpoint 404s**-- Use the agent's three.ws UUID for `/api/agents/<id>/reputation`. For a raw on-chain `agentId` or wallet, use the reputation module (Path 4), the contract (Path 5), or the MCP tool (Path 3) instead.+**`fetch` to the trust-score endpoint 404s**+- `/api/agents/<id>/reputation` takes the agent's three.ws UUID. For a raw on-chain `agentId`, use Path 1 or Path 3.---@@ -292,9 +261,10 @@ This is exactly the bouncer pattern three.ws's own Pole Club uses at its doorYou can read reputation. Now close the loop:-- **[Leave a vouch](/docs/reputation)** — write a review or a staked vouch of your own, from the UI or the SDK.-- **[Register your agent on-chain](/tutorials/register-onchain)** — give an agent the identity that reputation attaches to, so others can vouch for *it*.-- **[Agent Reputation: why it matters](/docs/agent-reputation)** — the trust problem reputation solves, the three registries, and how reputation and x402 payments interlock.-- **[ERC-8004 reference](/docs/erc8004)** — the full identity standard, agent-card format, and contract addresses across every supported chain.+- **[Leave a vouch](/docs/reputation)** write a review of your own, from the UI or the SDK.+- **[Register your agent on-chain](/tutorials/register-onchain)** give an agent the identity that reputation attaches to, so others can vouch for *it*.+- **[Read a Solana agent's reputation](/tutorials/solana-agent-reputation)** the Solana counterpart, where trust is built from signed memo attestations.+- **[Agent Reputation: why it matters](/docs/agent-reputation)** the trust problem reputation solves, and how reputation and x402 payments interlock.+- **[ERC-8004 reference](/docs/erc8004)** the full identity standard, agent-card format, and contract addresses across every supported chain.A read costs nothing and asks no one's permission. That's the property that lets an agent you've never heard of decide, on its own, to trust yours.diff --git a/tests/x402-mcp-perf.test.js b/tests/x402-mcp-perf.test.jsnew file mode 100644index 000000000..85066bb14--- /dev/null+++ b/tests/x402-mcp-perf.test.js@@ -0,0 +1,111 @@+/**+ * GET /api/x402/mcp-perf: the MCP latency SLA feed the dashboard renders.+ *+ * Two behaviours here are deliberate and easy to "fix" into something worse:+ *+ * - A breach is still a 200. The dashboard draws the breach itself, so+ * answering non-2xx would make a tool over its p95 indistinguishable from+ * the endpoint being down.+ * - A missing table (the sweep has never run) is 200 with note+ * no_samples_yet, while a real read failure is 503. One of those is a cold+ * start, the other is an outage, and they must not read alike.+ *+ * The window is clamped rather than trusted, because it goes into a rolling+ * query: an unbounded one is a free way to make the database do arbitrary work.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++let health = null;+let failure = null;++vi.mock('../api/_lib/x402/mcp-latency-sweep.js', () => ({+ readPerfHealth: async ({ windowHours }) => {+ if (failure) throw failure;+ return { ...health, window_hours: windowHours };+ },+}));++const { default: handler } = await import('../api/x402/mcp-perf.js');++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(payload) { this.headersSent = true; this.writableEnded = true; this.body = payload; },+ get json() { return this.body ? JSON.parse(this.body) : null; },+ };+}++const req = (url = '/api/x402/mcp-perf') => ({ method: 'GET', url, headers: {}, socket: {} });++beforeEach(() => {+ failure = null;+ health = {+ ok: true,+ healthy: false,+ tool_count: 12,+ breach_count: 1,+ breaches: [{ tool: 'render_avatar', p95_ms: 4200, sla_ms: 3000 }],+ tools: [{ tool: 'render_avatar', p50_ms: 900, p95_ms: 4200, p99_ms: 6100, samples: 41 }],+ };+});++describe('GET /api/x402/mcp-perf', () => {+ it('reports a breached SLA as a 200 the dashboard can render', async () => {+ const res = mockRes();+ await handler(req(), res);++ expect(res.statusCode).toBe(200);+ expect(res.json.healthy).toBe(false);+ expect(res.json.breach_count).toBe(1);+ expect(res.json.breaches[0].tool).toBe('render_avatar');+ expect(res.json.generated_at).toBeTruthy();+ });++ it('clamps the requested window to the supported range', async () => {+ const res = mockRes();+ await handler(req('/api/x402/mcp-perf?window=100000'), res);+ expect(res.json.window_hours).toBe(168);++ const res2 = mockRes();+ await handler(req('/api/x402/mcp-perf?window=6'), res2);+ expect(res2.json.window_hours).toBe(6);++ const res3 = mockRes();+ await handler(req('/api/x402/mcp-perf?window=not-a-number'), res3);+ expect(res3.json.window_hours).toBe(24);+ });++ it('answers 200 no_samples_yet before the sweep has ever written a row', async () => {+ failure = new Error('relation "x402_perf_log" does not exist');+ const res = mockRes();+ await handler(req(), res);++ expect(res.statusCode).toBe(200);+ expect(res.json.note).toBe('no_samples_yet');+ expect(res.json.tool_count).toBe(0);+ expect(res.json.error).toBeUndefined();+ });++ it('answers 503 on a real read failure', async () => {+ failure = new Error('connection terminated unexpectedly');+ const res = mockRes();+ await handler(req(), res);++ expect(res.statusCode).toBe(503);+ expect(res.json.ok).toBe(false);+ expect(res.json.error).toBe('perf_read_failed');+ });++ it('refuses a method other than GET', async () => {+ const res = mockRes();+ await handler({ ...req(), method: 'DELETE' }, res);+ expect(res.statusCode).toBe(405);+ });+});