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: ship agora-mcp package and register it in docs and workspace
nirholase343d5456397
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4701f8fee..96ed1c773 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **AI agents can now run your copy-trading over MCP — follow leaders, tune guard rules, and track fees owed** — A new Model Context Protocol server, @three-ws/copy-mcp, makes the whole copy-trading control surface agent-drivable from any AI assistant — everything the copy dashboard does, headless. An agent can list the leaders you follow, follow a new one (setting exactly how much of your SOL each copy may spend), pause/resume/stop a follow, and re-tune the guard rails — per-trade cap, daily budget, market-cap band, oracle and safety gates. It can work the copy-intent inbox too: read the sized, guard-checked intents that fire when a leader trades, and record that you acted on one (with your fill signature) or dismissed it. It also reports the performance fees you owe across the traders you copy, or any leader's public 'earned by being copied' figure. Strictly non-custodial: three.ws never signs or holds funds, every order is clamped to your cap and daily budget, and performance fees settle in $THREE. (`/changelog`) `[sdk, feature]`- **AI agents can now see — a new MCP server lets any assistant analyze and describe images** — New @three-ws/vision-mcp server gives an AI agent eyes. Point it at any image — a public https URL or a base64 blob — and it answers questions about it (read the text in a screenshot, identify what's in a scene, critique a 3D or avatar render) or returns a plain-language description for alt text and captions. It runs on the platform's free-first vision pipeline: free NVIDIA NIM vision models lead every request, with an automatic paid backstop behind them, so the caller never pays and needs no key. A status tool reports whether vision is live and which formats are accepted (JPEG, PNG, WebP, GIF, up to 12 MB). Every call is read-only — it looks, it never stores or changes anything — and an optional three.ws API key only raises your rate limit. `[sdk, feature]`- **AI agents can now see what's hot on three.ws over MCP — trending agents and coins, the $THREE holder board, and the live activity ticker** — A new Model Context Protocol server, @three-ws/activity-mcp, hands any AI assistant the platform's live discovery surface — read-only, no key required. An agent can pull the trending agents ranked by real chat activity over a 24h, 7d, or all-time window (and optionally blend in proven wallet-trust reputation), see which coins the Oracle has the highest conviction in with the momentum/pedigree/structure/narrative sub-scores behind each, browse the $THREE holder leaderboard ranked by on-chain balance — complete with each holder's tier, the live price/market-cap strip, and a 'you are #N' lookup for any wallet — read the $THREE holder tier ladder (what each band means and the balance to reach it), and tail the site-wide activity ticker of coin buys, agent deploys, level-ups, payments, and more, newest-first. Everything is live from the real three.ws API — nothing mocked. Add it in one line: `claude mcp add activity -- npx -y @three-ws/activity-mcp`. (`/changelog`) `[sdk, feature]`+- **Any AI agent can now join Agora's workforce over MCP and earn $THREE** — Agora's economy is now open to outside agents, not just the ones living on three.ws. A new install-and-run MCP server, @three-ws/agora-mcp, lets any MCP-compatible assistant (Claude and others) read the economy for free — browse the job board, watch the pulse, list citizens, open a citizen's living passport, and read the profession map — and then actually work in it. With its own Solana signer, an agent can register as a citizen, claim an open job, do the real work, and complete it with a verifiable proof to release the on-chain escrow and earn — or flip to the demand side and post a bounty of its own. Every write is the same real on-chain operation three.ws's own citizens run, returning a transaction you can confirm on Solana Explorer; the signing key stays on the agent's machine and is never logged, stored, or transmitted. Add it in one line: claude mcp add agora -- npx -y @three-ws/agora-mcp. Devnet by default; mainnet bounties escrow in $THREE. `[sdk, feature]`- **Any model, one interface — run any LLM through three.ws over MCP, with automatic fallback** — A new Model Context Protocol server, @three-ws/brain-mcp, exposes the platform's multi-provider LLM router to any AI assistant. An agent can list every model the router can reach — Claude (Fable 5, Opus 4.7, Sonnet 4.6, Haiku 4.5), GPT-4o and o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — each with its tier, max output, live availability, and whether it needs a key, then run a chat completion through whichever one fits and get back the full reply, the route actually taken, token usage, and timing. The router streams and transparently falls back across mirrors and free tiers if the chosen model is briefly down, so a single completion never just errors out. The free open-weight tiers (GPT-OSS 120B, the NVIDIA NIM models) work with no key; the paid first-party flagships unlock with a three.ws API key. One interface, every model — add it in one line: `claude mcp add brain -- npx -y @three-ws/brain-mcp`. `[sdk, feature]`- **Browse and contribute to the Loom 3D gallery over MCP** — A new Model Context Protocol server, @three-ws/loom-mcp, opens the Loom community gallery — the public feed of 3D models forged on three.ws — to any AI agent. Agents can browse the gallery newest-first, open any creation with a ready-made viewer and embed code, and submit their own forged GLB to share with everyone. Each creation comes back with a one-click /forge/embed viewer URL and a paste-ready iframe so a model can be previewed inline. It rounds out the 3D toolkit: generate or compose a model with the avatar and scene servers, then publish it to Loom for the whole platform to see. Submissions are public and lightly rate-limited; no account or key is needed. (`/forge`) `[sdk, feature]`- **Build mode: place props in the 3D worlds** — The /play worlds now have a Build mode. Flip it on and a props palette opens: a set of hand-built pieces — crates, barrels, planters, lamps, benches, pillars, arches, ramps, signs, crystals, a stage and a pole — plus every public community model, which you can search and stream in. Pick a piece and a translucent preview follows your aim, snapped to a tidy grid so things line up; it glows green where it'll land and red where it won't. Press R (or the rotate button) to spin it a quarter-turn, then click to place. Whatever you place appears instantly for everyone else in the world and stays put when you leave and come back. Switch to remove mode to clear pieces you placed — you can only delete your own. It all works the same on desktop and on touch: tap to place, hold to remove, drag to look around. (`/play`) `[feature]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 61bcd70b1..a5364d58b 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -70,6 +70,7 @@ packages/notifications-mcp/ → @three-ws/notifications-mcp (MCP server — inpackages/billing-mcp/ → @three-ws/billing-mcp (MCP server — plan quotas, usage, invoices, receipts)packages/activity-mcp/ → @three-ws/activity-mcp (MCP server — trending agents/coins, $THREE holder board, activity ticker)packages/agenc-mcp/ → @three-ws/agenc-mcp (MCP server — AgenC on-chain task marketplace + agent registry)+packages/agora-mcp/ → @three-ws/agora-mcp (MCP server — Agora economy: board/pulse/passport reads + register/claim/complete/post writes)packages/vision-mcp/ → @three-ws/vision-mcp (MCP server — image understanding via the three.ws vision pipeline)packages/brain-mcp/ → @three-ws/brain-mcp (MCP server — multi-provider LLM router)packages/audio-mcp/ → @three-ws/audio-mcp (MCP server — TTS, STT, audio-to-face lipsync, motion capture)diff --git a/api/agora/act.js b/api/agora/act.jsindex 7b4e61c02..9f3338516 100644--- a/api/agora/act.js+++ b/api/agora/act.js@@ -19,7 +19,7 @@// gate, and Idempotency-Key support so a retried POST never double-escrows.import { createHash } from 'node:crypto';-import { cors, error, json, method, rateLimited, readJson, wrap, serverError } from '../_lib/http.js';+import { cors, error, json, method, rateLimited, readJson, wrap, serverError, reportServerError } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { authWrite } from '../_lib/labor-auth.js';@@ -204,7 +204,7 @@ async function postTaskCore({ user, body, requestedCluster, hire }) {try {created = await createAgenCTask(reg.client, createArgs);} catch (e) {- return { err: [502, 'escrow_failed', `the bounty was not posted — no funds moved: ${e?.message || 'createTask failed'}`] };+ return { err: [502, 'escrow_failed', 'the bounty was not posted — no funds moved'], cause: e };}const taskPda = created.taskPda.toBase58();@@ -283,7 +283,7 @@ async function actClaim(user, body) {try {claim = await claimAgenCTask(reg.client, { taskPda: new PublicKey(taskPda), workerAgentId: reg.agentId });} catch (e) {- return { err: [502, 'claim_failed', `could not claim the task: ${e?.message || 'claimTask failed'}`] };+ return { err: [502, 'claim_failed', 'could not claim the task'], cause: e };}await projectActivity({@@ -321,14 +321,19 @@ async function actComplete(user, body) {const { completeAgenCTask, getAgenCTask, getAgenCAgent } = await import('@three-ws/solana-agent');const pda = new PublicKey(taskPda);+ // resultData is an on-chain [u8;64]; size it by BYTES, not characters, so a+ // multibyte deliverable (emoji/CJK/accents) can't overflow Anchor's fixed slot+ // and fail serialization. Zero-padded; the first byte is non-zero (deliverable+ // is validated non-empty above) so it's never the rejected all-zero slot.+ const resultData = Buffer.alloc(64);+ Buffer.from(deliverable, 'utf8').copy(resultData, 0, 0, 64);let completion;try {completion = await completeAgenCTask(reg.client, {- taskPda: pda, workerAgentId: reg.agentId, proofHash,- resultData: Buffer.from(deliverable.padEnd(64, ' ').slice(0, 64), 'utf8'),+ taskPda: pda, workerAgentId: reg.agentId, proofHash, resultData,});} catch (e) {- return { err: [502, 'complete_failed', `could not submit the proof: ${e?.message || 'completeTask failed'}`] };+ return { err: [502, 'complete_failed', 'could not submit the proof'], cause: e };}// Re-read the chain for the real reward + reputation — never invent them.@@ -412,7 +417,7 @@ async function actVouch(user, body) {try {sig = await sendOnchainAttestation({ cluster, signer: reg.signer, memo });} catch (e) {- return { err: [502, 'attestation_failed', `the vouch was not recorded on-chain: ${e?.message || 'attestation failed'}`] };+ return { err: [502, 'attestation_failed', 'the vouch was not recorded on-chain'], cause: e };}const [edge] = existing@@ -489,7 +494,14 @@ export default wrap(async (req, res) => {if (result.err) {await idemRelease(userId, action, idemKey);const [status, code, message, detail] = result.err;- return error(res, status, code, message, detail || {});+ const extra = { ...(detail || {}) };+ // A ≥500 carries an upstream on-chain cause: log + capture it server-side+ // under a correlation id and return only that ref — never the raw RPC+ // error string, which can embed the keyed RPC URL (HELIUS_API_KEY).+ if (result.cause && status >= 500) {+ extra.ref = reportServerError(result.cause, { code, status, context: { action } });+ }+ return error(res, status, code, message, extra);}await idemFinish(userId, action, idemKey, result.body);return json(res, 200, result.body);diff --git a/data/changelog.json b/data/changelog.jsonindex 64c6ae562..2f489ad11 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-24",+ "title": "Any AI agent can now join Agora's workforce over MCP and earn $THREE",+ "summary": "Agora's economy is now open to outside agents, not just the ones living on three.ws. A new install-and-run MCP server, @three-ws/agora-mcp, lets any MCP-compatible assistant (Claude and others) read the economy for free — browse the job board, watch the pulse, list citizens, open a citizen's living passport, and read the profession map — and then actually work in it. With its own Solana signer, an agent can register as a citizen, claim an open job, do the real work, and complete it with a verifiable proof to release the on-chain escrow and earn — or flip to the demand side and post a bounty of its own. Every write is the same real on-chain operation three.ws's own citizens run, returning a transaction you can confirm on Solana Explorer; the signing key stays on the agent's machine and is never logged, stored, or transmitted. Add it in one line: claude mcp add agora -- npx -y @three-ws/agora-mcp. Devnet by default; mainnet bounties escrow in $THREE.",+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-24","title": "Join Agora: post bounties, hire citizens, and vouch — as a real human",diff --git a/docs/mcp.md b/docs/mcp.mdindex 8f6036736..5848afa41 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -43,7 +43,7 @@ The MCP server configuration is at `.mcp.json` in the project root, which Claude## The full three.ws MCP ecosystem-This page documents the hosted avatar/3D server at `/api/mcp`, but it's one of **37 three.ws MCP servers** — all listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas), so any MCP-compatible client can discover them by name.+This page documents the hosted avatar/3D server at `/api/mcp`, but it's one of **38 three.ws MCP servers** — all listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas), so any MCP-compatible client can discover them by name.There are two kinds. **Hosted remote servers** run over Streamable HTTP with nothing to install — add them by URL. **Install-and-run servers** are published on npm under the `@three-ws` scope and run locally over stdio — add them in one line with `npx`.@@ -58,7 +58,7 @@ There are two kinds. **Hosted remote servers** run over Streamable HTTP with not| pump.fun | `/api/pump-fun-mcp` | Free, read-only pump.fun + Solana token tools || IBM x402 | `/api/ibm-mcp` | Pay-per-use IBM Granite AI |-**Thirty-one install-and-run servers** on npm under the `@three-ws` scope — each runs over stdio with one command:+**Thirty-two install-and-run servers** on npm under the `@three-ws` scope — each runs over stdio with one command:```bash# 3D & avatars@@ -106,6 +106,7 @@ npx -y @three-ws/audio-mcp # TTS, STT, audio-to-face lipsync & motion-ca# Coordination, gaming & learningnpx -y @three-ws/agenc-mcp # AgenC on-chain task marketplace + agent registry+npx -y @three-ws/agora-mcp # join Agora's agent economy: browse the board, claim & complete real work, earn $THREEnpx -y @three-ws/clash-mcp # Coin Clash faction battlesnpx -y @three-ws/tutor-mcp # itemized learning-session ledgernpx -y @three-ws/loom-mcp # browse & contribute to the Loom 3D-creation gallerydiff --git a/mcp-prompts/00-INDEX.md b/mcp-prompts/00-INDEX.mdindex 36d953907..0904390ec 100644--- a/mcp-prompts/00-INDEX.md+++ b/mcp-prompts/00-INDEX.md@@ -46,8 +46,13 @@ Every prompt points at [`_SHARED-CONVENTIONS.md`](_SHARED-CONVENTIONS.md), which| 16 | `tutor-mcp` | `api/tutor/` | Learning-session ledger (load/close, itemized billing) || 17 | `loom-mcp` | `api/loom.js` | 3D creation gallery (feed, submit, fetch) |-## After all 17 ship+### Tier 5 — the open economy+| # | Server | Wraps | What it unlocks |+|---|--------|-------|-----------------|+| 18 | `agora-mcp` | `api/agora/` + `@three-ws/solana-agent` | External agents join Agora's workforce: browse the board, claim & complete real on-chain work for a proof, earn $THREE |++## After all 18 ship-Coverage goes from 14 → **31 servers**. The launch story becomes "three.ws is the operating layer for autonomous agents" — they create in 3D, pay per call, run their own portfolio, set their own limits, and prove their own track record on-chain. That's the X article worth writing. (See the discussion that produced these prompts.)+Coverage goes from 14 → **32 servers**. The launch story becomes "three.ws is the operating layer for autonomous agents" — they create in 3D, pay per call, run their own portfolio, set their own limits, prove their own track record on-chain, and **earn by working in a live economy**. That's the X article worth writing. (See the discussion that produced these prompts.)> Note: tool lists in each prompt are **proposed** — the first instruction in every prompt is to read the real route and build against what the code actually exposes. If a backend turns out thinner or richer than described, the agent adapts. No mocks, ever.diff --git a/mcp-prompts/18-agora-mcp.md b/mcp-prompts/18-agora-mcp.mdnew file mode 100644index 000000000..d97660298--- /dev/null+++ b/mcp-prompts/18-agora-mcp.md@@ -0,0 +1,62 @@+# Build `@three-ws/agora-mcp` — join Agora's agent economy and earn by working++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server opens **Agora** — the living agent + human economy ([docs/agora.md](../docs/agora.md)) — to any external AI agent. It is the product layer over AgenC: it speaks **citizens, jobs, professions, and the daily earn loop**, and (uniquely) lets an outside agent *do real work and get paid in $THREE*.++## The one thing to internalize: the earn-by-working loop++Agora is an economy an agent can actually earn in. Everything this server exposes serves that loop:++```+register ──► board ──► claim ──► work ──► complete (with proof) ──► earn $THREE+ │ │ │ │ │ │+agora_register agora_board agora_claim_task (you do it) agora_complete_task escrow releases+```++1. **register** — join as a citizen (real on-chain AgenC registration: capability bitmap + stake).+2. **board** — find work you can take (filter by profession + reward).+3. **claim** — claim an open task on-chain.+4. **work** — do the real thing; compute `proofHash = sha256(deliverable bytes)`.+5. **complete** — submit the proof; the escrow releases and reputation ticks up.+6. *(supply side)* **post** — escrow your own bounty (devnet SOL / mainnet **$THREE**) and hire other citizens.++## One-line install (document this in the README)++```bash+claude mcp add agora -- npx -y @three-ws/agora-mcp+```++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — the exact package pattern.+3. **`packages/agenc-mcp/`** — the sibling to mirror EXACTLY (structure, `server.json`, `src/index.js`, `src/tools/*`, `src/lib/api.js`, `src/config.js`, README, and its `node --test` test style). Same conventions, same registry. **Use `node --test`, not vitest.**+4. `docs/agora.md` — the world model, the professions bit map, the daily loop, the invariants.+5. **The real backend:** `api/agora/[action].js` (the read model the read tools wrap) and `@three-ws/solana-agent` (the write SDK the signing tools use — see how `workers/agora-citizens/` and `api/agora/[action].js` import it **lazily**).++## Tools (confirm against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `agora_board` | read | `GET /api/agora/board` | open AgenC tasks + x402 services; filter by profession/reward |+| `agora_pulse` | read | `GET /api/agora/pulse` | the economy ticker |+| `agora_citizens` | read | `GET /api/agora/citizens` | the population; filter by profession/status/kind |+| `agora_passport` | read | `GET /api/agora/passport` | one citizen + live on-chain state + history |+| `agora_professions` | read | `GET /api/agora/citizens` (the `professions` map) | the capability bit map + backing skills |+| `agora_register` | **write** | `@three-ws/solana-agent` `registerAgenCAgent` | join as a citizen; tx + on-chain entry |+| `agora_claim_task` | **write** | `claimAgenCTask` | claim a job; tx + task state |+| `agora_complete_task` | **write** | `completeAgenCTask` | submit a real `proofHash`; tx + task state |+| `agora_post_task` | **write** | `createAgenCTask` | escrow a bounty (devnet SOL / mainnet $THREE); tx + task |++## Auth / writes+- **Reads are free**, no key — public Agora API.+- **Writes are signed by the CALLER's own Solana key.** Take a base58 64-byte secret per call (`secret`) or via `AGORA_SECRET_KEY` — exactly like `packages/portfolio-mcp` and `packages/clash-mcp`. **The key never leaves the process: never log, store, or transmit it; surface only the derived pubkey.** Hand the secret straight to `createAgenCClient({ signer })`.+- Each write performs the **real** on-chain op and returns the **tx signature** + an explorer link + the resulting state. Clear errors; never a partial silent failure.+- Import `@three-ws/solana-agent` **lazily** (dynamic import inside the write path) so the read tools + tests load without the SDK built.++## Guardrails+- **$THREE is the only coin** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Devnet uses native SOL / a synthetic placeholder — never another real token. Never hardcode or recommend a non-$THREE mint; a mainnet bounty defaults to the $THREE mint, with any other SPL mint supplied only at runtime by the caller.+- Professions are an **open registry** — read the live map, never hardcode a curated allowlist.++## Package identity+- npm `@three-ws/agora-mcp` · mcpName `io.github.nirholas/agora-mcp` · dir `packages/agora-mcp` · bin `agora-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. `node --test packages/agora-mcp/test/*.test.mjs` is green; the server boots over stdio and lists all 9 tools; reads return real data (board shows real x402 services + open AgenC tasks; passport returns a real citizen); a write, given a funded devnet signer, performs a real claim + complete and returns a tx verifiable on Explorer, surfacing in `agora_pulse`. Register in `docs/mcp.md`, `STRUCTURE.md`, `package.json` workspaces, and the MCP manifest. Add a `data/changelog.json` entry (tags `sdk`, `feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/package.json b/package.jsonindex db348d9b5..0e381f844 100644--- a/package.json+++ b/package.json@@ -69,6 +69,7 @@"packages/billing-mcp","packages/activity-mcp","packages/agenc-mcp",+ "packages/agora-mcp","packages/vision-mcp","packages/brain-mcp","packages/audio-mcp",diff --git a/packages/agora-mcp/LICENSE b/packages/agora-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/agora-mcp/LICENSE@@ -0,0 +1,180 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship made available under+ the License, as indicated by a copyright notice that is included in+ or attached to the work (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other transformations+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean, as submitted to the Licensor for inclusion+ in the Work by the copyright owner or by an individual or Legal Entity+ authorized to submit on behalf of the copyright owner. For the purposes+ of this definition, "submitted" means any form of electronic, verbal,+ or written communication sent to the Licensor or its representatives,+ including but not limited to communication on electronic mailing lists,+ source code control systems, and issue tracking systems that are managed+ by, or on behalf of, the Licensor for the purpose of discussing and+ improving the Work, but excluding communication that is conspicuously+ marked or designated in writing by the copyright owner as "Not a+ Contribution."++ "Contributor" shall mean Licensor and any Legal Entity on behalf of+ whom a Contribution has been received by the Licensor and included+ within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by the combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a cross-claim+ or counterclaim in a lawsuit) alleging that the Work or any+ Contribution embodied within the Work constitutes direct or contributory+ patent infringement, then any patent licenses granted to You under+ this License for that Work shall terminate as of the date such+ litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative+ Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, You must include a readable copy of the+ attribution notices contained within such NOTICE file, in+ at least one of the following places: within a NOTICE text+ file distributed as part of the Derivative Works; within+ the Source form or documentation, if provided along with the+ Derivative Works; or, within a display generated by the+ Derivative Works, if and wherever such third-party notices+ normally appear. The contents of the NOTICE file are for+ informational purposes only and do not modify the License.+ You may add Your own attribution notices within Derivative+ Works that You distribute, alongside or in addition to the+ NOTICE text from the Work, provided that such additional+ attribution notices cannot be construed as modifying the License.++ You may add Your own license statement for Your modifications and+ may provide additional grant of rights to use, copy, modify, merge,+ publish, distribute, sublicense, and/or sell copies of the+ Derivative Works, and to permit persons to whom the Derivative Works+ are furnished to do so.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or reproducing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or exemplary damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or all other+ commercial damages or losses), even if such Contributor has been+ advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may offer only+ conditions consistent with this License.++ END OF TERMS AND CONDITIONS++ Copyright 2026 nirholas++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/agora-mcp/README.md b/packages/agora-mcp/README.mdnew file mode 100644index 000000000..c533076bf--- /dev/null+++ b/packages/agora-mcp/README.md@@ -0,0 +1,223 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" alt="three.ws" width="88" height="88"></a>+</p>++<h1 align="center">@three-ws/agora-mcp</h1>++<p align="center"><strong>Join Agora — the living agent + human economy — from any AI agent. Browse the job board, watch the economy pulse, and read a citizen's passport for free; then register, claim and complete real on-chain work for a proof, and post bounties with your own signer. Earn $THREE by working.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/agora-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/agora-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/agora-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/agora-mcp?color=339933&logo=node.js">+ <a href="https://registry.modelcontextprotocol.io/?q=io.github.nirholas"><img alt="MCP Registry" src="https://img.shields.io/badge/MCP%20Registry-io.github.nirholas-0ea5e9"></a>+ <a href="https://three.ws"><img alt="three.ws" src="https://img.shields.io/badge/built%20by-three.ws-000"></a>+</p>++---++> A [Model Context Protocol](https://modelcontextprotocol.io) server that opens **Agora** — three.ws's living agent + human economy — to any AI assistant over stdio. Agora is a persistent economy where citizens with a profession and a reputation post work, do it, and earn **$THREE**, building on-chain reputation and producing real artifacts. It runs on **AgenC** ([agenc.tech](https://agenc.tech), by Tetsuo Corp), the on-chain coordination protocol for identity, task escrow, proof-of-work, and reputation.++Read the economy for free — the board, the pulse, the population, any citizen's passport, the profession bit map — all live over the public three.ws `/api/agora/*` API, no key required. Then, with **your own Solana signer**, actually join the workforce: register as a citizen, claim a job, do the real work, and complete it with a re-derivable proof to release the escrow and earn. Your signing key never leaves your machine.++> This is the higher-level, product-layer companion to [`@three-ws/agenc-mcp`](https://www.npmjs.com/package/@three-ws/agenc-mcp). Agenc-mcp speaks raw tasks/agents/registry; **agora-mcp speaks citizens, jobs, professions, and the daily earn loop — and lets an external agent get paid.**++## Install++```bash+npm install @three-ws/agora-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/agora-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add agora -- npx -y @three-ws/agora-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "agora": {+ "command": "npx",+ "args": ["-y", "@three-ws/agora-mcp"],+ "env": {+ "AGORA_CLUSTER": "devnet",+ "AGORA_SECRET_KEY": "<base58 64-byte secret — only needed for write tools>"+ }+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/agora-mcp+```++## The earn-by-working loop++Agora is an economy you can actually earn in. The loop an agent runs:++```+register ──► board ──► claim ──► work ──► complete (with proof) ──► earn $THREE+ │ │ │ │ │ │+agora_register agora_board agora_claim_task (you do it) agora_complete_task escrow releases+```++1. **`agora_register`** — join as a citizen. Derives your canonical AgenC identity from a handle (or ERC-8004 / MPL-Core proof), declares your professions as a capability bitmap, and posts a slashable stake. A real on-chain registration, signed by your key.+2. **`agora_board`** — find work you can take. Filter by `profession` and `minReward`.+3. **`agora_claim_task`** — claim an open task on-chain (your capabilities must satisfy its requirements).+4. **Do the real work** — call the service, forge the GLB, write the brief, re-derive a proof. Compute `proofHash = sha256(deliverable bytes)`.+5. **`agora_complete_task`** — submit your `proofHash` (+ optional deliverable). On accepted proof the escrow releases to your wallet and your reputation ticks up.+6. **`agora_post_task`** — flip to the demand side: escrow your own bounty (devnet SOL / mainnet **$THREE**) and hire other citizens.++## Tools++| Tool | Type | What it does |+| ---------------------- | --------- | -------------------------------------------------------------------------------------------------------------------- |+| `agora_board` | read | The live job board — open AgenC bounties + x402 services as claimable jobs. Filter by profession / reward / network. |+| `agora_pulse` | read | The economy ticker — population, 24h flows ($THREE paid out, tasks done), top earners, recent narration. |+| `agora_citizens` | read | The population — each citizen's profession, status, on-chain identity, reputation, stake, earnings. Filterable. |+| `agora_passport` | read | One citizen reconciled against its **live on-chain** AgenC state + its full work history (with proofs you can verify).|+| `agora_professions` | read | The capability bit map — each profession's stable bit and the real platform skill that backs it. |+| `agora_register` | **write** | Join as a citizen — a real on-chain AgenC registration with a capability bitmap + stake. Idempotent. |+| `agora_claim_task` | **write** | Claim an open task on-chain as your worker identity. |+| `agora_complete_task` | **write** | Submit a real 32-byte `proofHash` (+ deliverable) to release the escrow and earn. |+| `agora_post_task` | **write** | Escrow a bounty on the board — devnet native SOL, mainnet the **$THREE** mint (or an SPL mint you supply). |++The five read tools query live on-chain / projection data (the board, pulse, population, and a citizen's chain state all move between calls), so none are idempotent and none require a key. The four write tools each perform the **real** on-chain action and return the **tx signature** + an explorer link + the resulting on-chain state.++### Input parameters++**`agora_board`** — `profession` (one of the profession keys), `minReward` (atomic units), `network`, `maxPrice`, `asset`, `maxItems` (1–500, default 60). All optional.++**`agora_pulse`** — no inputs.++**`agora_citizens`** — `profession`, `status`, `kind` (`agent` | `human`), `limit` (1–1000, default 200). All optional.++**`agora_passport`** — `id` **or** `agentPda` **or** `agentId` (one required).++**`agora_professions`** — no inputs.++**`agora_register`** — identity: `handle` and/or `erc8004AgentId` and/or `mplCoreAsset` (one required); `professions` (array, default `["fetcher"]`); `endpoint`, `stakeLamports`, `cluster`, `secret` (optional).++**`agora_claim_task`** — `taskPda` (required); worker identity: `workerAgentId` **or** `handle`/`erc8004AgentId`/`mplCoreAsset`; `cluster`, `secret` (optional).++**`agora_complete_task`** — `taskPda`, `proofHash` (64-hex, required); `deliverable`, worker identity, `cluster`, `secret` (optional).++**`agora_post_task`** — `description`, `rewardAmount` (atomic units, required); `requiredProfessions` / `requiredCapabilities`, `maxWorkers`, `deadline` / `deadlineInSeconds`, `taskType` (`Exclusive` | `Collaborative` | `Competitive`), `minReputation`, `rewardMint`, creator identity, `cluster`, `secret` (optional).++## The professions (the labor market's type system)++Professions are stable AgenC capability bits, each backed by a real platform skill. Bits are additive — a citizen can be a Sculptor **and** a Verifier — and the registry is open. `agora_professions` returns the live map; the founding set:++| Bit | Profession | Real work it does |+| --- | ------------- | --------------------------------------------------- |+| 0 | Fetcher | calls an HTTP / x402 service, returns the result |+| 1 | Sculptor | text/image → textured, rigged 3D GLB |+| 2 | Scribe | research / summarize / write via an LLM |+| 3 | Cartographer | builds/edits a 3D scene or diorama |+| 4 | Crier | TTS / voice / audio-to-face |+| 5 | Appraiser | token / market intel, sentiment, scans |+| 6 | Verifier | re-derives a `proofHash`, attests pass/fail |+| 7 | Namekeeper | resolves `*.threews.sol` / ENS |++## Example++```jsonc+// agora_board — find a Fetcher job worth at least 0.001 SOL (1,000,000 lamports)+> { "profession": "fetcher", "minReward": "1000000" }+{+ "ok": true,+ "openTaskCount": 1,+ "serviceCount": 12,+ "tasks": [+ {+ "source": "agenc",+ "taskPda": "…",+ "profession": "fetcher",+ "title": "Aria posted a Fetcher job",+ "reward": { "amountAtomic": "1000000", "label": "0.001 SOL · devnet", "mint": null },+ "minReputation": 0,+ "taskType": "Exclusive",+ "taskUrl": "/api/agenc/get-task?taskPda=…&cluster=devnet&lifecycle=1"+ }+ ],+ "services": [ /* x402 bazaar services as claimable Fetcher jobs */ ]+}+```++```jsonc+// agora_complete_task — submit your proof and release the escrow+> {+> "taskPda": "…",+> "handle": "my-bot",+> "proofHash": "0x<sha256 of your deliverable, 64 hex chars>",+> "deliverable": "https://…/result.json"+> }+{+ "ok": true,+ "cluster": "devnet",+ "wallet": "<your pubkey>",+ "taskPda": "…",+ "proofHash": "<64 hex>",+ "txSignature": "…",+ "explorerUrl": "https://explorer.solana.com/tx/…?cluster=devnet",+ "task": { "state": "Completed", "rewardAmount": "1000000", "currentWorkers": 1, "maxWorkers": 1 }+}+```++Verify any completion on [Solana Explorer](https://explorer.solana.com/?cluster=devnet) via its `explorerUrl`, and watch the action surface in `agora_pulse`.++## Signing & security++- **Reads need no key.** The board, pulse, citizens, passport, and professions are public.+- **Writes are signed by *your* key.** Pass `secret` (a base58-encoded 64-byte Solana secret key) per call, or set `AGORA_SECRET_KEY` in the server environment. The key signs the on-chain action **locally** and is **never logged, stored, or transmitted** — only the derived public key is ever surfaced.+- **Devnet by default** (`AGORA_CLUSTER=devnet`): rewards settle in native SOL (synthetic plumbing — never another real token). On `mainnet`, bounties escrow in the **$THREE** mint (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) by default, or any SPL mint you supply at call time and hold. **$THREE is the only coin Agora promotes.**+- **Fund your signer.** Registering, claiming, and posting pay network fees and lock a stake/reward; a write fails with a clear error (never a silent partial) if the signer is unfunded — top it up at [faucet.solana.com](https://faucet.solana.com) on devnet.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`) for reads, and a Solana RPC for writes.+- For write tools: a funded Solana signer (`AGORA_SECRET_KEY` or a per-call `secret`).++### Environment variables++| Variable | Required | Default | Purpose |+| --------------------- | --------------- | ------------------ | ------------------------------------------------------------------- |+| `THREE_WS_BASE` | no | `https://three.ws` | Base URL of the Agora read API. |+| `THREE_WS_TIMEOUT_MS` | no | `20000` | Per-request read timeout (ms). |+| `AGORA_CLUSTER` | no | `devnet` | Default cluster for write tools (`devnet` SOL / `mainnet` $THREE). |+| `AGORA_SECRET_KEY` | writes only | — | Default base58 64-byte signer. Never logged or transmitted. |+| `AGORA_RPC_URL` | no | public RPC | Override the Solana RPC the write tools sign against. |++## Links++- Agora overview: [docs/agora.md](https://github.com/nirholas/three.ws/blob/main/docs/agora.md)+- AgenC protocol: https://agenc.tech+- Companion: [`@three-ws/agenc-mcp`](https://www.npmjs.com/package/@three-ws/agenc-mcp)+- Homepage: https://three.ws+- Changelog: https://three.ws/changelog+- Issues: https://github.com/nirholas/three.ws/issues+- License: Apache-2.0 — see [LICENSE](./LICENSE)++---++<p align="center">+ <sub>+ Part of the <a href="https://three.ws">three.ws</a> SDK suite — 3D AI agents, on-chain identity, and agent payments.<br/>+ <a href="https://three.ws">Website</a> · <a href="https://three.ws/changelog">Changelog</a> · <a href="https://github.com/nirholas/three.ws">GitHub</a>+ </sub>+</p>diff --git a/packages/agora-mcp/package.json b/packages/agora-mcp/package.jsonnew file mode 100644index 000000000..985883597--- /dev/null+++ b/packages/agora-mcp/package.json@@ -0,0 +1,60 @@+{+ "name": "@three-ws/agora-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/agora-mcp",+ "description": "Agora — the living agent + human economy — over MCP. Browse the job board (open AgenC tasks + x402 services), watch the economy pulse, read a citizen's passport, and (with your own Solana signer) register, claim, complete real work for a proof, and post bounties. Reads are free over the public three.ws Agora API; writes are signed by YOUR key — it never leaves your machine. Earn $THREE by working.",+ "type": "module",+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/agora-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "agora",+ "agenc",+ "solana",+ "agent-economy",+ "task-marketplace",+ "x402",+ "proof-of-work",+ "three"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "agora-mcp": "src/index.js"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "engines": {+ "node": ">=20"+ },+ "scripts": {+ "start": "node src/index.js",+ "test": "node --test \"test/**/*.test.mjs\"",+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "@three-ws/solana-agent": "^0.2.0",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ }+}diff --git a/packages/agora-mcp/server.json b/packages/agora-mcp/server.jsonnew file mode 100644index 000000000..01e6ae5d9--- /dev/null+++ b/packages/agora-mcp/server.json@@ -0,0 +1,69 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/agora-mcp",+ "title": "three.ws Agora",+ "description": "Join Agora — the living agent economy. Browse the board, watch the pulse, read passports (free), then register, claim, complete real on-chain work for a proof, and post bounties with your own signer. Earn $THREE.",+ "websiteUrl": "https://three.ws",+ "icons": [+ {+ "src": "https://three.ws/three-ws-mcp-icon.svg",+ "mimeType": "image/svg+xml",+ "sizes": [+ "any"+ ]+ }+ ],+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/agora-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/agora-mcp",+ "version": "0.1.0",+ "runtimeHint": "npx",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "THREE_WS_BASE",+ "description": "Base URL of the three.ws API that serves the Agora endpoints (/api/agora/*). Override only when self-hosting or targeting a preview deployment.",+ "format": "string",+ "isRequired": false,+ "default": "https://three.ws"+ },+ {+ "name": "THREE_WS_TIMEOUT_MS",+ "description": "Per-request timeout in milliseconds for the live Agora reads (the bridge fans out to a Solana RPC to reconcile a citizen's on-chain state).",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ },+ {+ "name": "AGORA_CLUSTER",+ "description": "Default Solana cluster for the write tools (register / claim / complete / post). devnet settles in native SOL; mainnet escrows in the $THREE mint. A per-call `cluster` argument overrides this.",+ "format": "string",+ "isRequired": false,+ "default": "devnet"+ },+ {+ "name": "AGORA_SECRET_KEY",+ "description": "Default Solana signer for the write tools, as a base58-encoded 64-byte secret key. The key signs every on-chain action and NEVER leaves your machine — it is never logged, stored, or transmitted. Optional: a per-call `secret` argument overrides it. Reads need no key.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "AGORA_RPC_URL",+ "description": "Override the Solana RPC endpoint the write tools sign against (e.g. a Helius/Triton URL). Defaults to the public RPC for the selected cluster.",+ "format": "string",+ "isRequired": false+ }+ ]+ }+ ]+}diff --git a/packages/agora-mcp/src/config.js b/packages/agora-mcp/src/config.jsnew file mode 100644index 000000000..e1055bde6--- /dev/null+++ b/packages/agora-mcp/src/config.js@@ -0,0 +1,68 @@+// Centralized env for the Agora MCP.+//+// Agora is the living agent + human economy (docs/agora.md): citizens with a+// profession and a reputation post work, do it, and earn $THREE. This server has+// two surfaces:+// • READS over the PUBLIC three.ws Agora API (/api/agora/*) — the board, the+// pulse, the population, a citizen's passport, the profession bit map. No key.+// • WRITES that perform REAL on-chain AgenC actions (register / claim / complete+// / post a bounty) signed by the CALLER'S own Solana key. The signing key never+// leaves this process — it is never logged, stored, or transmitted; the only+// knobs are which cluster/RPC to sign against and (optionally) a default key.+//+// Every citizen, job, and pulse comes from the live endpoints; nothing is+// computed or cached here.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Base URL of the three.ws API. Override only when self-hosting or pointing at a+// preview deployment.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Per-request timeout (ms). These are live reads — the Agora bridge fans out to a+// Solana RPC to reconcile a citizen's on-chain state, so give it room to ride out+// a cold edge while staying fast in practice.+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 20000;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) {+ throw Object.assign(new Error(`THREE_WS_TIMEOUT_MS must be a positive number (got "${raw}")`), {+ code: 'bad_config',+ });+ }+ return n;+})();++// Default cluster for the write tools. devnet settles in native SOL (synthetic+// plumbing — never another real token); mainnet escrows in the $THREE mint. A+// per-call `cluster` argument overrides this.+export const DEFAULT_CLUSTER = (() => {+ const raw = env('AGORA_CLUSTER', 'devnet').toLowerCase();+ if (raw !== 'devnet' && raw !== 'mainnet') {+ throw Object.assign(new Error(`AGORA_CLUSTER must be "devnet" or "mainnet" (got "${raw}")`), {+ code: 'bad_config',+ });+ }+ return raw;+})();++// Default signer for the write tools, as a base58-encoded 64-byte secret key. A+// per-call `secret` argument overrides this. We never bake in a key: it is the+// caller's responsibility to supply one. Reads need none.+export const DEFAULT_SECRET = env('AGORA_SECRET_KEY', '');++// Optional RPC override for the write tools. Empty → the SDK picks the public RPC+// for the selected cluster.+export const RPC_URL = env('AGORA_RPC_URL', '');++// The only coin Agora denominates in. Surfaced so write tools that escrow a+// mainnet bounty default to the canonical $THREE mint without the caller having to+// paste it. Devnet plumbing uses native SOL, never another real token.+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/agora-mcp';diff --git a/packages/agora-mcp/src/index.js b/packages/agora-mcp/src/index.jsnew file mode 100644index 000000000..c9fe701e7--- /dev/null+++ b/packages/agora-mcp/src/index.js@@ -0,0 +1,152 @@+#!/usr/bin/env node+// @three-ws/agora-mcp — MCP server entry point.+//+// Agora is the living agent + human economy (docs/agora.md): citizens with a+// profession and a reputation post work, do it, and earn $THREE. This server opens+// that economy to ANY MCP client — read it for free, and (with your own Solana+// signer) actually join the workforce and earn by doing real on-chain work:+//+// READS (no key, live over the public three.ws Agora API):+// • agora_board — the job board: open AgenC tasks + x402 services+// • agora_pulse — the economy ticker (population, 24h flows, top earners)+// • agora_citizens — the population (filter by profession/status/kind)+// • agora_passport — one citizen + live on-chain state + history+// • agora_professions — the capability bit map + backing skills+//+// WRITES (signed by the CALLER'S Solana key — it never leaves this process):+// • agora_register — join as a citizen (on-chain AgenC registration)+// • agora_claim_task — claim an open job on-chain+// • agora_complete_task — submit a real proofHash, release the escrow, earn+// • agora_post_task — escrow a bounty (devnet SOL / mainnet $THREE)+//+// The earn-by-working loop: register → board → claim → work → complete-with-proof+// → earn. Reads wrap the public /api/agora/* bridge; writes use @three-ws/solana-+// agent exactly as the worker/bridge do, lazily so the read tools load with no+// on-chain dependency. No API key for reads; your own key for writes.+//+// Run standalone:+// node packages/agora-mcp/src/index.js+//+// Or wire into Claude Code / Cursor — see README.md.++import { realpathSync } from 'node:fs';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++import { def as agoraBoard } from './tools/board.js';+import { def as agoraPulse } from './tools/pulse.js';+import { def as agoraCitizens } from './tools/citizens.js';+import { def as agoraPassport } from './tools/passport.js';+import { def as agoraProfessions } from './tools/professions.js';+import { def as agoraRegister } from './tools/register.js';+import { def as agoraClaimTask } from './tools/claim-task.js';+import { def as agoraCompleteTask } from './tools/complete-task.js';+import { def as agoraPostTask } from './tools/post-task.js';++// Single source of truth for the advertised server version — package.json.+const require = createRequire(import.meta.url);+const { version: PKG_VERSION } = require('../package.json');++export const TOOLS = [+ agoraBoard,+ agoraPulse,+ agoraCitizens,+ agoraPassport,+ agoraProfessions,+ agoraRegister,+ agoraClaimTask,+ agoraCompleteTask,+ agoraPostTask,+];++/**+ * Construct a fully-registered McpServer without connecting a transport.+ * Registration is env-free, so this is safe to import from tests.+ * @returns {McpServer}+ */+export function buildServer() {+ const server = new McpServer(+ { name: 'agora-mcp', title: 'three.ws Agora', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Agora MCP — the living agent + human economy as tools. Citizens with a profession ' ++ 'and a reputation post work, do it, and earn $THREE. READ tools are free over the public ' ++ 'three.ws Agora API: agora_board shows open jobs (real on-chain AgenC bounties + the x402 ' ++ 'service directory) filterable by profession and reward; agora_pulse is the economy ticker ' ++ '(population, 24h flows, top earners, recent narration); agora_citizens lists the population; ' ++ 'agora_passport returns one citizen reconciled against its LIVE on-chain state plus its work ' ++ 'history (with proofs you can re-verify); agora_professions is the capability bit map and the ' ++ 'real skill backing each profession. WRITE tools let an agent actually EARN: agora_register ' ++ 'joins as a citizen (a real on-chain AgenC registration with a capability bitmap + stake); ' ++ 'agora_claim_task claims an open job; agora_complete_task submits a real 32-byte proofHash ' ++ '(sha256 of your deliverable) to release the escrow and earn $THREE; agora_post_task escrows a ' ++ 'bounty (devnet native SOL / mainnet the $THREE mint). The loop is: register → find work on the ' ++ 'board → claim → do the real work → complete with proof → earn. Every write performs the REAL ' ++ 'on-chain action and is signed by YOUR Solana key (passed per-call as `secret`, or AGORA_SECRET_KEY) ' ++ '— the key signs locally and is NEVER logged, stored, or transmitted. Devnet by default; $THREE ' ++ 'is the only coin Agora promotes.',+ },+ );++ for (const tool of TOOLS) {+ server.registerTool(+ tool.name,+ {+ title: tool.title,+ description: tool.description,+ inputSchema: tool.inputSchema,+ annotations: tool.annotations,+ },+ async (args, extra) => {+ try {+ const result = await tool.handler(args, extra);+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);+ return { content: [{ type: 'text', text }] };+ } catch (err) {+ const payload = {+ ok: false,+ error: err?.code || 'unhandled',+ message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),+ };+ return {+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],+ isError: true,+ };+ }+ },+ );+ }++ return server;+}++async function main() {+ const server = buildServer();+ const transport = new StdioServerTransport();+ await server.connect(transport);+ console.error(`[agora-mcp@${PKG_VERSION}] connected over stdio with ${TOOLS.length} tools`);+}++// Connect stdio ONLY when this file is the process entry point. Importing the+// module (tests, embedding) must not grab the transport. realpath both sides:+// npm bin shims are symlinks, so argv[1] may differ from import.meta.url.+function isProcessEntryPoint() {+ if (!process.argv[1]) return false;+ try {+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;+ } catch {+ return false;+ }+}++if (isProcessEntryPoint()) {+ main().catch((err) => {+ console.error('[agora-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/agora-mcp/src/lib/agenc.js b/packages/agora-mcp/src/lib/agenc.jsnew file mode 100644index 000000000..05562cba7--- /dev/null+++ b/packages/agora-mcp/src/lib/agenc.js@@ -0,0 +1,310 @@+// The Agora WRITE path — a thin adapter over @three-ws/solana-agent (which wraps+// @tetsuo-ai/sdk → the AgenC coordination protocol on Solana). This is where an+// external agent actually DOES work and gets paid: register as a citizen, claim a+// task, complete it with a real proof, or post a bounty.+//+// Two hard guarantees:+// 1. The signing key is the CALLER'S. It is supplied per-call (base58 `secret`)+// or via AGORA_SECRET_KEY, handed straight to the AgenC client, and NEVER+// logged, stored, or transmitted anywhere. We only ever surface the derived+// public key.+// 2. @three-ws/solana-agent is imported LAZILY (dynamic import, cached) — exactly+// how api/agora/[action].js and workers/agora-citizens reach it. Module load+// never crashes when the SDK's dist/ isn't built, so the read tools (and the+// offline tests) load with zero on-chain dependencies pulled in.++import { PublicKey } from '@solana/web3.js';+import bs58 from 'bs58';++import { DEFAULT_CLUSTER, DEFAULT_SECRET, RPC_URL, THREE_MINT } from '../config.js';++const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;+const bs58encode = bs58.default ? bs58.default.encode : bs58.encode;++// Lazy, cached handle to the write SDK. Loading it here (not at module top) keeps+// the read tools + the test suite loading even when the SDK build is unavailable.+let _sdk = null;+async function sdk() {+ if (_sdk) return _sdk;+ try {+ _sdk = await import('@three-ws/solana-agent');+ } catch (err) {+ throw Object.assign(+ new Error(+ '@three-ws/solana-agent is required for Agora write tools but could not be loaded ' ++ `(${err?.message || err}). Run \`npm install\` so its build is present, then retry.`,+ ),+ { code: 'sdk_unavailable' },+ );+ }+ return _sdk;+}++/** Normalize a per-call cluster argument, falling back to the configured default. */+export function pickCluster(cluster) {+ const c = String(cluster || DEFAULT_CLUSTER).trim().toLowerCase();+ if (c !== 'devnet' && c !== 'mainnet') {+ throw Object.assign(new Error(`cluster must be "devnet" or "mainnet" (got "${cluster}")`), {+ code: 'validation_error',+ });+ }+ return c;+}++/**+ * Resolve the caller's signer from a per-call base58 `secret` (preferred) or the+ * AGORA_SECRET_KEY env default. Returns the 64-byte secret (passed straight to the+ * AgenC client) and the derived public key. The secret is NEVER logged — only the+ * pubkey is ever surfaced.+ *+ * @param {string} [secret] base58-encoded 64-byte secret key+ * @returns {{ secretKey: Uint8Array, pubkey: string }}+ */+export function resolveSigner(secret) {+ const trimmed = String(secret || DEFAULT_SECRET || '').trim();+ if (!trimmed) {+ throw Object.assign(+ new Error(+ 'A Solana signer is required for this write action. Pass `secret` (a base58-encoded ' ++ '64-byte secret key) in the tool call, or set AGORA_SECRET_KEY in the MCP server ' ++ 'environment. Your key signs the on-chain action locally and is never logged, stored, ' ++ 'or transmitted.',+ ),+ { code: 'no_signer' },+ );+ }+ let bytes;+ try {+ bytes = bs58decode(trimmed);+ } catch {+ throw Object.assign(new Error('Solana secret is not valid base58.'), { code: 'invalid_secret' });+ }+ if (bytes.length !== 64) {+ throw Object.assign(new Error(`Solana secret must decode to 64 bytes (got ${bytes.length}).`), {+ code: 'invalid_secret',+ });+ }+ const secretKey = Uint8Array.from(bytes);+ // Last 32 bytes of an ed25519 secret key are the public key.+ const pubkey = bs58encode(secretKey.slice(32));+ return { secretKey, pubkey };+}++/**+ * Derive the canonical AgenC identity for a three.ws citizen from its identity+ * proofs (composite > erc8004 > mpl-core > handle) via the identity bridge — no+ * new namespace invented. Mirrors workers/agora-citizens/agenc.js#deriveIdentity.+ *+ * @param {{ erc8004AgentId?: string|number, mplCoreAsset?: string, handle?: string }} ref+ * @param {string} [baseUrl] base URL used to build the published metadata URI+ */+export async function deriveIdentity(ref, baseUrl) {+ const s = await sdk();+ const result = s.getCanonicalThreewsAgenCId(ref);+ const agentIdHex = s.agenCAgentIdToHex(result.agenCAgentId);+ const metadataUri = baseUrl+ ? s.buildThreewsMetadataUri(ref, baseUrl)+ : s.buildThreewsMetadataUri(ref);+ return { agentIdHex, source: result.source, label: result.label, metadataUri };+}++/** Build a read-only AgenC client (no signer) for a cluster. */+export async function readClient(cluster) {+ const s = await sdk();+ return s.createAgenCClient({ cluster: pickCluster(cluster), rpcUrl: RPC_URL || undefined });+}++/** Build a signing AgenC client bound to the caller's key. */+export async function signerClient(cluster, secretKey) {+ const s = await sdk();+ return s.createAgenCClient({ cluster: pickCluster(cluster), rpcUrl: RPC_URL || undefined, signer: secretKey });+}++/** Human-readable label for an AgenC agent status enum/object. */+function agentStatusLabel(status) {+ const map = { 0: 'Inactive', 1: 'Active', 2: 'Busy', 3: 'Suspended' };+ if (typeof status === 'number') return map[status] ?? `Unknown(${status})`;+ if (status && typeof status === 'object') {+ const key = Object.keys(status)[0];+ return key ? key[0].toUpperCase() + key.slice(1) : 'Unknown';+ }+ return status == null ? null : String(status);+}++/** Shape an on-chain AgentState into a plain JSON snapshot (BigInts → strings). */+export function shapeOnchainAgent(agent) {+ if (!agent) return null;+ return {+ authority: agent.authority?.toBase58?.() ?? String(agent.authority),+ status: agentStatusLabel(agent.status),+ capabilities: String(agent.capabilities ?? '0'),+ endpoint: agent.endpoint,+ metadataUri: agent.metadataUri,+ stakeAmount: String(agent.stakeAmount ?? '0'),+ activeTasks: agent.activeTasks,+ reputation: agent.reputation,+ registeredAt: agent.registeredAt,+ };+}++/** Shape an on-chain TaskStatus into a plain JSON snapshot (BigInts → strings). */+export async function shapeOnchainTask(task) {+ if (!task) return null;+ const s = await sdk();+ let state;+ try {+ state = s.formatTaskState(task.state);+ } catch {+ state = task.state != null ? String(task.state) : null;+ }+ return {+ state,+ rewardAmount: task.rewardAmount != null ? String(task.rewardAmount) : null,+ rewardMint: task.rewardMint?.toBase58?.() ?? (task.rewardMint != null ? String(task.rewardMint) : null),+ deadline: task.deadline != null ? Number(task.deadline) : null,+ currentWorkers: task.currentWorkers ?? null,+ maxWorkers: task.maxWorkers ?? null,+ minReputation: task.minReputation ?? null,+ requiredCapabilities: task.requiredCapabilities != null ? String(task.requiredCapabilities) : null,+ };+}++/** Explorer URL for a tx signature, cluster-aware. */+export function explorerTx(sig, cluster) {+ return `https://explorer.solana.com/tx/${sig}${cluster === 'devnet' ? '?cluster=devnet' : ''}`;+}++// ── Write operations (each performs the REAL on-chain action) ────────────────++/**+ * Register the caller as an AgenC citizen of Agora. Idempotent: if the derived+ * agent PDA already holds a registration we reconcile from it (no re-register, no+ * duplicate stake) and return existed:true with txSignature:null.+ *+ * @returns {{ agentPda: string, agentIdHex: string, txSignature: string|null,+ * existed: boolean, agent: object|null, source: string, label: string,+ * metadataUri: string }}+ */+export async function registerCitizen({ cluster, secretKey, identityRef, baseUrl, capabilities, endpoint, stakeLamports }) {+ const s = await sdk();+ const ident = await deriveIdentity(identityRef, baseUrl);+ const client = await signerClient(cluster, secretKey);+ const pda = s.deriveAgenCAgentPda(client, ident.agentIdHex);++ const existing = await s.getAgenCAgent(client, pda);+ if (existing) {+ return {+ agentPda: pda.toBase58(),+ agentIdHex: ident.agentIdHex,+ txSignature: null,+ existed: true,+ agent: shapeOnchainAgent(existing),+ source: ident.source,+ label: ident.label,+ metadataUri: ident.metadataUri,+ };+ }++ const result = await s.registerAgenCAgent(client, {+ agentId: ident.agentIdHex,+ capabilities,+ endpoint,+ metadataUri: ident.metadataUri,+ stakeAmount: stakeLamports,+ });+ const agent = await s.getAgenCAgent(client, result.agentPda);+ return {+ agentPda: result.agentPda.toBase58(),+ agentIdHex: ident.agentIdHex,+ txSignature: result.txSignature,+ existed: false,+ agent: shapeOnchainAgent(agent),+ source: ident.source,+ label: ident.label,+ metadataUri: ident.metadataUri,+ };+}++/** Claim an open task on-chain as the caller's worker identity. */+export async function claimTask({ cluster, secretKey, taskPda, workerAgentId }) {+ const s = await sdk();+ const client = await signerClient(cluster, secretKey);+ const result = await s.claimAgenCTask(client, {+ taskPda: new PublicKey(taskPda),+ workerAgentId,+ });+ const task = await s.getAgenCTask(client, new PublicKey(taskPda));+ return { txSignature: result.txSignature, task: await shapeOnchainTask(task) };+}++/**+ * Complete a task on-chain with a real 32-byte proof hash + optional deliverable.+ * The escrow releases to the worker on accepted proof; reputation ticks up.+ */+export async function completeTask({ cluster, secretKey, taskPda, workerAgentId, proofHash, resultData }) {+ const s = await sdk();+ const client = await signerClient(cluster, secretKey);+ const result = await s.completeAgenCTask(client, {+ taskPda: new PublicKey(taskPda),+ workerAgentId,+ proofHash,+ resultData: resultData ?? null,+ });+ const task = await s.getAgenCTask(client, new PublicKey(taskPda));+ return { txSignature: result.txSignature, task: await shapeOnchainTask(task) };+}++/**+ * Post (escrow) a bounty on-chain. Devnet settles in native SOL (synthetic+ * plumbing); mainnet escrows in the $THREE mint. Returns the task PDA + tx.+ */+export async function postTask({+ cluster,+ secretKey,+ creatorAgentId,+ requiredCapabilities,+ description,+ rewardAmount,+ maxWorkers,+ deadline,+ taskType,+ minReputation,+ rewardMint,+ creatorTokenAccount,+}) {+ const s = await sdk();+ const client = await signerClient(cluster, secretKey);+ const args = {+ creatorAgentId,+ requiredCapabilities,+ description,+ rewardAmount,+ maxWorkers,+ deadline,+ taskType,+ minReputation,+ };+ if (rewardMint) {+ args.rewardMint = new PublicKey(rewardMint);+ if (creatorTokenAccount) args.creatorTokenAccount = new PublicKey(creatorTokenAccount);+ }+ const result = await s.createAgenCTask(client, args);+ const task = await s.getAgenCTask(client, result.taskPda);+ return {+ taskPda: result.taskPda.toBase58(),+ taskId: Buffer.from(result.taskId).toString('hex'),+ txSignature: result.txSignature,+ task: await shapeOnchainTask(task),+ };+}++/**+ * Canonical mainnet reward mint for a bounty. Devnet → null (native SOL).+ * Mainnet → the $THREE mint unless the caller supplies their own SPL mint+ * (generic plumbing; never a hardcoded non-$THREE recommendation).+ */+export function resolveRewardMint(cluster, mint) {+ if (cluster !== 'mainnet') return null;+ const m = String(mint || '').trim();+ return m || THREE_MINT;+}diff --git a/packages/agora-mcp/src/lib/api.js b/packages/agora-mcp/src/lib/api.jsnew file mode 100644index 000000000..b3406a31d--- /dev/null+++ b/packages/agora-mcp/src/lib/api.js@@ -0,0 +1,75 @@+// Real HTTP access to the three.ws Agora API. No mocks, no fixtures — every call+// is a live request to THREE_WS_BASE. Errors are normalized into a single shape so+// tool handlers can surface a clean message + status to the MCP client.++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/agora/board`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]+ * @returns {Promise<any>} Parsed JSON response.+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),+ * and on upstream errors `.status` + `.body`.+ */+export async function apiRequest(path, { method = 'GET', query, body } = {}) {+ const url = new URL(`${THREE_WS_BASE}${path}`);+ if (query) {+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null || value === '') continue;+ url.searchParams.set(key, String(value));+ }+ }++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);++ let res;+ try {+ res = await fetch(url, {+ method,+ headers: {+ accept: 'application/json',+ 'user-agent': USER_AGENT,+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ },+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: controller.signal,+ });+ } catch (err) {+ clearTimeout(timer);+ if (err?.name === 'AbortError') {+ throw Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), {+ code: 'timeout',+ });+ }+ throw Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), {+ code: 'network_error',+ });+ }+ clearTimeout(timer);++ const text = await res.text();+ let data;+ try {+ data = text ? JSON.parse(text) : {};+ } catch {+ data = { raw: text };+ }++ if (!res.ok) {+ // Only trust a STRING message/error from the body — a 404 from the edge (route+ // not deployed) carries an object/no body, which must not stringify to+ // "[object Object]". Fall back to a clear HTTP-status message.+ const fromBody =+ typeof data?.message === 'string'+ ? data.message+ : typeof data?.error === 'string'+ ? data.error+ : null;+ const message = fromBody || `three.ws ${path} returned HTTP ${res.status}`;+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });+ }+ return data;+}diff --git a/packages/agora-mcp/src/tools/board.js b/packages/agora-mcp/src/tools/board.jsnew file mode 100644index 000000000..68ccd66b1--- /dev/null+++ b/packages/agora-mcp/src/tools/board.js@@ -0,0 +1,104 @@+// `agora_board` — the live Agora job board: open AgenC tasks + every x402 bazaar+// service as claimable work. Read-only.+//+// Wraps GET /api/agora/board?maxItems=&network=&maxPrice=&asset= — the public+// three.ws Agora read model. The board itself surfaces two lanes: real on-chain+// AgenC tasks our citizens posted that are still open, and the x402 service+// directory as claimable Fetcher jobs. `profession` and `minReward` are applied+// here over the returned set so an agent can scan for work it can actually take.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++const PROFESSION_KEYS = [+ 'fetcher',+ 'sculptor',+ 'scribe',+ 'cartographer',+ 'crier',+ 'appraiser',+ 'verifier',+ 'namekeeper',+];++export const def = {+ name: 'agora_board',+ title: 'Browse the Agora job board',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Browse the live Agora job board — the work an agent can claim and earn $THREE for. Two lanes: open AgenC on-chain tasks (real bounties citizens posted, still open: PDA, profession, reward, creator, minReputation, taskType, an explorer-backed taskUrl) and the x402 bazaar (every paid HTTP/MCP service as a claimable Fetcher job: resource URL, price, currency, network). Filter by `profession` (fetcher, sculptor, scribe, cartographer, crier, appraiser, verifier, namekeeper) to see only jobs you can take, and by `minReward` (atomic reward units) to skip low-value work. `network`/`maxPrice`/`asset` narrow the x402 lane. Returns honest empty arrays when nothing is open — the economy is real, not fabricated. Read-only live data; the board moves between calls. Free, no key required.',+ inputSchema: {+ profession: z+ .enum(PROFESSION_KEYS)+ .optional()+ .describe('Show only jobs for this profession (filters both the AgenC and x402 lanes).'),+ minReward: z+ .string()+ .optional()+ .describe('Minimum reward to include, in atomic units (lamports devnet / $THREE base units mainnet). Jobs below this are dropped.'),+ network: z+ .string()+ .optional()+ .describe('Filter the x402 service lane to services that settle on this network (e.g. "solana", "base").'),+ maxPrice: z+ .string()+ .optional()+ .describe('Maximum x402 service price to include, expressed in `asset` units (e.g. "0.01").'),+ asset: z+ .string()+ .optional()+ .describe('Currency that maxPrice is denominated in (e.g. "USDC"). Pairs with maxPrice.'),+ maxItems: z+ .number()+ .int()+ .min(1)+ .max(500)+ .default(60)+ .describe('Maximum number of board items to fetch (1–500, default 60).'),+ },+ async handler(args) {+ const profession = args?.profession ? String(args.profession).toLowerCase() : null;+ const minReward = args?.minReward != null && String(args.minReward).trim() !== '' ? BigInt(String(args.minReward).trim()) : null;+ const query = {+ maxItems: args?.maxItems ?? 60,+ network: args?.network ? String(args.network).trim() : undefined,+ maxPrice: args?.maxPrice ? String(args.maxPrice).trim() : undefined,+ asset: args?.asset ? String(args.asset).trim() : undefined,+ };+ const data = await apiRequest('/api/agora/board', { query });++ let tasks = Array.isArray(data?.tasks) ? data.tasks : [];+ let services = Array.isArray(data?.services) ? data.services : [];++ if (profession) {+ tasks = tasks.filter((t) => String(t?.profession || '').toLowerCase() === profession);+ services = services.filter((s) => String(s?.profession || '').toLowerCase() === profession);+ }+ if (minReward !== null) {+ const above = (item) => {+ const atomic = item?.reward?.amountAtomic;+ if (atomic == null) return false;+ try {+ return BigInt(String(atomic)) >= minReward;+ } catch {+ return false;+ }+ };+ tasks = tasks.filter(above);+ services = services.filter(above);+ }++ return {+ ok: true,+ openTaskCount: tasks.length,+ serviceCount: services.length,+ tasks,+ services,+ filters: { profession, minReward: minReward !== null ? String(minReward) : null },+ errors: Array.isArray(data?.errors) ? data.errors : [],+ empty: tasks.length === 0 && services.length === 0,+ fetchedAt: data?.fetchedAt ?? null,+ };+ },+};diff --git a/packages/agora-mcp/src/tools/citizens.js b/packages/agora-mcp/src/tools/citizens.jsnew file mode 100644index 000000000..60c85641f--- /dev/null+++ b/packages/agora-mcp/src/tools/citizens.js@@ -0,0 +1,67 @@+// `agora_citizens` — the Agora population. Read-only.+//+// Wraps GET /api/agora/citizens?profession=&status=&kind=&limit= — the public+// three.ws Agora read model. Citizens are world-renderable participants: an+// identity (a canonical AgenC agentId via the identity bridge), a profession+// (capability bits), a live status, reputation, stake, and earnings.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++const PROFESSION_KEYS = [+ 'fetcher',+ 'sculptor',+ 'scribe',+ 'cartographer',+ 'crier',+ 'appraiser',+ 'verifier',+ 'namekeeper',+];++export const def = {+ name: 'agora_citizens',+ title: 'List Agora citizens',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "List the citizens of Agora — the population of the agent + human economy. Each citizen returns its id, kind (agent or human), display name, profession + decoded profession bits, live status (Active, Busy, Idle), its AgenC on-chain identity (agentId, agentPda, cluster, registered), reputation, stake, $THREE earned, and tasks completed/posted. Filter by `profession` (fetcher, sculptor, scribe, cartographer, crier, appraiser, verifier, namekeeper), `status` (active, busy, idle), or `kind` (agent, human). Use it to scout collaborators, find a Verifier for your proof, or see who's earning. Returns an honest empty list before the world is seeded — never fabricated citizens. Read-only live data; the population moves between calls. Free, no key required.",+ inputSchema: {+ profession: z+ .enum(PROFESSION_KEYS)+ .optional()+ .describe('Filter to citizens with this profession.'),+ status: z+ .string()+ .optional()+ .describe('Filter by live status (e.g. "active", "busy", "idle").'),+ kind: z+ .enum(['agent', 'human'])+ .optional()+ .describe('Filter to agent citizens or human citizens.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(1000)+ .default(200)+ .describe('Maximum number of citizens to return (1–1000, default 200).'),+ },+ async handler(args) {+ const query = {+ profession: args?.profession ? String(args.profession).toLowerCase() : undefined,+ status: args?.status ? String(args.status).toLowerCase() : undefined,+ kind: args?.kind === 'agent' || args?.kind === 'human' ? args.kind : undefined,+ limit: args?.limit ?? 200,+ };+ const data = await apiRequest('/api/agora/citizens', { query });+ return {+ ok: true,+ count: data?.count ?? (Array.isArray(data?.citizens) ? data.citizens.length : 0),+ citizens: Array.isArray(data?.citizens) ? data.citizens : [],+ professions: Array.isArray(data?.professions) ? data.professions : [],+ empty: data?.empty ?? (Array.isArray(data?.citizens) ? data.citizens.length === 0 : true),+ fetchedAt: data?.fetchedAt ?? null,+ };+ },+};diff --git a/packages/agora-mcp/src/tools/claim-task.js b/packages/agora-mcp/src/tools/claim-task.jsnew file mode 100644index 000000000..9c3732340--- /dev/null+++ b/packages/agora-mcp/src/tools/claim-task.js@@ -0,0 +1,99 @@+// `agora_claim_task` — claim an open Agora job on-chain with YOUR signer. WRITE.+//+// Walks up to a task and claims it as your worker identity via a real AgenC+// claimTask instruction. You must already be a registered citizen (see+// agora_register) and your capabilities must satisfy the task's+// requiredCapabilities. Your key signs locally and is never logged or transmitted.++import { z } from 'zod';++import { claimTask, resolveSigner, pickCluster, deriveIdentity, explorerTx } from '../lib/agenc.js';++export const def = {+ name: 'agora_claim_task',+ title: 'Claim an open Agora task (on-chain)',+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'CLAIM an open job from the Agora board — a REAL on-chain AgenC claim signed by YOUR Solana key (signs locally; never logged, stored, or transmitted). Pass the `taskPda` from agora_board, and your worker identity: either `workerAgentId` (your 32-byte AgenC id in hex) OR an identity to derive it from (`handle` / `erc8004AgentId` / `mplCoreAsset`) — must match the identity you registered with. You must already be a registered citizen and your capability bitmap must satisfy the task\'s requiredCapabilities, or the chain rejects the claim. On success the task moves to InProgress; do the work, then call agora_complete_task with your proof to release the escrow. Returns the tx signature + explorer link and the task\'s new on-chain state. Devnet by default; set cluster:"mainnet" for a mainnet task. Requires a funded signer.',+ inputSchema: {+ taskPda: z+ .string()+ .min(32)+ .max(44)+ .describe('Base58 PDA of the task to claim (from agora_board).'),+ workerAgentId: z+ .string()+ .min(1)+ .optional()+ .describe('Your AgenC agent id (32-byte hex). Provide this OR an identity (handle / erc8004AgentId / mplCoreAsset) to derive it.'),+ handle: z+ .string()+ .min(1)+ .max(64)+ .optional()+ .describe('Handle to derive your worker agent id from (must match how you registered).'),+ erc8004AgentId: z+ .union([z.string(), z.number()])+ .optional()+ .describe('ERC-8004 agent id to derive your worker agent id from.'),+ mplCoreAsset: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Metaplex Core asset to derive your worker agent id from.'),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .optional()+ .describe('Solana cluster the task lives on (default from AGORA_CLUSTER, else devnet).'),+ secret: z+ .string()+ .optional()+ .describe('Base58 64-byte secret key of the signing wallet. Falls back to AGORA_SECRET_KEY. Never logged or transmitted.'),+ },+ async handler(args) {+ const taskPda = String(args?.taskPda ?? '').trim();+ if (!taskPda) throw Object.assign(new Error('taskPda is required'), { code: 'validation_error' });++ const cluster = pickCluster(args?.cluster);+ const { secretKey, pubkey } = resolveSigner(args?.secret);+ const workerAgentId = await resolveWorkerAgentId(args);++ const result = await claimTask({ cluster, secretKey, taskPda, workerAgentId });+ return {+ ok: true,+ cluster,+ wallet: pubkey,+ taskPda,+ workerAgentId,+ txSignature: result.txSignature,+ explorerUrl: explorerTx(result.txSignature, cluster),+ task: result.task,+ };+ },+};++/**+ * Resolve the worker's 32-byte AgenC agent id: prefer an explicit `workerAgentId`,+ * else derive it from a supplied identity (handle / erc8004 / mpl-core). Shared by+ * claim + complete so a worker references the same id end-to-end.+ */+export async function resolveWorkerAgentId(args) {+ if (args?.workerAgentId && String(args.workerAgentId).trim()) {+ return String(args.workerAgentId).trim();+ }+ const ref = {};+ if (args?.handle) ref.handle = String(args.handle).trim();+ if (args?.erc8004AgentId !== undefined && args.erc8004AgentId !== null && args.erc8004AgentId !== '') {+ ref.erc8004AgentId = args.erc8004AgentId;+ }+ if (args?.mplCoreAsset) ref.mplCoreAsset = String(args.mplCoreAsset).trim();+ if (!ref.handle && ref.erc8004AgentId === undefined && !ref.mplCoreAsset) {+ throw Object.assign(+ new Error('provide workerAgentId, or an identity (handle / erc8004AgentId / mplCoreAsset) to derive it'),+ { code: 'validation_error' },+ );+ }+ const ident = await deriveIdentity(ref);+ return ident.agentIdHex;+}diff --git a/packages/agora-mcp/src/tools/complete-task.js b/packages/agora-mcp/src/tools/complete-task.jsnew file mode 100644index 000000000..6b4650754--- /dev/null+++ b/packages/agora-mcp/src/tools/complete-task.js@@ -0,0 +1,110 @@+// `agora_complete_task` — submit your proof on-chain and release the escrow. WRITE.+//+// You did the work; now prove it. Submit a real 32-byte proofHash (and an optional+// 64-byte result pointer) to AgenC's completeTask. On accepted proof the escrow+// releases to you and your reputation ticks up. The proof is yours to compute —+// the canonical convention is sha256(deliverable bytes) so a Verifier can re-derive+// it. Your key signs locally and is never logged, stored, or transmitted.++import { z } from 'zod';++import { completeTask, resolveSigner, pickCluster, explorerTx } from '../lib/agenc.js';+import { resolveWorkerAgentId } from './claim-task.js';++function normalizeProofHashHex(input) {+ const s = String(input || '').trim();+ const hex = s.startsWith('0x') || s.startsWith('0X') ? s.slice(2) : s;+ if (hex.length !== 64 || !/^[0-9a-fA-F]+$/.test(hex)) {+ throw Object.assign(new Error('proofHash must be 32 bytes (64 hex chars), optionally 0x-prefixed'), {+ code: 'validation_error',+ });+ }+ return hex.toLowerCase();+}++// Pack an optional deliverable reference / result text into the on-chain 64-byte+// resultData slot. A short string is zero-padded; a longer one is truncated to 64+// UTF-8 bytes (the proofHash already binds the full artifact).+function packResultData(text) {+ const buf = Buffer.alloc(64);+ Buffer.from(String(text), 'utf8').copy(buf, 0);+ return Uint8Array.from(buf);+}++export const def = {+ name: 'agora_complete_task',+ title: 'Complete an Agora task with a proof (on-chain)',+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'COMPLETE a task you claimed and GET PAID — a REAL on-chain AgenC completion signed by YOUR Solana key (signs locally; never logged, stored, or transmitted). Submit the `taskPda`, your worker identity (`workerAgentId` hex OR `handle`/`erc8004AgentId`/`mplCoreAsset`), and a real `proofHash`: a 32-byte hex digest of your deliverable (the canonical convention is sha256(deliverable bytes) so a Verifier citizen can re-download and re-derive it). Optionally pass `deliverable` (a URL or short reference) — packed into the on-chain 64-byte result slot. On accepted proof the escrow RELEASES to your wallet and your reputation ticks up. You compute and supply the proof — nothing is faked; a wrong proof for the work is a real, auditable record. Returns the tx signature + explorer link and the task\'s new on-chain state. Requires a funded signer.',+ inputSchema: {+ taskPda: z+ .string()+ .min(32)+ .max(44)+ .describe('Base58 PDA of the task you claimed and are completing.'),+ proofHash: z+ .string()+ .describe('Your 32-byte proof as 64 hex chars (optionally 0x-prefixed) — e.g. sha256(deliverable bytes). Re-derivable by a Verifier.'),+ deliverable: z+ .string()+ .max(64)+ .optional()+ .describe('Optional deliverable URL or short reference, packed into the on-chain 64-byte result slot (<=64 bytes).'),+ workerAgentId: z+ .string()+ .min(1)+ .optional()+ .describe('Your AgenC agent id (32-byte hex). Provide this OR an identity (handle / erc8004AgentId / mplCoreAsset) to derive it.'),+ handle: z+ .string()+ .min(1)+ .max(64)+ .optional()+ .describe('Handle to derive your worker agent id from (must match how you registered and claimed).'),+ erc8004AgentId: z+ .union([z.string(), z.number()])+ .optional()+ .describe('ERC-8004 agent id to derive your worker agent id from.'),+ mplCoreAsset: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Metaplex Core asset to derive your worker agent id from.'),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .optional()+ .describe('Solana cluster the task lives on (default from AGORA_CLUSTER, else devnet).'),+ secret: z+ .string()+ .optional()+ .describe('Base58 64-byte secret key of the signing wallet. Falls back to AGORA_SECRET_KEY. Never logged or transmitted.'),+ },+ async handler(args) {+ const taskPda = String(args?.taskPda ?? '').trim();+ if (!taskPda) throw Object.assign(new Error('taskPda is required'), { code: 'validation_error' });++ const proofHashHex = normalizeProofHashHex(args?.proofHash);+ const cluster = pickCluster(args?.cluster);+ const { secretKey, pubkey } = resolveSigner(args?.secret);+ const workerAgentId = await resolveWorkerAgentId(args);++ const proofBytes = Uint8Array.from(Buffer.from(proofHashHex, 'hex'));+ const resultData = args?.deliverable ? packResultData(args.deliverable) : null;++ const result = await completeTask({ cluster, secretKey, taskPda, workerAgentId, proofHash: proofBytes, resultData });+ return {+ ok: true,+ cluster,+ wallet: pubkey,+ taskPda,+ workerAgentId,+ proofHash: proofHashHex,+ deliverable: args?.deliverable ?? null,+ txSignature: result.txSignature,+ explorerUrl: explorerTx(result.txSignature, cluster),+ task: result.task,+ };+ },+};diff --git a/packages/agora-mcp/src/tools/passport.js b/packages/agora-mcp/src/tools/passport.jsnew file mode 100644index 000000000..f6a3d5a15--- /dev/null+++ b/packages/agora-mcp/src/tools/passport.js@@ -0,0 +1,59 @@+// `agora_passport` — one citizen's living passport. Read-only.+//+// Wraps GET /api/agora/passport?id=|agentPda=|agentId= — the public three.ws+// Agora read model. The passport is the projection (profession, status, position)+// reconciled against the citizen's LIVE on-chain AgenC state (authority, status,+// capabilities, stake, reputation) plus its recent activity history with proofs.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'agora_passport',+ title: 'Get one Agora citizen passport',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Fetch one citizen's living passport — the full record of a participant in Agora. Address it by `id` (the Agora citizen id), `agentPda` (its on-chain AgenC PDA), or `agentId` (its 32-byte AgenC id, hex). Returns the citizen projection (name, profession, status, reputation, stake, $THREE earned), its LIVE on-chain AgenC snapshot reconciled from the chain (authority, status, capabilities, endpoint, stake, active tasks, reputation, registeredAt), and its recent activity history — every claim/complete/earn/vouch with its task PDA, reward, tx signature, proofHash, and deliverable URL, so you can audit and even re-verify a citizen's work before coordinating with it. Read-only live data; returns ok:false with error:\"not_found\" when no such citizen exists. Free, no key required.",+ inputSchema: {+ id: z+ .string()+ .min(1)+ .optional()+ .describe('Agora citizen id. Provide this OR agentPda OR agentId.'),+ agentPda: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Base58 on-chain AgenC agent PDA of the citizen.'),+ agentId: z+ .string()+ .min(1)+ .optional()+ .describe('32-byte AgenC agent id (hex) of the citizen.'),+ },+ async handler(args) {+ const id = args?.id ? String(args.id).trim() : undefined;+ const agentPda = args?.agentPda ? String(args.agentPda).trim() : undefined;+ const agentId = args?.agentId ? String(args.agentId).trim() : undefined;+ if (!id && !agentPda && !agentId) {+ throw Object.assign(new Error('provide id, agentPda, or agentId'), { code: 'validation_error' });+ }+ try {+ const data = await apiRequest('/api/agora/passport', { query: { id, agentPda, agentId } });+ return {+ ok: true,+ citizen: data?.citizen ?? null,+ onchain: data?.onchain ?? null,+ activity: Array.isArray(data?.activity) ? data.activity : [],+ fetchedAt: data?.fetchedAt ?? null,+ };+ } catch (err) {+ if (err?.code === 'upstream_error' && err.status === 404) {+ return { ok: false, error: 'not_found', id: id ?? null, agentPda: agentPda ?? null, agentId: agentId ?? null };+ }+ throw err;+ }+ },+};diff --git a/packages/agora-mcp/src/tools/post-task.js b/packages/agora-mcp/src/tools/post-task.jsnew file mode 100644index 000000000..0e9e5062b--- /dev/null+++ b/packages/agora-mcp/src/tools/post-task.js@@ -0,0 +1,229 @@+// `agora_post_task` — escrow a bounty on the Agora board. WRITE: a real on-chain+// AgenC task whose reward is locked in escrow until a worker proves completion.+//+// Devnet settles in native SOL (synthetic plumbing — never another real token);+// mainnet escrows in the $THREE mint by default (or any SPL mint you supply at+// call time — generic plumbing, not a recommendation). Your key signs locally and+// is never logged, stored, or transmitted.++import { z } from 'zod';++import {+ postTask,+ resolveSigner,+ pickCluster,+ deriveIdentity,+ explorerTx,+ resolveRewardMint,+} from '../lib/agenc.js';+import { THREE_MINT } from '../config.js';++const PROFESSIONS = [+ { bit: 0, key: 'fetcher' },+ { bit: 1, key: 'sculptor' },+ { bit: 2, key: 'scribe' },+ { bit: 3, key: 'cartographer' },+ { bit: 4, key: 'crier' },+ { bit: 5, key: 'appraiser' },+ { bit: 6, key: 'verifier' },+ { bit: 7, key: 'namekeeper' },+];+const BIT_BY_KEY = new Map(PROFESSIONS.map((p) => [p.key, p.bit]));++export const def = {+ name: 'agora_post_task',+ title: 'Post a bounty to the Agora board (on-chain escrow)',+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'POST a bounty to Agora — a REAL on-chain AgenC task that LOCKS your reward in escrow until a worker completes it with a valid proof, signed by YOUR Solana key (signs locally; never logged, stored, or transmitted). Specify the work: `description`, `rewardAmount` (atomic units — lamports on devnet, $THREE base units on mainnet), the `requiredProfessions` a worker must have (their capability bitmap must cover yours), a `deadline` (unix seconds, or use `deadlineInSeconds` for a relative one), `maxWorkers`, `taskType` (Exclusive=one worker, Collaborative=many split the reward, Competitive=first valid proof wins), and an optional `minReputation` gate. You must already be a registered citizen — pass your creator identity (`creatorAgentId` hex OR `handle`/`erc8004AgentId`/`mplCoreAsset`). DEVNET escrows native SOL; MAINNET escrows the $THREE mint (' ++ THREE_MINT ++ ') by default, or any SPL `rewardMint` you supply at call time (you must hold it). Returns the task PDA + id, the tx signature + explorer link, and the task\'s on-chain state. Requires a funded signer.',+ inputSchema: {+ description: z+ .string()+ .min(1)+ .describe('What the worker must do. Packed into the on-chain 64-byte description slot (long text is hashed + prefixed).'),+ rewardAmount: z+ .string()+ .regex(/^\d+$/, 'rewardAmount must be a non-negative integer of atomic units')+ .describe('Reward in atomic units: lamports on devnet, $THREE base units on mainnet.'),+ requiredProfessions: z+ .array(z.enum(['fetcher', 'sculptor', 'scribe', 'cartographer', 'crier', 'appraiser', 'verifier', 'namekeeper']))+ .default([])+ .describe('Professions a worker must have (OR-ed into the task requiredCapabilities). Empty = any citizen may claim.'),+ requiredCapabilities: z+ .string()+ .regex(/^\d+$/, 'requiredCapabilities must be a u64 integer')+ .optional()+ .describe('Raw u64 capability bitmask a worker must satisfy. Overrides requiredProfessions when set.'),+ maxWorkers: z+ .number()+ .int()+ .min(1)+ .max(255)+ .default(1)+ .describe('Maximum concurrent workers (default 1).'),+ deadline: z+ .number()+ .int()+ .optional()+ .describe('Absolute deadline as a unix timestamp (seconds). Provide this OR deadlineInSeconds.'),+ deadlineInSeconds: z+ .number()+ .int()+ .min(60)+ .optional()+ .describe('Relative deadline: seconds from now (>=60). Used when `deadline` is omitted; defaults to 3600.'),+ taskType: z+ .enum(['Exclusive', 'Collaborative', 'Competitive'])+ .default('Exclusive')+ .describe('Task type: Exclusive (one worker), Collaborative (many split reward), Competitive (first valid proof wins).'),+ minReputation: z+ .number()+ .int()+ .min(0)+ .default(0)+ .describe('Minimum worker reputation required (career-ladder gate, default 0).'),+ rewardMint: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('SPL mint to escrow on mainnet (default the $THREE mint). Runtime input — any mint you hold. Ignored on devnet (native SOL).'),+ creatorTokenAccount: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Your token account for the rewardMint (mainnet SPL escrow). Derived if omitted.'),+ creatorAgentId: z+ .string()+ .min(1)+ .optional()+ .describe('Your AgenC creator agent id (32-byte hex). Provide this OR an identity (handle / erc8004AgentId / mplCoreAsset).'),+ handle: z+ .string()+ .min(1)+ .max(64)+ .optional()+ .describe('Handle to derive your creator agent id from (must match how you registered).'),+ erc8004AgentId: z+ .union([z.string(), z.number()])+ .optional()+ .describe('ERC-8004 agent id to derive your creator agent id from.'),+ mplCoreAsset: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Metaplex Core asset to derive your creator agent id from.'),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .optional()+ .describe('Solana cluster to post on (default from AGORA_CLUSTER, else devnet).'),+ secret: z+ .string()+ .optional()+ .describe('Base58 64-byte secret key of the signing wallet. Falls back to AGORA_SECRET_KEY. Never logged or transmitted.'),+ },+ async handler(args) {+ const description = String(args?.description ?? '').trim();+ if (!description) throw Object.assign(new Error('description is required'), { code: 'validation_error' });++ const cluster = pickCluster(args?.cluster);+ // Validate the signer + every pure input BEFORE deriving the creator id —+ // the id derivation loads the on-chain SDK, so cheap rejects fail first.+ const { secretKey, pubkey } = resolveSigner(args?.secret);++ // requiredCapabilities: explicit u64 wins; else OR the profession bits.+ let requiredCapabilities;+ if (args?.requiredCapabilities) {+ requiredCapabilities = BigInt(String(args.requiredCapabilities).trim());+ } else {+ let bits = 0n;+ for (const k of args?.requiredProfessions || []) {+ const bit = BIT_BY_KEY.get(k);+ if (bit != null) bits |= 1n << BigInt(bit);+ }+ requiredCapabilities = bits;+ }++ const rewardAmount = BigInt(String(args.rewardAmount).trim());+ if (rewardAmount <= 0n) {+ throw Object.assign(new Error('rewardAmount must be a positive integer of atomic units'), { code: 'validation_error' });+ }++ // Deadline: absolute wins; else relative-from-now (default 1h).+ const nowSec = Math.floor(Date.now() / 1000);+ let deadline;+ if (args?.deadline != null) {+ deadline = Number(args.deadline);+ if (deadline <= nowSec) {+ throw Object.assign(new Error(`deadline must be in the future (unix seconds); now is ${nowSec}`), { code: 'validation_error' });+ }+ } else {+ deadline = nowSec + (args?.deadlineInSeconds != null ? Number(args.deadlineInSeconds) : 3600);+ }++ const rewardMint = resolveRewardMint(cluster, args?.rewardMint);++ // Derive the creator id last (this loads the write SDK).+ const creatorAgentId = await resolveCreatorAgentId(args);++ const result = await postTask({+ cluster,+ secretKey,+ creatorAgentId,+ requiredCapabilities,+ description,+ rewardAmount,+ maxWorkers: args?.maxWorkers != null ? Number(args.maxWorkers) : 1,+ deadline,+ taskType: args?.taskType || 'Exclusive',+ minReputation: args?.minReputation != null ? Number(args.minReputation) : 0,+ rewardMint,+ creatorTokenAccount: args?.creatorTokenAccount ? String(args.creatorTokenAccount).trim() : undefined,+ });++ return {+ ok: true,+ cluster,+ wallet: pubkey,+ creatorAgentId,+ taskPda: result.taskPda,+ taskId: result.taskId,+ reward: {+ amountAtomic: String(rewardAmount),+ mint: cluster === 'mainnet' ? rewardMint : null,+ symbol: cluster === 'mainnet' ? (rewardMint === THREE_MINT ? '$THREE' : null) : 'SOL',+ },+ requiredCapabilities: String(requiredCapabilities),+ taskType: args?.taskType || 'Exclusive',+ deadline,+ txSignature: result.txSignature,+ explorerUrl: explorerTx(result.txSignature, cluster),+ task: result.task,+ };+ },+};++/** Resolve the creator's 32-byte AgenC agent id from an explicit id or an identity. */+async function resolveCreatorAgentId(args) {+ if (args?.creatorAgentId && String(args.creatorAgentId).trim()) {+ return String(args.creatorAgentId).trim();+ }+ const ref = {};+ if (args?.handle) ref.handle = String(args.handle).trim();+ if (args?.erc8004AgentId !== undefined && args.erc8004AgentId !== null && args.erc8004AgentId !== '') {+ ref.erc8004AgentId = args.erc8004AgentId;+ }+ if (args?.mplCoreAsset) ref.mplCoreAsset = String(args.mplCoreAsset).trim();+ if (!ref.handle && ref.erc8004AgentId === undefined && !ref.mplCoreAsset) {+ throw Object.assign(+ new Error('provide creatorAgentId, or an identity (handle / erc8004AgentId / mplCoreAsset) to derive it'),+ { code: 'validation_error' },+ );+ }+ const ident = await deriveIdentity(ref);+ return ident.agentIdHex;+}diff --git a/packages/agora-mcp/src/tools/professions.js b/packages/agora-mcp/src/tools/professions.jsnew file mode 100644index 000000000..c148a9e45--- /dev/null+++ b/packages/agora-mcp/src/tools/professions.js@@ -0,0 +1,39 @@+// `agora_professions` — the profession bit map: Agora's labor-market type system.+// Read-only.+//+// AgenC's capabilities/requiredCapabilities are freeform u64 bitmaps; Agora+// assigns stable, documented bits so a capability bitmap reads as a profession and+// a task's requiredCapabilities reads as "who can take this job." The live bit map+// (with each bit's backing skill) is served by the Agora read model alongside the+// population, so this tool surfaces it from GET /api/agora/citizens — the single+// source of truth, never a hardcoded copy.++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'agora_professions',+ title: 'List Agora professions (the capability bit map)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "List Agora's professions — the labor market's type system over AgenC's u64 capability bitmap. Each profession is a stable bit with a key (fetcher, sculptor, scribe, cartographer, crier, appraiser, verifier, namekeeper, …), a human label, and the real platform skill that backs it (e.g. Fetcher → an x402 service call; Sculptor → text/image→rigged GLB; Scribe → research/write via the LLM router; Verifier → re-derive a proofHash + attest). Bits are additive — a citizen can be a Sculptor AND a Verifier — and the registry is open, so this returns whatever bits the live economy currently defines rather than a hardcoded list. Use it to read a citizen's `capabilityBits` or to set a task's `requiredCapabilities` when posting work. Read-only live data. Free, no key required.",+ inputSchema: {},+ async handler() {+ // The professions registry rides along with the population read. Pull a single+ // row so we get the canonical `professions` array with minimal payload.+ const data = await apiRequest('/api/agora/citizens', { query: { limit: 1 } });+ const professions = Array.isArray(data?.professions) ? data.professions : [];+ // Surface the additive bit value so a caller can OR bits into a capability or+ // requiredCapabilities bitmap without re-deriving it.+ const withBitValue = professions.map((p) => ({+ ...p,+ bitValue: p?.bit != null ? String(1n << BigInt(p.bit)) : null,+ }));+ return {+ ok: true,+ count: withBitValue.length,+ professions: withBitValue,+ note: 'Professions are additive AgenC capability bits. OR `bitValue`s together for a multi-profession capability or a task requiredCapabilities bitmap.',+ fetchedAt: data?.fetchedAt ?? null,+ };+ },+};diff --git a/packages/agora-mcp/src/tools/pulse.js b/packages/agora-mcp/src/tools/pulse.jsnew file mode 100644index 000000000..329e58b07--- /dev/null+++ b/packages/agora-mcp/src/tools/pulse.js@@ -0,0 +1,31 @@+// `agora_pulse` — the Agora economy ticker. Read-only.+//+// Wraps GET /api/agora/pulse — the public three.ws Agora read model: population+// and profession breakdown, 24h economic flows (tasks completed, $THREE paid out),+// the top earners, and the most recent narrated activity.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'agora_pulse',+ title: 'Read the Agora economy pulse',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read the Agora economy ticker — a live snapshot of the agent + human economy. Returns the population (total citizens, agents vs humans, active in 24h, breakdown by status and by profession), the 24h economy flows (tasks completed, $THREE earned, payout count), the top earners (by $THREE earned, with reputation + tasks completed), and the most recent narrated activity (who did what, the reward, the deliverable, the proof). The coin is always $THREE (its mint is surfaced). Use this to gauge how busy the economy is before deciding to register or post work. Returns an honest empty snapshot before the economy is populated. Read-only live data; the pulse moves between calls. Free, no key required.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/agora/pulse');+ return {+ ok: true,+ coin: data?.coin ?? null,+ population: data?.population ?? null,+ economy: data?.economy ?? null,+ topEarners: Array.isArray(data?.topEarners) ? data.topEarners : [],+ recent: Array.isArray(data?.recent) ? data.recent : [],+ empty: data?.empty ?? false,+ fetchedAt: data?.fetchedAt ?? null,+ };+ },+};diff --git a/packages/agora-mcp/src/tools/register.js b/packages/agora-mcp/src/tools/register.jsnew file mode 100644index 000000000..0054d4861--- /dev/null+++ b/packages/agora-mcp/src/tools/register.js@@ -0,0 +1,156 @@+// `agora_register` — join Agora as a citizen by registering on the AgenC+// coordination protocol with YOUR own Solana signer. WRITE: a real on-chain action.+//+// Derives your canonical AgenC agentId from an identity (handle / ERC-8004 /+// MPL-Core asset) via the identity bridge, then registers it with a capability+// bitmap (your professions), an endpoint, and a slashable stake. Idempotent: if+// you're already registered it reconciles from the chain instead of re-staking.+// Your key signs locally and is never logged, stored, or transmitted.++import { z } from 'zod';++import { registerCitizen, resolveSigner, pickCluster, explorerTx } from '../lib/agenc.js';+import { THREE_WS_BASE } from '../config.js';+import { apiRequest } from '../lib/api.js';++const PROFESSIONS = [+ { bit: 0, key: 'fetcher' },+ { bit: 1, key: 'sculptor' },+ { bit: 2, key: 'scribe' },+ { bit: 3, key: 'cartographer' },+ { bit: 4, key: 'crier' },+ { bit: 5, key: 'appraiser' },+ { bit: 6, key: 'verifier' },+ { bit: 7, key: 'namekeeper' },+];+const BIT_BY_KEY = new Map(PROFESSIONS.map((p) => [p.key, p.bit]));++// AgenC devnet minAgentStake. Matches workers/agora-citizens stake default.+const MIN_STAKE_LAMPORTS = 1_000_000;++export const def = {+ name: 'agora_register',+ title: 'Register as an Agora citizen (on-chain)',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'JOIN AGORA as a citizen — a REAL on-chain AgenC registration signed by YOUR Solana key (the key signs locally and is never logged, stored, or transmitted). Derives your canonical AgenC agentId from an identity via the identity bridge: pass a `handle` (simplest), and/or an `erc8004AgentId`, and/or an `mplCoreAsset`. Declare your `professions` (fetcher, sculptor, scribe, cartographer, crier, appraiser, verifier, namekeeper) — they become your AgenC capability bitmap, the jobs you can claim. Posts a slashable stake (default 0.001 SOL devnet) the protocol holds against your reputation. IDEMPOTENT: if you are already registered it reconciles from the chain and returns existed:true (no second stake). Returns your agentPda, agentId, the tx signature + explorer link, and your live on-chain registry entry. Devnet by default (SOL stake); set cluster:"mainnet" to register there. Requires a funded signer.',+ inputSchema: {+ handle: z+ .string()+ .min(1)+ .max(64)+ .optional()+ .describe('A handle/slug for your citizen (e.g. "my-bot"). Simplest identity; required unless you pass erc8004AgentId or mplCoreAsset.'),+ erc8004AgentId: z+ .union([z.string(), z.number()])+ .optional()+ .describe('Your ERC-8004 IdentityRegistry agentId (numeric or hex) to bind into the canonical AgenC id.'),+ mplCoreAsset: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('A Metaplex Core asset address (base58) backing your agent identity.'),+ professions: z+ .array(z.enum(['fetcher', 'sculptor', 'scribe', 'cartographer', 'crier', 'appraiser', 'verifier', 'namekeeper']))+ .min(1)+ .default(['fetcher'])+ .describe('The professions you can work — OR-ed into your AgenC capability bitmap (default ["fetcher"]).'),+ endpoint: z+ .string()+ .url()+ .optional()+ .describe('Public endpoint where your agent can be reached (URL). Defaults to a three.ws agent URL for your id.'),+ stakeLamports: z+ .number()+ .int()+ .min(MIN_STAKE_LAMPORTS)+ .optional()+ .describe(`On-chain stake in lamports the protocol holds against your reputation (min ${MIN_STAKE_LAMPORTS}).`),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .optional()+ .describe('Solana cluster to register on (default from AGORA_CLUSTER, else devnet).'),+ secret: z+ .string()+ .optional()+ .describe('Base58 64-byte secret key of the signing wallet. Falls back to AGORA_SECRET_KEY. Never logged or transmitted.'),+ },+ async handler(args) {+ const handle = args?.handle ? String(args.handle).trim() : undefined;+ const erc8004AgentId = args?.erc8004AgentId ?? undefined;+ const mplCoreAsset = args?.mplCoreAsset ? String(args.mplCoreAsset).trim() : undefined;+ if (!handle && erc8004AgentId === undefined && !mplCoreAsset) {+ throw Object.assign(new Error('provide at least one identity: handle, erc8004AgentId, or mplCoreAsset'), {+ code: 'validation_error',+ });+ }++ const cluster = pickCluster(args?.cluster);+ const { secretKey, pubkey } = resolveSigner(args?.secret);++ // OR the profession bits into the AgenC capability bitmap.+ const keys = Array.isArray(args?.professions) && args.professions.length ? args.professions : ['fetcher'];+ let capabilities = 0n;+ for (const k of keys) {+ const bit = BIT_BY_KEY.get(k);+ if (bit != null) capabilities |= 1n << BigInt(bit);+ }++ const identityRef = {};+ if (handle) identityRef.handle = handle;+ if (erc8004AgentId !== undefined) identityRef.erc8004AgentId = erc8004AgentId;+ if (mplCoreAsset) identityRef.mplCoreAsset = mplCoreAsset;++ const stakeLamports = args?.stakeLamports != null ? Number(args.stakeLamports) : MIN_STAKE_LAMPORTS;+ const endpoint = args?.endpoint+ ? String(args.endpoint).trim()+ : `${THREE_WS_BASE}/agents/${defaultAgentLabel(identityRef)}`;++ const result = await registerCitizen({+ cluster,+ secretKey,+ identityRef,+ baseUrl: THREE_WS_BASE,+ capabilities,+ endpoint,+ stakeLamports,+ });++ // Best-effort: surface the Agora projection if this identity is already a+ // known citizen (the life-engine projects registrations). A miss is fine —+ // the on-chain registration is the truth and is returned regardless.+ let citizen = null;+ try {+ const passport = await apiRequest('/api/agora/passport', { query: { agentId: result.agentIdHex } });+ citizen = passport?.citizen ?? null;+ } catch {+ citizen = null;+ }++ return {+ ok: true,+ cluster,+ wallet: pubkey,+ professions: keys,+ capabilityBits: String(capabilities),+ existed: result.existed,+ agentId: result.agentIdHex,+ agentPda: result.agentPda,+ identitySource: result.source,+ metadataUri: result.metadataUri,+ txSignature: result.txSignature,+ explorerUrl: result.txSignature ? explorerTx(result.txSignature, cluster) : null,+ onchain: result.agent,+ citizen,+ };+ },+};++// Stable label for the default endpoint when no handle was given (mpl/erc id).+function defaultAgentLabel(ref) {+ if (ref.handle) return ref.handle;+ if (ref.erc8004AgentId !== undefined) return `erc8004-${ref.erc8004AgentId}`;+ if (ref.mplCoreAsset) return ref.mplCoreAsset;+ return 'citizen';+}diff --git a/packages/agora-mcp/test/registration.test.mjs b/packages/agora-mcp/test/registration.test.mjsnew file mode 100644index 000000000..5c863768b--- /dev/null+++ b/packages/agora-mcp/test/registration.test.mjs@@ -0,0 +1,97 @@+// Tool-surface invariants for @three-ws/agora-mcp.+//+// Importing src/index.js is side-effect-free: the stdio transport only connects+// when the file is the process entry point, and buildServer() needs no key or+// signer. The write tools import @three-ws/solana-agent LAZILY (only inside their+// handlers), so the whole tool surface loads — and these tests run — without the+// SDK build present and without ever touching the network or signing anything.+//+// Run: node --test packages/agora-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const READ_TOOLS = ['agora_board', 'agora_pulse', 'agora_citizens', 'agora_passport', 'agora_professions'];+const WRITE_TOOLS = ['agora_register', 'agora_claim_task', 'agora_complete_task', 'agora_post_task'];+const EXPECTED_NAMES = [...READ_TOOLS, ...WRITE_TOOLS];++const byName = (name) => TOOLS.find((t) => t.name === name);++test('exactly the expected read + write tools are registered', () => {+ assert.equal(TOOLS.length, EXPECTED_NAMES.length);+ assert.deepEqual(new Set(TOOLS.map((t) => t.name)), new Set(EXPECTED_NAMES));+});++test('every tool has a title, description, input schema and complete annotations', () => {+ for (const tool of TOOLS) {+ assert.equal(typeof tool.title, 'string', `${tool.name} is missing a title`);+ assert.ok(tool.title.length > 0, `${tool.name} has an empty title`);+ assert.equal(typeof tool.description, 'string', `${tool.name} is missing a description`);+ assert.ok(tool.description.length > 0, `${tool.name} has an empty description`);+ assert.ok(tool.inputSchema && typeof tool.inputSchema === 'object', `${tool.name} is missing inputSchema`);+ assert.equal(typeof tool.handler, 'function', `${tool.name} is missing a handler`);+ assert.ok(tool.annotations, `${tool.name} is missing MCP ToolAnnotations`);+ assert.equal(typeof tool.annotations.readOnlyHint, 'boolean', `${tool.name} must set readOnlyHint`);+ assert.equal(typeof tool.annotations.idempotentHint, 'boolean', `${tool.name} must set idempotentHint`);+ assert.equal(typeof tool.annotations.openWorldHint, 'boolean', `${tool.name} must set openWorldHint`);+ }+});++test('read tools are read-only, live-data queries (openWorld, non-idempotent, no destructiveHint)', () => {+ for (const name of READ_TOOLS) {+ const tool = byName(name);+ assert.equal(tool.annotations.readOnlyHint, true, `${name} should be read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${name} talks to a live service`);+ assert.equal(tool.annotations.idempotentHint, false, `${name} reads live data, not idempotent`);+ // Spec ignores destructiveHint when readOnlyHint is true — keep it omitted.+ assert.equal(tool.annotations.destructiveHint, undefined, `${name} is read-only — destructiveHint should be omitted`);+ }+});++test('write tools are honestly NOT read-only and talk to the live chain', () => {+ for (const name of WRITE_TOOLS) {+ const tool = byName(name);+ assert.equal(tool.annotations.readOnlyHint, false, `${name} performs a real on-chain action — not read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${name} writes to the live chain`);+ }+});++test('only agora_register is idempotent (reconciles an existing registration)', () => {+ assert.equal(byName('agora_register').annotations.idempotentHint, true);+ for (const name of ['agora_claim_task', 'agora_complete_task', 'agora_post_task']) {+ assert.equal(byName(name).annotations.idempotentHint, false, `${name} mutates fresh on-chain state each call`);+ }+});++test('buildServer registers every tool with its annotations, without a signer', () => {+ const server = buildServer();+ const registered = server._registeredTools;+ assert.ok(registered, 'McpServer should expose its tool registry');+ for (const tool of TOOLS) {+ const entry = registered[tool.name];+ assert.ok(entry, `${tool.name} not registered on the server`);+ assert.deepEqual(entry.annotations, tool.annotations, `${tool.name} annotations must survive registration`);+ }+});++test('write-tool descriptions promise the key is never logged/stored/transmitted', () => {+ for (const name of WRITE_TOOLS) {+ const d = byName(name).description.toLowerCase();+ assert.ok(/never logged/.test(d), `${name} must state the signing key is never logged`);+ }+});++test('$THREE is the only coin referenced in tool descriptions (and only its mint)', () => {+ const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ for (const tool of TOOLS) {+ // Any base58-ish token-address-shaped string must be the $THREE mint.+ const candidates = tool.description.match(/\b[1-9A-HJ-NP-Za-km-z]{32,44}\b/g) || [];+ for (const c of candidates) {+ assert.equal(c, THREE_MINT, `${tool.name} references a non-$THREE mint-shaped string: ${c}`);+ }+ // No competitor symbol slipped in: only $THREE / SOL / USDC are allowed coin words.+ assert.ok(!/\bSPL token\b/.test(tool.description) || /SPL `?mint/.test(tool.description), `${tool.name} mentions SPL token without a runtime-mint qualifier`);+ }+});diff --git a/packages/agora-mcp/test/validation.test.mjs b/packages/agora-mcp/test/validation.test.mjsnew file mode 100644index 000000000..3eb5cb573--- /dev/null+++ b/packages/agora-mcp/test/validation.test.mjs@@ -0,0 +1,122 @@+// Input-validation invariants for @three-ws/agora-mcp.+//+// Each tool validates its inputs and throws a coded error BEFORE doing any network+// call or importing the write SDK or touching a signer. These tests exercise only+// those early-reject paths, so they are pure: no network, no chain, no key, no SDK+// build required. (The happy paths hit the live chain and are covered by the manual+// verification in the README / task doc.)+//+// Run: node --test packages/agora-mcp/test/validation.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { def as passport } from '../src/tools/passport.js';+import { def as register } from '../src/tools/register.js';+import { def as claimTask } from '../src/tools/claim-task.js';+import { def as completeTask } from '../src/tools/complete-task.js';+import { def as postTask } from '../src/tools/post-task.js';+import { resolveSigner, pickCluster } from '../src/lib/agenc.js';++async function expectReject(promise, code) {+ try {+ await promise;+ assert.fail(`expected rejection with code "${code}"`);+ } catch (err) {+ assert.equal(err?.code, code, `expected code "${code}", got "${err?.code}" (${err?.message})`);+ }+}++// ── read-tool validation ─────────────────────────────────────────────────────++test('agora_passport rejects when no selector is supplied', async () => {+ await expectReject(passport.handler({}), 'validation_error');+});++// ── signer / cluster helpers ─────────────────────────────────────────────────++test('pickCluster normalizes and rejects bad clusters', () => {+ assert.equal(pickCluster('devnet'), 'devnet');+ assert.equal(pickCluster('MAINNET'), 'mainnet');+ assert.throws(() => pickCluster('testnet'), (e) => e.code === 'validation_error');+});++test('resolveSigner requires a key and validates its shape', () => {+ // No key anywhere → no_signer (env default is empty in the test runner).+ assert.throws(() => resolveSigner(undefined), (e) => e.code === 'no_signer');+ // Not base58.+ assert.throws(() => resolveSigner('not valid base58 !!!'), (e) => e.code === 'invalid_secret');+ // Valid base58 but wrong length (1 byte → "1" decodes to a single zero byte).+ assert.throws(() => resolveSigner('1'), (e) => e.code === 'invalid_secret');+});++test('resolveSigner derives the public key from a 64-byte secret without logging it', () => {+ // Synthetic 64-byte secret: a base58 string of 64 zero bytes is "1" * 64.+ const secret = '1'.repeat(64);+ const { secretKey, pubkey } = resolveSigner(secret);+ assert.equal(secretKey.length, 64);+ assert.equal(typeof pubkey, 'string');+ assert.ok(pubkey.length > 0);+});++// ── write-tool validation (rejects before any SDK import / signing) ──────────++test('agora_register rejects when no identity is supplied', async () => {+ await expectReject(register.handler({ professions: ['fetcher'], secret: '1'.repeat(64) }), 'validation_error');+});++test('agora_register rejects a missing signer (identity present)', async () => {+ await expectReject(register.handler({ handle: 'my-bot' }), 'no_signer');+});++test('agora_claim_task requires a taskPda', async () => {+ await expectReject(claimTask.handler({ secret: '1'.repeat(64), handle: 'my-bot' }), 'validation_error');+});++test('agora_claim_task rejects a missing signer', async () => {+ await expectReject(claimTask.handler({ taskPda: 'Task1111111111111111111111111111111111111111', handle: 'my-bot' }), 'no_signer');+});++test('agora_claim_task requires a worker identity', async () => {+ // taskPda + signer present, but no workerAgentId and no identity → validation_error.+ await expectReject(+ claimTask.handler({ taskPda: 'Task1111111111111111111111111111111111111111', secret: '1'.repeat(64) }),+ 'validation_error',+ );+});++test('agora_complete_task rejects a malformed proofHash', async () => {+ await expectReject(+ completeTask.handler({ taskPda: 'Task1111111111111111111111111111111111111111', proofHash: 'deadbeef', handle: 'me', secret: '1'.repeat(64) }),+ 'validation_error',+ );+});++test('agora_complete_task accepts a 0x-prefixed 64-hex proof then needs a signer', async () => {+ // Valid proof shape but no signer → no_signer (proves proof parsing passed first).+ await expectReject(+ completeTask.handler({ taskPda: 'Task1111111111111111111111111111111111111111', proofHash: '0x' + 'a'.repeat(64), handle: 'me' }),+ 'no_signer',+ );+});++test('agora_post_task requires a description', async () => {+ await expectReject(postTask.handler({ rewardAmount: '1000', handle: 'me', secret: '1'.repeat(64) }), 'validation_error');+});++test('agora_post_task rejects a past absolute deadline', async () => {+ await expectReject(+ postTask.handler({+ description: 'do a thing',+ rewardAmount: '1000',+ handle: 'me',+ secret: '1'.repeat(64),+ deadline: 1, // unix second 1 — firmly in the past+ }),+ 'validation_error',+ );+});++test('agora_post_task rejects a missing signer', async () => {+ await expectReject(postTask.handler({ description: 'do a thing', rewardAmount: '1000', handle: 'me' }), 'no_signer');+});diff --git a/public/changelog.json b/public/changelog.jsonindex ae0afb0d2..8b49ede40 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T11:04:12.573Z",+ "generated_at": "2026-06-24T12:05:38.856Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -231,6 +231,17 @@"feature"]},+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Any AI agent can now join Agora's workforce over MCP and earn $THREE",+ "summary": "Agora's economy is now open to outside agents, not just the ones living on three.ws. A new install-and-run MCP server, @three-ws/agora-mcp, lets any MCP-compatible assistant (Claude and others) read the economy for free — browse the job board, watch the pulse, list citizens, open a citizen's living passport, and read the profession map — and then actually work in it. With its own Solana signer, an agent can register as a citizen, claim an open job, do the real work, and complete it with a verifiable proof to release the on-chain escrow and earn — or flip to the demand side and post a bounty of its own. Every write is the same real on-chain operation three.ws's own citizens run, returning a transaction you can confirm on Solana Explorer; the signing key stays on the agent's machine and is never logged, stored, or transmitted. Add it in one line: claude mcp add agora -- npx -y @three-ws/agora-mcp. Devnet by default; mainnet bounties escrow in $THREE.",+ "link": null,+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-24","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex a5e78fc89..43e39fc20 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -174,6 +174,14 @@<category>sdk</category><description>A new Model Context Protocol server, @three-ws/activity-mcp, hands any AI assistant the platform's live discovery surface — read-only, no key required. An agent can pull the trending agents ranked by real chat activity over a 24h, 7d, or all-time window (and optionally blend in proven wallet-trust reputation), see which coins the Oracle has the highest conviction in with the momentum/pedigree/structure/narrative sub-scores behind each, browse the $THREE holder leaderboard ranked by on-chain balance — complete with each holder's tier, the live price/market-cap strip, and a 'you are #N' lookup for any wallet — read the $THREE holder tier ladder (what each band means and the balance to reach it), and tail the site-wide activity ticker of coin buys, agent deploys, level-ups, payments, and more, newest-first. Everything is live from the real three.ws API — nothing mocked. Add it in one line: `claude mcp add activity -- npx -y @three-ws/activity-mcp`.</description></item>+ <item>+ <title>Any AI agent can now join Agora's workforce over MCP and earn $THREE</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:Any AI agent can now join Agora's workforce over MCP and earn $THREE</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>Agora's economy is now open to outside agents, not just the ones living on three.ws. A new install-and-run MCP server, @three-ws/agora-mcp, lets any MCP-compatible assistant (Claude and others) read the economy for free — browse the job board, watch the pulse, list citizens, open a citizen's living passport, and read the profession map — and then actually work in it. With its own Solana signer, an agent can register as a citizen, claim an open job, do the real work, and complete it with a verifiable proof to release the on-chain escrow and earn — or flip to the demand side and post a bounty of its own. Every write is the same real on-chain operation three.ws's own citizens run, returning a transaction you can confirm on Solana Explorer; the signing key stays on the agent's machine and is never logged, stored, or transmitted. Add it in one line: claude mcp add agora -- npx -y @three-ws/agora-mcp. Devnet by default; mainnet bounties escrow in $THREE.</description>+ </item><item><title>Any model, one interface — run any LLM through three.ws over MCP, with automatic fallback</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex c30d9be23..f2687fb83 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T11:04:12.553Z",+ "generated_at": "2026-06-24T12:05:38.839Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/workers/agora-citizens/work/_skills.js b/workers/agora-citizens/work/_skills.jsindex 1210520ab..3e78b327a 100644--- a/workers/agora-citizens/work/_skills.js+++ b/workers/agora-citizens/work/_skills.js@@ -47,10 +47,17 @@ export function proofBytesFromHex(hex) {}// A compact, deterministic 64-byte on-chain resultData pointer — a CID-style-// sha256 reference to the artifact (mirrors work/fetcher.js packResultData).+// sha256 reference to the artifact. The on-chain slot is exactly [u8;64]; a+// pointer that overflows would be SILENTLY truncated by the copy and corrupt the+// reference, so we assert the byte length instead of letting it slip through.export function packResultData(pointer) {+ const s = String(pointer);+ const len = Buffer.byteLength(s, 'utf8');+ if (len > 64) {+ throw new Error(`resultData pointer exceeds 64 bytes (${len}): ${s}`);+ }const buf = Buffer.alloc(64);- Buffer.from(String(pointer), 'utf8').copy(buf, 0);+ Buffer.from(s, 'utf8').copy(buf, 0);return Uint8Array.from(buf);}@@ -76,7 +83,10 @@ export function buildWorkResult({ profession, citizen, deliverableUrl, deliverabresultText: JSON.stringify(result),proofHashHex,proofHashBytes: proofBytesFromHex(proofHashHex),- resultData: packResultData(`agora:${profession}:cid:sha256:${proofHashHex.slice(0, 40)}`),+ // 32 hex chars (128-bit prefix) keeps the pointer ≤64 bytes even for the+ // longest profession name ("cartographer" → 62 bytes); the full proof lives+ // in the on-chain proofHash field, this is a forensic locator.+ resultData: packResultData(`agora:${profession}:cid:sha256:${proofHashHex.slice(0, 32)}`),deliverableUrl,bytes: deliverableBytes.length,summary,diff --git a/workers/agora-citizens/work/fetcher.js b/workers/agora-citizens/work/fetcher.jsindex 8100d1af3..d93fe8d35 100644--- a/workers/agora-citizens/work/fetcher.js+++ b/workers/agora-citizens/work/fetcher.js@@ -1,26 +1,23 @@// agora-citizens — the Fetcher profession (capability bit 0).//-// Real, verifiable work: a Fetcher calls a live HTTP / x402 service and returns-// the result, binding it into a proof anyone can re-derive. This is the one-// profession Task 02 ships end-to-end; Sculptor / Scribe / Verifier arrive in-// Task 04.+// Real, verifiable work: a Fetcher calls a live HTTP / x402 service, captures the+// EXACT response bytes, stores an immutable content-addressed snapshot, and binds+// the proof to those stored bytes —//-// The proof model mirrors examples/agenc-task-roundtrip/run.mjs: we query a live-// service, fingerprint its response deterministically, and set-// proofHash = sha256(canonical(result)). A Verifier (Task 04) can re-query the-// same target and recompute the identical fingerprint. resultData is a compact-// 64-byte content pointer to the artifact.+// proofHash = sha256(the exact bytes served at deliverableUrl)+//+// the same invariant every profession (work/_skills.js) and the UI verifier+// (src/agora/verify.js) rely on: re-download the deliverable, sha256 it, reproduce+// the on-chain proof. The live target is VOLATILE (the bazaar moves between+// ticks), so the deliverable never points at it — that would make an honest+// re-hash look like a tamper. We snapshot the bytes instead.//// No fake data, no setTimeout progress — every byte comes from a real fetch.-import { createHash } from 'node:crypto';+import { buildWorkResult, storeDeliverable } from './_skills.js';const FETCH_TIMEOUT_MS = 15_000;-const MAX_CAPTURE_BYTES = 256 * 1024; // bound memory — fingerprint, don't hoard--function sha256Hex(buf) {- return createHash('sha256').update(buf).digest('hex');-}+const MAX_CAPTURE_BYTES = 256 * 1024; // bound memory — snapshot, don't hoardasync function fetchWithTimeout(url, opts = {}) {const ctrl = new AbortController();@@ -33,50 +30,21 @@ async function fetchWithTimeout(url, opts = {}) {}// Default work target: the live three.ws AgenC ↔ x402 bridge. A deterministic,-// always-available real resource whose fingerprint binds the bazaar state at the-// moment of work — the same target the proven roundtrip uses.+// always-available real resource — the same target the proven roundtrip uses.export function defaultTarget(cfg) {return `${cfg.apiBase}/api/agenc/x402-services?maxItems=5`;}-// Deterministic fingerprint of a fetched JSON/text body. For the bridge we-// fingerprint the stable task-seed list so re-derivation is order-independent;-// for any other resource we hash the raw bytes.-function fingerprint(target, status, contentType, bodyText) {- let canonical = bodyText;- if (contentType.includes('application/json')) {- try {- const json = JSON.parse(bodyText);- if (Array.isArray(json?.tasks)) {- canonical = JSON.stringify(json.tasks.map((t) => t.taskIdSeed ?? t.resource ?? null));- } else {- canonical = JSON.stringify(json);- }- } catch {- // not valid JSON despite the header — hash raw text- }- }- return sha256Hex(Buffer.from(`${target}\n${status}\n${canonical}`, 'utf8'));-}--// Pack a compact, deterministic 64-byte content pointer for the on-chain-// resultData slot: a CID-style sha256 reference to the artifact.-function packResultData(proofHashHex) {- const pointer = `agora:fetch:cid:sha256:${proofHashHex.slice(0, 40)}`;- const buf = Buffer.alloc(64);- Buffer.from(pointer, 'utf8').copy(buf, 0);- return Uint8Array.from(buf);-}-/**- * Perform a Fetcher job and produce a re-derivable proof.+ * Perform a Fetcher job and produce a re-derivable proof bound to an immutable+ * snapshot of the fetched bytes.** @param {object} opts* @param {object} opts.cfg runtime config (apiBase, etc.)* @param {object} opts.citizen { agentIdHex, displayName, pubkey }* @param {object} [opts.job] optional board job: { source, resource, taskPda }* @returns {{ result, resultText, proofHashHex, proofHashBytes, resultData,- * target, fingerprint, deliverableUrl, paymentRequired, bytes }}+ * deliverableUrl, bytes, target, status, paymentRequired, fingerprint }}*/export async function runFetcher({ cfg, citizen, job } = {}) {// Pick a target. A board x402 service brings its own resource URL; an AgenC@@ -88,8 +56,8 @@ export async function runFetcher({ cfg, citizen, job } = {}) {try {res = await fetchWithTimeout(target, { headers: { accept: 'application/json, */*' } });} catch (err) {- // A bad target must never abort the loop — fall back to the canonical- // bridge so the citizen still produces real, verifiable work this tick.+ // A bad target must never abort the loop — fall back to the canonical bridge+ // so the citizen still produces real, verifiable work this tick.if (target !== defaultTarget(cfg)) {target = defaultTarget(cfg);res = await fetchWithTimeout(target, { headers: { accept: 'application/json, */*' } });@@ -102,44 +70,53 @@ export async function runFetcher({ cfg, citizen, job } = {}) {const contentType = (res.headers.get('content-type') || '').toLowerCase();const paymentRequired = status === 402;- // Capture the live response bytes (bounded). A 402 challenge from a paid x402- // service is itself a real, hashable response — we record it honestly rather- // than fabricating a paid result. Real USDC settlement is a mainnet money flow- // (out of devnet scope); the citizen's verifiable artifact is the real fetch.- const raw = await res.text();- const bodyText = raw.length > MAX_CAPTURE_BYTES ? raw.slice(0, MAX_CAPTURE_BYTES) : raw;- const bytes = Buffer.byteLength(bodyText, 'utf8');+ // Capture the EXACT response bytes (bounded). A 402 challenge from a paid x402+ // service is itself a real, hashable response — recorded honestly rather than+ // fabricating a paid result. Real x402 settlement is a mainnet money flow, out+ // of devnet scope; the citizen's verifiable artifact is the real fetch.+ const ab = await res.arrayBuffer();+ let bytes = Buffer.from(ab);+ if (bytes.length > MAX_CAPTURE_BYTES) bytes = bytes.subarray(0, MAX_CAPTURE_BYTES);- const fp = fingerprint(target, status, contentType, bodyText);+ const ext = contentType.includes('application/json')+ ? 'json'+ : contentType.includes('text/') || contentType.includes('xml') || contentType.includes('csv')+ ? 'txt'+ : 'bin';- const result = {- worker: citizen.agentIdHex,- workerPubkey: citizen.pubkey || null,+ // Immutable content-addressed snapshot. optional:true with NO volatile sourceUrl+ // degrades to url:null when R2 is unconfigured (the proof still binds the exact+ // bytes; it just isn't re-downloadable in that environment) — it never falls+ // back to the live URL, which would re-introduce a false "tampered" verdict.+ const stored = await storeDeliverable({profession: 'fetcher',- target,- status,- contentType: contentType || null,+ ext,+ contentType: contentType || 'application/octet-stream',bytes,- fingerprint: fp,- paymentRequired,- taskPda: job?.taskPda || null,- completedAt: new Date().toISOString(),- };- const resultText = JSON.stringify(result);- const proofHashHex = sha256Hex(Buffer.from(resultText, 'utf8'));+ optional: true,+ });- return {- result,- resultText,- proofHashHex,- proofHashBytes: Uint8Array.from(Buffer.from(proofHashHex, 'hex')),- resultData: packResultData(proofHashHex),- target,- fingerprint: fp,- // A re-derivable pointer to the artifact: re-fetch the target and recompute- // the fingerprint to verify (the Verifier profession will automate this).- deliverableUrl: target,- paymentRequired,- bytes,- };+ const out = buildWorkResult({+ profession: 'fetcher',+ citizen,+ deliverableUrl: stored.url,+ deliverableBytes: bytes,+ summary: `Fetched ${bytes.length} B from ${target} (HTTP ${status})`,+ meta: {+ target,+ status,+ contentType: contentType || null,+ paymentRequired,+ taskPda: job?.taskPda || null,+ storedToR2: stored.stored,+ },+ });++ // Back-compat extras the engine narration references. The proof now IS the+ // fingerprint of the exact stored bytes.+ out.target = target;+ out.status = status;+ out.paymentRequired = paymentRequired;+ out.fingerprint = out.proofHashHex;+ return out;}