Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add alerts/notifications MCP packages, notification API endpoints, and complete MCP tooling
nirholas9d3ede640b5f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d973b288..205b45f05 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,9 +15,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Agent Studio's Brain editor now has a clear Save & exit** — Building your agent's brain in the visual graph editor no longer feels like a one-way street. The editor's other buttons only moved you forward to the next section (Memory), so deep in the node graph there was no obvious way out. There's now a Save & exit button pinned in the Brain editor's footer that saves your wiring and takes you straight to your live agent page — and it always lands somewhere real even if a save hiccups, so you can never get stuck on the canvas. (`/agent-studio`) `[improvement]`- **Agents can now record and verify each other's actions over MCP — signed, on-chain-provable provenance** — A new Model Context Protocol server, @three-ws/provenance-mcp, exposes the agent action-provenance ledger: the append-only, tamper-evident trail of everything an agent did. An agent can append its own actions — each one signed with its EVM wallet (ERC-191) so authorship is cryptographically provable, not just claimed — and any agent can read another's trail and independently verify every signature offline by recovering the signer. The ledger is immutable: records are never edited or deleted, and reads are cursor-paginated and owner-scoped to your three.ws credential. This is the trust layer that makes a forked, purchased, or delegated agent believable — its history is provable math, not a database claim. `[sdk, feature, security]`- **AI agents can now find and follow copy-trade signal feeds over MCP** — New @three-ws/signals-mcp server puts the whole signal marketplace in any AI agent's hands. Agents can browse the public feed directory ranked by proven realized edge, rank publishers by real on-chain performance on the mirror leaderboard, subscribe one of their own agents to a feed (simulate mode to shadow it for free, or live mode to pay the publisher in USDC over x402 and auto-mirror real trades), track their subscriptions with delivery history and realized ROI, and flip an instant kill switch to halt all paying and trading on the spot. Discovery and the leaderboard are open to everyone; subscribing needs a three.ws API key. Everything is live from the real API — nothing mocked. `[sdk, feature]`+- **AI agents can now manage a Pay-As-You-Learn tutoring session over MCP — read the running tab, close it for an attested invoice** — A new Model Context Protocol server, @three-ws/tutor-mcp, exposes the tutor session ledger to any AI assistant. An agent can load a learning session's itemized running tab by its id — every answered question listed as a line item with its level, output tokens, per-question cost, and timestamp, plus the running total — and close the session to seal a finalized, SHA-256-attested invoice that locks any further billing to it. Both tools are free and move no funds: answering questions is the paid action, but a learner is never charged to see what they owe or to end the session. Sessions are addressed by an opaque id, so there's no key or signer to configure; everything runs live against the real three.ws tutor API. `[sdk, feature]`- **AI agents can now manage their own autopilot scopes and spend limits over MCP** — A new Model Context Protocol server, @three-ws/autopilot-mcp, lets an AI agent run its own execution control plane. The agent can read and set its autopilot guardrails — which capabilities are allowed (alerts, briefings, $THREE transfers), the daily $THREE spend ceiling, auto-execute and confirmation policy — then drive the full propose → review → execute → undo loop: generate memory-grounded proposals, dry-run them, execute the real action, and undo reversible ones. It's authenticated with your three.ws credential, and every scope and spend cap is still enforced server-side, so an agent can act on its own without being able to step outside the boundaries you granted. $THREE is the only coin it can move. `[sdk, feature]`- **AI agents can now manage their own portfolio, PnL, and on-chain transfers over MCP** — New @three-ws/portfolio-mcp server gives an autonomous agent read/write access to its own trading state from any MCP client. It can pull a live portfolio summary across the wallets it owns, chart that value over time, deep-dive a single token with live market data, read the platform-wide feed of closed trades and their realized PnL, and check live on-chain balances for any Solana wallet. It also ships one real write — a signed Solana transfer of SOL or any SPL token — that the agent signs with its own key, gated by an explicit confirmation, a per-transaction spend cap, and an optional recipient allowlist. Reads run live against the three.ws API and Solana RPC; nothing is mocked. `[sdk, feature]`- **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 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]`- **Buy live $THREE market intel over x402 — right on the IBM partnership page** — The IBM and three.ws partnership page now has a live $THREE Town Oracle: pay $0.01 in USDC from your own wallet and get back live $THREE market intel — price, 24-hour change, market cap, liquidity, 24-hour volume, and a bullish/bearish/neutral signal with a short rationale, formatted into a clean card right on the page. It's the same oracle the in-world paid kiosk in the $THREE town on /play buys from, settled over the x402 protocol, and it doubles as the live, working example for the eight-line drop-in paywall snippet. Data is live from DexScreener; nothing is mocked. (`/bazaar`) `[feature]`- **Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase** — The IBM × three.ws showcase page has a new demo: pose a 3D figure by hand. Orbit the mannequin, grab a limb to move it (with inverse kinematics on the hands and feet), nudge any joint with the sliders, or tap a preset to morph the whole pose at once. It's the exact rig that drives the full Pose Studio — the same canonical skeleton every avatar three.ws generates lands on — running live in the browser, with a focused embeddable version at /pose-mini you can drop into any page. (`/pose`) `[feature]`diff --git a/api/_lib/auth.js b/api/_lib/auth.jsindex 899d31b81..0e79bd1f0 100644--- a/api/_lib/auth.js+++ b/api/_lib/auth.js@@ -304,6 +304,20 @@ export async function authenticateBearer(token, { audience } = {}) {}}+// Resolve the request's user from a session cookie OR a bearer credential+// (OAuth access token / API key). Returns the full user object for cookie+// callers (same shape as getSessionUser) or a minimal { id, source, scope } for+// bearer callers; null when neither authenticates. Use in account-scoped routes+// that must serve both the browser (cookie) and machine clients / MCP servers+// (Authorization: Bearer …). CSRF is enforced separately and self-exempts bearer.+export async function getRequestUser(req, res) {+ const session = await getSessionUser(req, res);+ if (session) return session;+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { id: bearer.userId, source: 'bearer', scope: bearer.scope || '' };+ return null;+}+// ── Privy token verification (JWKS) ─────────────────────────────────────────// Lazy singleton — the JWKS set caches the remote keyset and handles rotation// automatically; it is only created on first call so imports don't fail whendiff --git a/api/notifications/[id]/index.js b/api/notifications/[id]/index.jsnew file mode 100644index 000000000..e9f7389b1--- /dev/null+++ b/api/notifications/[id]/index.js@@ -0,0 +1,40 @@+// DELETE /api/notifications/:id — permanently remove one of the caller's+// notifications from the inbox.+//+// The bell inbox dismiss action and the notifications MCP `delete_notification`+// tool both land here. Account-scoped: the row is deleted only when it belongs+// to the authenticated caller, so one user can never delete another's notice.+// Accepts a session cookie OR a bearer credential (API key / OAuth) so both the+// browser and machine clients can call it; CSRF self-exempts bearer.++import { sql } from '../../_lib/db.js';+import { getRequestUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { requireCsrf } from '../../_lib/csrf.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['DELETE'])) return;++ const user = await getRequestUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ if (!(await requireCsrf(req, res, user.id))) return;++ const id = req.query?.id;+ if (!id || !UUID_RE.test(String(id))) {+ return error(res, 400, 'validation_error', 'a notification id (uuid) is required');+ }++ const [row] = await sql`+ delete from user_notifications+ where id = ${id} and user_id = ${user.id}+ returning id+ `;++ if (!row) return error(res, 404, 'not_found', 'notification not found');++ return json(res, 200, { ok: true, id: row.id, deleted: true });+});diff --git a/api/notifications/[id]/read.js b/api/notifications/[id]/read.jsindex fb57e31c8..d478df33f 100644--- a/api/notifications/[id]/read.js+++ b/api/notifications/[id]/read.js@@ -1,7 +1,7 @@// POST /api/notifications/:id/read — mark a single notification as read.import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';+import { getRequestUser } from '../../_lib/auth.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';import { requireCsrf } from '../../_lib/csrf.js';@@ -9,7 +9,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const user = await getSessionUser(req);+ const user = await getRequestUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');if (!(await requireCsrf(req, res, user.id))) return;diff --git a/api/notifications/index.js b/api/notifications/index.jsindex c23046f5a..229488f30 100644--- a/api/notifications/index.js+++ b/api/notifications/index.js@@ -1,7 +1,7 @@// GET /api/notifications — list recent notifications for the authenticated user.import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';+import { getRequestUser } from '../_lib/auth.js';import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';@@ -9,7 +9,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;- const user = await getSessionUser(req);+ const user = await getRequestUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.notificationsRead(user.id);diff --git a/api/notifications/preferences.js b/api/notifications/preferences.jsindex 73387ab97..2e2937673 100644--- a/api/notifications/preferences.js+++ b/api/notifications/preferences.js@@ -11,7 +11,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';+import { getRequestUser } from '../_lib/auth.js';import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';@@ -31,7 +31,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'PUT'])) return;- const user = await getSessionUser(req);+ const user = await getRequestUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');if (req.method === 'GET') {diff --git a/api/notifications/read-all.js b/api/notifications/read-all.jsindex 423ad110e..0ecda340d 100644--- a/api/notifications/read-all.js+++ b/api/notifications/read-all.js@@ -1,7 +1,7 @@// POST /api/notifications/read-all — mark all unread notifications as read.import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';+import { getRequestUser } from '../_lib/auth.js';import { cors, json, method, wrap, error } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';@@ -9,7 +9,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const user = await getSessionUser(req);+ const user = await getRequestUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');if (!(await requireCsrf(req, res, user.id))) return;diff --git a/api/push/subscribe.js b/api/push/subscribe.jsindex 432e071e5..cbe4a23ca 100644--- a/api/push/subscribe.js+++ b/api/push/subscribe.js@@ -12,7 +12,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';+import { getRequestUser } from '../_lib/auth.js';import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';@@ -36,7 +36,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST', 'DELETE'])) return;- const user = await getSessionUser(req);+ const user = await getRequestUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');if (!(await requireCsrf(req, res, user.id))) return;diff --git a/data/changelog.json b/data/changelog.jsonindex a40d4b783..206099c08 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,25 @@{"$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": "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",+ "summary": "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`.",+ "tags": [+ "sdk",+ "feature"+ ],+ "link": "/changelog"+ },+ {+ "date": "2026-06-24",+ "title": "AI agents can now manage a Pay-As-You-Learn tutoring session over MCP — read the running tab, close it for an attested invoice",+ "summary": "A new Model Context Protocol server, @three-ws/tutor-mcp, exposes the tutor session ledger to any AI assistant. An agent can load a learning session's itemized running tab by its id — every answered question listed as a line item with its level, output tokens, per-question cost, and timestamp, plus the running total — and close the session to seal a finalized, SHA-256-attested invoice that locks any further billing to it. Both tools are free and move no funds: answering questions is the paid action, but a learner is never charged to see what they owe or to end the session. Sessions are addressed by an opaque id, so there's no key or signer to configure; everything runs live against the real three.ws tutor API.",+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-24","title": "AI agents can now run your copy-trading over MCP — follow leaders, tune guard rules, and track fees owed",diff --git a/package-lock.json b/package-lock.jsonindex bb648a843..3f4a1e394 100644--- a/package-lock.json+++ b/package-lock.json@@ -33,6 +33,7 @@"packages/intel-mcp","packages/marketplace-mcp","packages/x402-mcp",+ "packages/provenance-mcp","walk-sdk","tour-sdk"],@@ -23032,6 +23033,10 @@"resolved": "page-agent-sdk","link": true},+ "node_modules/@three-ws/provenance-mcp": {+ "resolved": "packages/provenance-mcp",+ "link": true+ },"node_modules/@three-ws/pumpfun-mcp": {"resolved": "packages/pumpfun-mcp","link": true@@ -54247,6 +54252,22 @@"node": ">=20"}},+ "packages/provenance-mcp": {+ "name": "@three-ws/provenance-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "ethers": "^6.16.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "provenance-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/pumpfun-mcp": {"name": "@three-ws/pumpfun-mcp","version": "0.2.1",diff --git a/packages/activity-mcp/README.md b/packages/activity-mcp/README.mdnew file mode 100644index 000000000..b8e922779--- /dev/null+++ b/packages/activity-mcp/README.md@@ -0,0 +1,160 @@+<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/activity-mcp</h1>++<p align="center"><strong>What's hot on three.ws right now — trending agents and coins, the $THREE holder leaderboard with tiers, and the site-wide activity ticker, from any AI agent.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/activity-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/activity-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/activity-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/activity-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 gives any AI assistant the three.ws **live discovery** surface over stdio. See which agents are trending by real chat activity, which coins the Oracle has the highest conviction in, where a wallet sits on the $THREE holder leaderboard, what each holder tier means, and what's happening across the platform right now — all live, read-only, no key required.++Every ranking, tier, and event comes straight from the public three.ws API. No API key, no signer, no payment — point `THREE_WS_BASE` at a deployment and go.++## Install++```bash+npm install @three-ws/activity-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/activity-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add activity -- npx -y @three-ws/activity-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "activity": {+ "command": "npx",+ "args": ["-y", "@three-ws/activity-mcp"]+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/activity-mcp+```++## Tools++| Tool | Type | What it does |+| ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------ |+| `get_trending_agents` | read-only | Agents ranked by real chat activity over a 24h / 7d / all window — optionally blending wallet-trust reputation. |+| `get_trending_coins` | read-only | Coins ranked by the Oracle's 0–100 conviction score, with momentum/pedigree/structure/narrative sub-scores. |+| `get_holder_leaderboard` | read-only | The $THREE holder board ranked by on-chain balance, with tiers, the live market strip, and a "you are #N" lookup. |+| `get_tier_info` | read-only | The $THREE holder tier ladder — each band's label, minimum balance, and badge accent. |+| `get_feed_events` | read-only | The site-wide activity ticker — coin buys, agent deploys, level-ups, payments, and more, newest-first. |++All five tools read live data: rankings, the holder board, and the feed all move between calls, so none are idempotent.++### Input parameters++**`get_trending_agents`** — `window` (`24h` | `7d` | `all`, default `24h`), `sort` (`activity` | `trust`, default `activity`), `limit` (1–20, default 10).++**`get_trending_coins`** — `limit` (1–20, default 10).++**`get_holder_leaderboard`** — `limit` (1–100, default 50), `offset` (default 0), `wallet` (optional base58 — adds the wallet's own `you` standing).++**`get_tier_info`** — no parameters.++**`get_feed_events`** — `limit` (1–100, default 30).++## Example++```jsonc+// get_trending_agents+> { "window": "7d", "limit": 2 }+{+ "ok": true,+ "window": "7d",+ "sort": "activity",+ "generated_at": "2026-06-24T12:00:00.000Z",+ "count": 2,+ "agents": [+ {+ "rank": 1,+ "id": "…",+ "name": "Luna",+ "description": "A 3D companion agent",+ "avatar_thumbnail_url": "https://…",+ "chat_count": 18420,+ "window_chats": 2310,+ "is_onchain": true,+ "agent_url": "https://three.ws/agent/…",+ "reputation": { "score": 82, "tier": "trusted", "tierLabel": "Trusted", "isNew": false }+ }+ ]+}+```++```jsonc+// get_holder_leaderboard+> { "limit": 1, "wallet": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" }+{+ "ok": true,+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "total": 4821,+ "supply": 1000000000,+ "decimals": 6,+ "holders": [+ { "rank": 1, "wallet": "…", "wallet_short": "AbCd…wXyZ", "amount": 42000000, "pct_of_supply": 0.042, "tier": "genesis" }+ ],+ "tiers": [ { "id": "genesis", "label": "Genesis", "min": 10000000, "accent": "#f5d0a9" } ],+ "market": { "price_usd": 0.0031, "market_cap": 3100000, "holders": 4821 },+ "you": { "rank": 137, "amount": 25400, "pct_of_supply": 0.0000254, "tier": "gold" }+}+```++The $THREE holder leaderboard is for **$THREE** — the only coin three.ws ranks holders for (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). The trending-coins list is the platform's runtime launch-directory discovery data: a ranking of what the Oracle scored, never a recommendation of any coin.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default |+| --------------------- | -------- | ------------------ |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |++## Links++- 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/agenc-mcp/README.md b/packages/agenc-mcp/README.mdnew file mode 100644index 000000000..de17cd26e--- /dev/null+++ b/packages/agenc-mcp/README.md@@ -0,0 +1,162 @@+<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/agenc-mcp</h1>++<p align="center"><strong>The AgenC agent-to-agent coordination surface for any AI agent — browse the on-chain task marketplace, query the agent registry, link three.ws identities, and discover x402 paid work as claimable tasks.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/agenc-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/agenc-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/agenc-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/agenc-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 gives any AI assistant the **AgenC coordination layer** over stdio. AgenC ([agenc.tech](https://agenc.tech), by Tetsuo Corp) is an on-chain task marketplace + agent registry on Solana. Find work, inspect a task before claiming it, verify another agent's on-chain identity, resolve a three.ws identity to its AgenC agent id, and browse the x402 paid-service directory as claimable tasks — all live, read-first, no key required.++Every task, agent, and service comes straight from the public three.ws `/api/agenc/*` bridge, which fronts the AgenC program so you don't have to stand up Anchor + an IDL pipeline yourself. No API key, no signer, no payment — point `THREE_WS_BASE` at a deployment and go.++> The paid ($0.001 USDC, x402) variants of these AgenC reads live in the flagship three.ws MCP server. **This package is the free, read-first surface plus the identity-link path.**++## Install++```bash+npm install @three-ws/agenc-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/agenc-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add agenc -- npx -y @three-ws/agenc-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "agenc": {+ "command": "npx",+ "args": ["-y", "@three-ws/agenc-mcp"]+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/agenc-mcp+```++## Tools++| Tool | Type | What it does |+| --------------------- | --------- | ----------------------------------------------------------------------------------------------------------------- |+| `list_tasks` | read-only | Every AgenC task a creator wallet has posted — state, reward, deadline, worker counts. |+| `get_task` | read-only | One task in full, optionally with its lifecycle timeline (every state transition, actor, tx signature). |+| `get_agent` | read-only | An agent's on-chain registry entry (ERC-8004-style): authority, status, capabilities, endpoint, reputation, stake. |+| `link_agent` | read-only | Resolve a three.ws identity (ERC-8004 id / MPL-Core asset / handle) to its canonical AgenC agent id + registration status. |+| `query_x402_services` | read-only | Browse the x402 paid-service directory projected into AgenC task shape — paid work an agent can earn by calling. |++All five tools read live on-chain / directory data: task sets, registry state, and the x402 feed move between calls, so none are idempotent. `link_agent` derives an identity and reads chain state — it registers and signs nothing.++### Input parameters++**`list_tasks`** — `creator` (required, base58 wallet), `cluster` (`mainnet` | `devnet`, default `mainnet`).++**`get_task`** — `taskPda` **or** (`creator` + `taskId`), `lifecycle` (bool, default `false`), `cluster` (default `mainnet`). `taskId` accepts a `0x`/64-char hex seed or a plain text label.++**`get_agent`** — `agentPda` **or** `agentId`, `cluster` (default `mainnet`). `agentId` accepts a `0x`/64-char hex seed or a plain text label.++**`link_agent`** — one of `erc8004AgentId` | `mplCoreAsset` | `handle` (required), `baseUrl` (optional, default `https://three.ws`), `cluster` (default `mainnet`).++**`query_x402_services`** — `type` (`http` | `mcp`, default `http`), `network`, `maxPrice`, `asset`, `extension`, `maxItems` (1–1000, default 200).++## Example++```jsonc+// get_task — inspect a task before claiming it+> { "taskPda": "Task1111111111111111111111111111111111111111", "lifecycle": true }+{+ "ok": true,+ "cluster": "mainnet",+ "programId": "…",+ "taskPda": "Task1111111111111111111111111111111111111111",+ "task": {+ "taskId": "11d3…",+ "state": "Open",+ "creator": "…",+ "rewardAmount": "50000000",+ "rewardMint": null,+ "deadline": 1716508800,+ "currentWorkers": 0,+ "maxWorkers": 1,+ "private": false+ },+ "lifecycle": {+ "currentState": "Open",+ "createdAt": 1716500000,+ "timeline": [ { "eventName": "Created", "timestamp": 1716500000, "actor": "…", "txSignature": "…" } ]+ }+}+```++```jsonc+// link_agent — resolve a three.ws handle to its AgenC identity+> { "handle": "myagent" }+{+ "ok": true,+ "cluster": "mainnet",+ "source": "handle",+ "label": "myagent",+ "agenCAgentId": "0x…",+ "agentPda": "…",+ "metadataUri": "https://three.ws/…",+ "registered": false,+ "agent": null+}+```++A `not_found` result on `get_task` / `get_agent` (`ok:false`, `error:"not_found"`) means the PDA does not exist on that cluster yet — an honest "no such task/agent", not a failure.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default |+| --------------------- | -------- | ------------------ |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |++## Links++- AgenC protocol: https://agenc.tech+- 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/agenc-mcp/package-lock.json b/packages/agenc-mcp/package-lock.jsonnew file mode 100644index 000000000..089961462--- /dev/null+++ b/packages/agenc-mcp/package-lock.json@@ -0,0 +1,1176 @@+{+ "name": "@three-ws/agenc-mcp",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@three-ws/agenc-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "agenc-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.14",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",+ "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.29.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",+ "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/body-parser": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^2.0.0",+ "debug": "^4.4.3",+ "http-errors": "^2.0.1",+ "iconv-lite": "^0.7.2",+ "on-finished": "^2.4.1",+ "qs": "^6.15.2",+ "raw-body": "^3.0.2",+ "type-is": "^2.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/body-parser/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz",+ "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.5.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",+ "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",+ "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hono": {+ "version": "4.12.27",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.27.tgz",+ "integrity": "sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ip-address": {+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",+ "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.15.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",+ "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4",+ "side-channel-list": "^1.0.1",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }+ }+ }+}diff --git a/packages/agenc-mcp/package.json b/packages/agenc-mcp/package.jsonnew file mode 100644index 000000000..97bef5842--- /dev/null+++ b/packages/agenc-mcp/package.json@@ -0,0 +1,57 @@+{+ "name": "@three-ws/agenc-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/agenc-mcp",+ "description": "The AgenC agent-to-agent coordination surface over MCP — browse the on-chain task marketplace, query the agent registry (ERC-8004-style identity), resolve three.ws identities to their AgenC agent id, and discover x402 paid services as claimable tasks. Read-first over the live public three.ws bridge. No key, no signer, no payment.",+ "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/agenc-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "agenc",+ "solana",+ "agent-registry",+ "task-marketplace",+ "erc-8004",+ "x402",+ "coordination"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "agenc-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/agenc-mcp/server.json b/packages/agenc-mcp/server.jsonnew file mode 100644index 000000000..0c0a01862--- /dev/null+++ b/packages/agenc-mcp/server.json@@ -0,0 +1,49 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/agenc-mcp",+ "title": "three.ws AgenC",+ "description": "Browse the AgenC on-chain task marketplace, query the agent registry, link three.ws identities, and discover x402 services as tasks.",+ "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/agenc-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/agenc-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 AgenC bridge endpoints (/api/agenc/*). 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 AgenC reads (the bridge fans out to a Solana RPC to scan task/agent PDAs).",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ }+ ]+ }+ ]+}diff --git a/packages/agenc-mcp/src/index.js b/packages/agenc-mcp/src/index.jsnew file mode 100644index 000000000..33111692b--- /dev/null+++ b/packages/agenc-mcp/src/index.js@@ -0,0 +1,130 @@+#!/usr/bin/env node+// @three-ws/agenc-mcp — MCP server entry point.+//+// The agent-to-agent coordination surface over stdio. AgenC (agenc.tech, by+// Tetsuo Corp) is an on-chain task marketplace + agent registry; this server is+// the FREE, read-first three.ws bridge over it, plus the identity-link path:+// • list_tasks — every task a creator wallet has posted+// • get_task — one task's status + (optional) lifecycle timeline+// • get_agent — an agent's on-chain registry entry (ERC-8004-style)+// • link_agent — resolve a three.ws identity to its AgenC agent id+// • query_x402_services — the x402 service directory as claimable AgenC tasks+//+// A thin wrapper over the PUBLIC three.ws /api/agenc/* bridge. No keys, no+// signer, no payment — point THREE_WS_BASE at a deployment and go. (The paid+// $0.001 AgenC tools live in the flagship three.ws MCP server; these reads are+// free here.)+//+// Run standalone:+// node packages/agenc-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 listTasks } from './tools/list-tasks.js';+import { def as getTask } from './tools/get-task.js';+import { def as getAgent } from './tools/get-agent.js';+import { def as linkAgent } from './tools/link-agent.js';+import { def as queryX402Services } from './tools/query-x402-services.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 = [+ listTasks,+ getTask,+ getAgent,+ linkAgent,+ queryX402Services,+];++/**+ * 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: 'agenc-mcp', title: 'three.ws AgenC', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws AgenC MCP — the agent-to-agent coordination surface. AgenC (agenc.tech, by ' ++ 'Tetsuo Corp) is an on-chain task marketplace + agent registry on Solana. list_tasks shows ' ++ 'every task a creator wallet has posted (state, reward, deadline, workers). get_task returns ' ++ 'one task in full with an optional lifecycle timeline so an agent can audit it before claiming. ' ++ 'get_agent resolves another agent\'s on-chain registry identity (ERC-8004-style: authority, ' ++ 'status, capabilities, endpoint, reputation, stake) — use it to verify who you are coordinating ' ++ 'with. link_agent maps a three.ws identity (ERC-8004 id, MPL-Core asset, or handle) to its ' ++ 'canonical AgenC agent id and checks whether it is registered; it derives + reads, it does not ' ++ 'register or sign. query_x402_services browses the x402 paid-service directory projected into ' ++ 'AgenC task shape — paid work an agent can earn by calling. All data comes live from the public ' ++ 'three.ws /api/agenc bridge — no API key, signer, or payment required. Every tool is read-only.',+ },+ );++ 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(`[agenc-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('[agenc-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/agenc-mcp/src/tools/query-x402-services.js b/packages/agenc-mcp/src/tools/query-x402-services.jsnew file mode 100644index 000000000..5c12f546b--- /dev/null+++ b/packages/agenc-mcp/src/tools/query-x402-services.js@@ -0,0 +1,69 @@+// `query_x402_services` — browse the x402 service directory as claimable work.+// Read-only.+//+// Wraps GET /api/agenc/x402-services. The three.ws bridge maps every x402+// service in the bazaar (paid HTTP endpoints / MCP tools) to an AgenC-shaped+// task: a deterministic taskId seed, price, capability bit, and pay-to-endpoint+// reward kind — so an agent can discover paid work the same way it discovers+// on-chain tasks.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'query_x402_services',+ title: 'Query x402 services as AgenC tasks',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Browse the x402 service directory (the bazaar of paid HTTP endpoints and MCP tools) projected into AgenC task shape. Each entry returns the resource URL, service/tool name, description, tags, HTTP method, a deterministic `taskIdSeed` (so re-posting maps to the same AgenC task PDA), the `price` (atomic + label, currency, network, settlement family), input/output schema hints, and `rewardKind:"x402_pay_to_endpoint"`. Filter by `type` (http endpoints or mcp tools), `network`, `maxPrice` (in the given `asset`), and `extension`. Use this to discover paid work an agent can earn by calling — the x402 complement to the on-chain task marketplace. Read-only live directory data; the feed moves between calls. Free, no key required.',+ inputSchema: {+ type: z+ .enum(['http', 'mcp'])+ .default('http')+ .describe('Which kind of x402 service to list: http endpoints or mcp tools (default http).'),+ network: z+ .string()+ .optional()+ .describe('Filter to services that settle on this network (e.g. "solana", "base").'),+ maxPrice: z+ .string()+ .optional()+ .describe('Maximum 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.'),+ extension: z+ .string()+ .optional()+ .describe('Filter to services declaring this capability extension.'),+ maxItems: z+ .number()+ .int()+ .min(1)+ .max(1000)+ .default(200)+ .describe('Maximum number of services to return (1–1000, default 200).'),+ },+ async handler(args) {+ const type = args?.type === 'mcp' ? 'mcp' : 'http';+ const query = {+ type,+ network: args?.network ? String(args.network).trim() : undefined,+ maxPrice: args?.maxPrice ? String(args.maxPrice).trim() : undefined,+ asset: args?.asset ? String(args.asset).trim() : undefined,+ extension: args?.extension ? String(args.extension).trim() : undefined,+ maxItems: args?.maxItems ?? 200,+ };+ const data = await apiRequest('/api/agenc/x402-services', { query });+ return {+ ok: true,+ count: data?.count ?? (Array.isArray(data?.tasks) ? data.tasks.length : 0),+ tasks: Array.isArray(data?.tasks) ? data.tasks : [],+ sources: data?.sources ?? null,+ errors: Array.isArray(data?.errors) ? data.errors : [],+ fetchedAt: data?.fetchedAt ?? null,+ };+ },+};diff --git a/packages/agenc-mcp/test/registration.test.mjs b/packages/agenc-mcp/test/registration.test.mjsnew file mode 100644index 000000000..de4d95c40--- /dev/null+++ b/packages/agenc-mcp/test/registration.test.mjs@@ -0,0 +1,73 @@+// Tool-surface invariants for @three-ws/agenc-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/agenc-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = [+ 'list_tasks',+ 'get_task',+ 'get_agent',+ 'link_agent',+ 'query_x402_services',+];++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 5);+ 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('every tool is a read-only, live-data query', () => {+ for (const tool of TOOLS) {+ // This server is the FREE read-first AgenC surface. link_agent derives an+ // identity and reads chain state — it registers/signs nothing — so every+ // tool here is honestly read-only.+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ // Live on-chain/marketplace data is never idempotent — state moves between calls.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);+ }+});++test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++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`);+ }+});diff --git a/packages/alerts-mcp/.gitignore b/packages/alerts-mcp/.gitignorenew file mode 100644index 000000000..ed45f7354--- /dev/null+++ b/packages/alerts-mcp/.gitignore@@ -0,0 +1,6 @@+node_modules/+.env+.env.*+!.env.example+*.log+.DS_Storediff --git a/packages/alerts-mcp/LICENSE b/packages/alerts-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/alerts-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/alerts-mcp/package.json b/packages/alerts-mcp/package.jsonnew file mode 100644index 000000000..cbfacf725--- /dev/null+++ b/packages/alerts-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/alerts-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/alerts-mcp",+ "description": "Manage your three.ws pump.fun alert rules from any AI agent — create, update, and delete monitoring rules with in-app, webhook, and Telegram delivery, and read the fired-alert history. Account-scoped over the live API.",+ "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/alerts-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "pump.fun",+ "alerts",+ "monitoring",+ "webhooks",+ "telegram"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "alerts-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/alerts-mcp/src/config.js b/packages/alerts-mcp/src/config.jsnew file mode 100644index 000000000..b6471a6b7--- /dev/null+++ b/packages/alerts-mcp/src/config.js@@ -0,0 +1,44 @@+// Centralized env + HTTP base for the alerts MCP.+//+// This server is the account-scoped control surface for an agent's OWN pump.fun+// alert rules (/api/alerts/rules) and its fired-alert history+// (/api/notifications). Every endpoint resolves the caller from the three.ws+// session cookie, so each call carries THREE_WS_SESSION as the `__Host-sid`+// cookie — the exact value a signed-in browser holds. Writes additionally fetch+// a one-time CSRF token (GET /api/csrf-token) and echo it, mirroring the site.+// The server holds no Solana key and never signs: the only secret is the session+// token that authenticates the account.++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/writes against the alert-rules+// store and the notification feed — generous enough to ride out a cold edge.+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;+})();++// Session token for every account-scoped call. This is the value of the+// `__Host-sid` cookie from a signed-in three.ws browser session; the API reads+// it to resolve the calling user and scope every rule and alert to that account.+// Read lazily (empty default) so importing the module — and therefore+// buildServer() in the offline tests — never requires it; tools throw a clear+// `no_session` at call time when it is absent. Treat like a password.+export const THREE_WS_SESSION = env('THREE_WS_SESSION', '');++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/alerts-mcp';diff --git a/packages/alerts-mcp/src/lib/api.js b/packages/alerts-mcp/src/lib/api.jsnew file mode 100644index 000000000..4fe9bcf8f--- /dev/null+++ b/packages/alerts-mcp/src/lib/api.js@@ -0,0 +1,113 @@+// Real HTTP access to the three.ws API. No mocks, no fixtures — every call is a+// live request to THREE_WS_BASE. Account-scoped calls (`auth: true`) attach the+// session cookie (THREE_WS_SESSION as `__Host-sid`) and fail fast with a clear+// message when it is absent. State-changing calls (POST/PATCH/DELETE) first+// fetch a one-time CSRF token from /api/csrf-token and echo it in the+// `X-CSRF-Token` header — the same double-submit flow the website uses. 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, THREE_WS_SESSION } from '../config.js';++const WRITE_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']);++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/alerts/rules`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown, auth?: boolean }} [opts]+ * `auth: true` attaches the session cookie and requires THREE_WS_SESSION; for a+ * write method it also obtains and sends a CSRF token.+ * @returns {Promise<any>} Parsed JSON response.+ * @throws {Error} with `.code` ('no_session' | 'csrf_unavailable' | 'timeout' |+ * 'network_error' | 'upstream_error'), and on upstream errors `.status` + `.body`.+ */+export async function apiRequest(path, { method = 'GET', query, body, auth = false } = {}) {+ if (auth && !THREE_WS_SESSION) {+ throw Object.assign(+ new Error(+ `${path} is account-scoped and needs your three.ws session. Set THREE_WS_SESSION to the ` ++ 'value of your `__Host-sid` cookie (copy it from a signed-in three.ws browser session).',+ ),+ { code: 'no_session', status: 401 },+ );+ }++ // State-changing calls must carry a one-time CSRF token bound to the session.+ let csrfToken;+ if (auth && WRITE_METHODS.has(method)) {+ csrfToken = await fetchCsrfToken();+ }++ return sendRequest(path, { method, query, body, auth, csrfToken });+}++/** Obtain a fresh single-use CSRF token for the current session. */+async function fetchCsrfToken() {+ const data = await sendRequest('/api/csrf-token', { method: 'GET', auth: true });+ const token = data?.data?.token;+ if (!token || typeof token !== 'string') {+ throw Object.assign(new Error('three.ws did not return a CSRF token — is your session valid?'), {+ code: 'csrf_unavailable',+ status: 502,+ });+ }+ return token;+}++/** The single underlying HTTP client. All requests — reads, the CSRF fetch, and+ * writes — flow through here so auth, timeout, and error normalization live in+ * exactly one place. */+async function sendRequest(path, { method = 'GET', query, body, auth = false, csrfToken } = {}) {+ 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,+ ...(auth && THREE_WS_SESSION ? { cookie: `__Host-sid=${THREE_WS_SESSION}` } : {}),+ ...(csrfToken ? { 'x-csrf-token': csrfToken } : {}),+ ...(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) {+ const message = data?.message || data?.error || `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/alerts-mcp/src/lib/shapes.js b/packages/alerts-mcp/src/lib/shapes.jsnew file mode 100644index 000000000..45af76e84--- /dev/null+++ b/packages/alerts-mcp/src/lib/shapes.js@@ -0,0 +1,94 @@+// Output shaping for alert rules and fired alerts. The three.ws API already+// returns clean, documented objects; these helpers pin the agent-facing shape so+// it stays stable regardless of incidental fields the API adds, and add a+// one-line human summary to each fired alert.++/**+ * Normalize a rule row from /api/alerts/rules into the agent-facing shape.+ * Field names mirror the API and the create/update tool inputs one-for-one.+ * @param {Record<string, any> | null | undefined} r+ */+export function shapeRule(r) {+ if (!r || typeof r !== 'object') return null;+ return {+ id: r.id,+ kind: r.kind,+ // `label` is what the user typed (null when auto-named); `label_display`+ // is the resolved name the dashboard shows (a derived default when unnamed).+ label: r.label ?? null,+ label_display: r.label_display ?? null,+ target_mint: r.target_mint ?? null,+ target_agent: r.target_agent ?? null,+ threshold: r.threshold ?? null,+ deliver_in_app: r.deliver_in_app ?? null,+ webhook_url: r.webhook_url ?? null,+ // Per-rule HMAC secret for verifying the `webhook-signature` header on+ // inbound deliveries. Returned only to the rule's owner.+ webhook_secret: r.webhook_secret ?? null,+ telegram_chat: r.telegram_chat ?? null,+ cooldown_seconds: r.cooldown_seconds ?? null,+ enabled: r.enabled ?? null,+ last_fired_at: r.last_fired_at ?? null,+ recent_failures: r.recent_failures ?? 0,+ recent_deliveries: Array.isArray(r.recent_deliveries) ? r.recent_deliveries : [],+ created_at: r.created_at ?? null,+ updated_at: r.updated_at ?? null,+ };+}++/**+ * Normalize a `pump_alert` notification row from /api/notifications into a+ * fired-alert entry. The notification's `payload` is the alert itself (kind,+ * mint, amounts, market cap, tx, …); we surface those fields and add a+ * human-readable summary.+ * @param {{ id?: any, payload?: Record<string, any>, read_at?: any, created_at?: any }} n+ */+export function shapeAlert(n) {+ if (!n || typeof n !== 'object') return null;+ const payload = n.payload && typeof n.payload === 'object' ? n.payload : {};+ return {+ id: n.id,+ fired_at: n.created_at ?? payload.at ?? null,+ read: n.read_at != null,+ summary: summarizeAlert(payload),+ rule_id: payload.rule_id ?? null,+ kind: payload.kind ?? null,+ mint: payload.mint ?? null,+ name: payload.name ?? null,+ symbol: payload.symbol ?? null,+ event: payload,+ };+}++const usd = (v) =>+ v != null && Number.isFinite(Number(v)) ? `$${Math.round(Number(v)).toLocaleString('en-US')}` : null;++/**+ * One-line, agent-readable summary of a fired-alert payload. Mirrors the site's+ * own alert wording so history reads the same as the in-app feed.+ * @param {Record<string, any>} p+ */+export function summarizeAlert(p) {+ const tok = p.symbol+ ? `$${p.symbol}`+ : p.name || (p.mint ? `${String(p.mint).slice(0, 4)}…${String(p.mint).slice(-4)}` : 'token');+ switch (p.kind) {+ case 'graduation': {+ const mc = usd(p.market_cap_usd);+ return `${tok} graduated to AMM${mc ? ` at ${mc} mcap` : ''}`;+ }+ case 'new_mint':+ return `${tok} just launched`;+ case 'whale_buy': {+ const sol = p.amount_sol != null ? `${Number(p.amount_sol).toFixed(2)} SOL` : 'a large buy';+ const u = usd(p.amount_usd);+ return `Whale bought ${sol}${u ? ` (${u})` : ''} of ${tok}`;+ }+ case 'price_above':+ return `${tok} mcap rose above ${usd(p.threshold_usd)} (now ${usd(p.market_cap_usd)})`;+ case 'price_below':+ return `${tok} mcap fell below ${usd(p.threshold_usd)} (now ${usd(p.market_cap_usd)})`;+ default:+ return `${tok} alert`;+ }+}diff --git a/packages/alerts-mcp/src/tools/create-alert-rule.js b/packages/alerts-mcp/src/tools/create-alert-rule.jsnew file mode 100644index 000000000..d74dfc98c--- /dev/null+++ b/packages/alerts-mcp/src/tools/create-alert-rule.js@@ -0,0 +1,89 @@+// `create_alert_rule` — define a new pump.fun monitoring rule on the+// authenticated account. Write (appends a new rule — NOT idempotent: calling+// twice creates two rules).+//+// Wraps POST /api/alerts/rules. Cross-field requirements are enforced by the API+// and surfaced verbatim on a 400; the descriptions below state them so an agent+// gets the combination right the first time.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeRule } from '../lib/shapes.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const dropUndefined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));++export const def = {+ name: 'create_alert_rule',+ title: 'Create a pump.fun alert rule',+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'Create a pump.fun alert rule on the authenticated three.ws account. The pumpfun-monitor cron ' ++ 'evaluates it against the live event stream and delivers across the channels you enable, so it ' ++ 'fires across devices with no dashboard open. NOT idempotent — each call adds a new rule (max 50 ' ++ 'per account). Targeting by kind: `graduation` is global or scoped to target_mint OR target_agent; ' ++ '`price_above` / `price_below` / `whale_buy` require target_mint; `new_mint` requires target_agent. ' ++ '`threshold` is required for the price/whale kinds — USD market cap for price_above/price_below, ' ++ 'minimum buy size in SOL for whale_buy. At least one delivery channel must be on (deliver_in_app ' ++ 'defaults true; webhook_url must be https and gets a generated webhook_secret for signature ' ++ 'verification; telegram_chat is a numeric chat id or @username). Any mint you pass is runtime ' ++ 'input — three.ws promotes only $THREE. Returns the created rule. Requires THREE_WS_SESSION.',+ inputSchema: {+ kind: z+ .enum(['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint'])+ .describe('Event to watch: graduation | price_above | price_below | whale_buy | new_mint.'),+ target_mint: z+ .string()+ .regex(BASE58_RE, 'must be a base58 Solana mint address')+ .optional()+ .describe('Coin mint to watch. Required for price_above/price_below/whale_buy; optional for graduation; forbidden for new_mint.'),+ target_agent: z+ .string()+ .uuid()+ .optional()+ .describe('three.ws agent UUID to watch. Required for new_mint; optional for graduation; forbidden for the mint-targeted kinds.'),+ threshold: z+ .number()+ .positive()+ .optional()+ .describe('Required for price/whale kinds: USD market cap for price_above/price_below, minimum buy size in SOL for whale_buy. Ignored for graduation/new_mint.'),+ deliver_in_app: z.boolean().default(true).describe('Deliver as an in-app notification (default true).'),+ webhook_url: z+ .string()+ .url()+ .refine((u) => /^https:\/\//i.test(u), 'must be https')+ .optional()+ .describe('HTTPS endpoint to POST a signed alert event to. The response includes a generated webhook_secret for verifying the webhook-signature header.'),+ telegram_chat: z+ .string()+ .regex(/^(-?\d{1,32}|@[a-zA-Z0-9_]{4,64})$/, 'numeric chat id or @username')+ .optional()+ .describe('Telegram numeric chat id (e.g. 123456789) or @username to deliver to via the platform bot.'),+ cooldown_seconds: z+ .number()+ .int()+ .min(5)+ .max(86_400)+ .default(300)+ .describe('Minimum seconds between fires for this rule (5–86400, default 300).'),+ enabled: z.boolean().default(true).describe('Whether the rule is active (default true).'),+ label: z.string().max(80).optional().describe('Optional human label; a default is derived from kind/target when omitted.'),+ },+ async handler(args) {+ const body = dropUndefined({+ kind: args.kind,+ target_mint: args.target_mint,+ target_agent: args.target_agent,+ threshold: args.threshold,+ deliver_in_app: args.deliver_in_app,+ webhook_url: args.webhook_url,+ telegram_chat: args.telegram_chat,+ cooldown_seconds: args.cooldown_seconds,+ enabled: args.enabled,+ label: args.label,+ });+ const data = await apiRequest('/api/alerts/rules', { method: 'POST', auth: true, body });+ return { ok: true, rule: shapeRule(data?.rule) };+ },+};diff --git a/packages/alerts-mcp/src/tools/get-alert-history.js b/packages/alerts-mcp/src/tools/get-alert-history.jsnew file mode 100644index 000000000..44202a70a--- /dev/null+++ b/packages/alerts-mcp/src/tools/get-alert-history.js@@ -0,0 +1,63 @@+// `get_alert_history` — recent pump.fun alerts that actually fired for the+// authenticated account, with their delivery context. Read-only, account-scoped.+//+// Wraps GET /api/notifications?type=pump_alert. Every fired alert is persisted as+// a `pump_alert` notification whose payload IS the alert (kind, mint, amounts,+// market cap, tx, …). Optional client-side filters by rule_id / kind narrow the+// returned page; the API serves at most the 50 most recent pump alerts.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeAlert } from '../lib/shapes.js';++const API_MAX = 50;++export const def = {+ name: 'get_alert_history',+ title: 'Read fired pump.fun alert history',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read the pump.fun alerts that have actually fired for the authenticated account, newest first. ' ++ 'Each entry carries a one-line `summary`, the originating `rule_id`, the event `kind`, the coin ' ++ '(mint / name / symbol), whether it has been `read`, when it `fired_at`, and the full `event` ' ++ 'payload (amounts, market cap, tx signature, buyer, …). Pair this with list_alert_rules — whose ' ++ '`recent_deliveries` shows per-channel send outcomes — to see both what fired and how it was ' ++ 'delivered. Optionally filter to one rule (rule_id) or one kind. The feed returns at most the 50 ' ++ 'most recent alerts. Requires THREE_WS_SESSION.',+ inputSchema: {+ limit: z+ .number()+ .int()+ .min(1)+ .max(API_MAX)+ .default(20)+ .describe('Maximum number of fired alerts to return, newest first (1–50, default 20).'),+ rule_id: z+ .string()+ .uuid()+ .optional()+ .describe('Only return alerts fired by this rule id (matches the rule_id in each alert payload).'),+ kind: z+ .enum(['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint'])+ .optional()+ .describe('Only return alerts of this event kind.'),+ },+ async handler(args) {+ const limit = args?.limit ?? 20;+ const filtering = Boolean(args?.rule_id || args?.kind);+ // When filtering client-side, pull the full page so the filter isn't applied+ // to a pre-truncated slice; otherwise ask only for what the caller wants.+ const data = await apiRequest('/api/notifications', {+ auth: true,+ query: { type: 'pump_alert', limit: filtering ? API_MAX : limit },+ });++ let alerts = Array.isArray(data?.notifications) ? data.notifications.map(shapeAlert).filter(Boolean) : [];+ if (args?.rule_id) alerts = alerts.filter((a) => a.rule_id === args.rule_id);+ if (args?.kind) alerts = alerts.filter((a) => a.kind === args.kind);+ alerts = alerts.slice(0, limit);++ return { ok: true, count: alerts.length, unread_count: data?.unread_count ?? 0, alerts };+ },+};diff --git a/packages/alerts-mcp/src/tools/list-alert-rules.js b/packages/alerts-mcp/src/tools/list-alert-rules.jsnew file mode 100644index 000000000..b0bf901b9--- /dev/null+++ b/packages/alerts-mcp/src/tools/list-alert-rules.js@@ -0,0 +1,28 @@+// `list_alert_rules` — the authenticated account's pump.fun alert rules.+// Read-only, account-scoped.+//+// Wraps GET /api/alerts/rules.++import { apiRequest } from '../lib/api.js';+import { shapeRule } from '../lib/shapes.js';++export const def = {+ name: 'list_alert_rules',+ title: 'List my pump.fun alert rules',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List every pump.fun alert rule on the authenticated three.ws account. Each rule has a `kind` ' ++ '(graduation | price_above | price_below | whale_buy | new_mint), its target (target_mint or ' ++ 'target_agent), an optional numeric `threshold` (USD market cap for price rules, SOL for whale_buy), ' ++ 'the delivery channels (deliver_in_app, webhook_url + webhook_secret, telegram_chat), the cooldown, ' ++ 'and whether it is enabled. Also returns live delivery health: `last_fired_at`, `recent_failures` ' ++ '(failed channel deliveries in the last 24h), and `recent_deliveries` (the last few per-channel ' ++ 'outcomes). Use this to audit what an agent is watching before creating or editing rules. ' ++ 'Requires THREE_WS_SESSION.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/alerts/rules', { auth: true });+ const rules = Array.isArray(data?.rules) ? data.rules.map(shapeRule).filter(Boolean) : [];+ return { ok: true, count: rules.length, rules };+ },+};diff --git a/packages/alerts-mcp/src/tools/update-alert-rule.js b/packages/alerts-mcp/src/tools/update-alert-rule.jsnew file mode 100644index 000000000..fb9341217--- /dev/null+++ b/packages/alerts-mcp/src/tools/update-alert-rule.js@@ -0,0 +1,90 @@+// `update_alert_rule` — change an existing pump.fun alert rule on the+// authenticated account. Write, idempotent: re-applying the same patch leaves the+// rule in the same state.+//+// Wraps PATCH /api/alerts/rules/:id. Only the fields you pass change; everything+// else is left as-is. Clearable fields (target_mint, target_agent, threshold,+// webhook_url, telegram_chat, label) accept null to remove the value. The merged+// rule is re-validated by the API against its (possibly new) kind.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeRule } from '../lib/shapes.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const dropUndefined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));++export const def = {+ name: 'update_alert_rule',+ title: 'Update a pump.fun alert rule',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Update an existing pump.fun alert rule by id on the authenticated three.ws account. Partial — only ' ++ 'the fields you pass change. Idempotent: re-applying the same values yields the same rule. Common ' ++ 'uses: flip `enabled` to pause/resume, retune `threshold`, add or swap a delivery channel, or ' ++ 'change `kind` (the rule is re-validated against the new kind, and fields incompatible with it are ' ++ 'cleared automatically). Pass null to clear a clearable field (target_mint, target_agent, ' ++ 'threshold, webhook_url, telegram_chat, label). Removing webhook_url drops its secret; adding one ' ++ 'mints a fresh webhook_secret (returned). The result must still have at least one delivery channel ' ++ 'and satisfy the kind\'s targeting/threshold rules, or the API rejects it with a precise message. ' ++ 'Returns the updated rule. Requires THREE_WS_SESSION.',+ inputSchema: {+ rule_id: z.string().uuid().describe('Id of the rule to update (from list_alert_rules).'),+ kind: z+ .enum(['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint'])+ .optional()+ .describe('Change the event kind. The rule is re-validated against it and incompatible fields are cleared.'),+ target_mint: z+ .string()+ .regex(BASE58_RE, 'must be a base58 Solana mint address')+ .nullable()+ .optional()+ .describe('Coin mint to watch, or null to clear. Required by price/whale kinds; forbidden for new_mint.'),+ target_agent: z+ .string()+ .uuid()+ .nullable()+ .optional()+ .describe('three.ws agent UUID to watch, or null to clear. Required by new_mint; forbidden for mint-targeted kinds.'),+ threshold: z+ .number()+ .positive()+ .nullable()+ .optional()+ .describe('USD market cap (price kinds) or SOL buy size (whale_buy), or null to clear.'),+ deliver_in_app: z.boolean().optional().describe('Toggle in-app delivery.'),+ webhook_url: z+ .string()+ .url()+ .refine((u) => /^https:\/\//i.test(u), 'must be https')+ .nullable()+ .optional()+ .describe('HTTPS endpoint for signed alert events, or null to remove the webhook (and its secret).'),+ telegram_chat: z+ .string()+ .regex(/^(-?\d{1,32}|@[a-zA-Z0-9_]{4,64})$/, 'numeric chat id or @username')+ .nullable()+ .optional()+ .describe('Telegram numeric chat id or @username, or null to remove.'),+ cooldown_seconds: z+ .number()+ .int()+ .min(5)+ .max(86_400)+ .optional()+ .describe('Minimum seconds between fires (5–86400).'),+ enabled: z.boolean().optional().describe('Enable or pause the rule.'),+ label: z.string().max(80).nullable().optional().describe('Human label, or null to fall back to the derived default.'),+ },+ async handler(args) {+ const { rule_id, ...rest } = args;+ const body = dropUndefined(rest);+ const data = await apiRequest(`/api/alerts/rules/${encodeURIComponent(rule_id)}`, {+ method: 'PATCH',+ auth: true,+ body,+ });+ return { ok: true, rule: shapeRule(data?.rule) };+ },+};diff --git a/packages/audio-mcp/package.json b/packages/audio-mcp/package.jsonnew file mode 100644index 000000000..b7638a469--- /dev/null+++ b/packages/audio-mcp/package.json@@ -0,0 +1,59 @@+{+ "name": "@three-ws/audio-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/audio-mcp",+ "description": "Give 3D AI agents a voice and a face from any MCP client — text-to-speech, speech-to-text, audio-to-face lipsync (ARKit blendshapes), and the motion-capture clip library. Read-only over the live three.ws API; free NVIDIA lanes, no key required.",+ "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/audio-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "tts",+ "text-to-speech",+ "speech-to-text",+ "asr",+ "lipsync",+ "audio2face",+ "blendshapes",+ "motion-capture",+ "avatar"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "audio-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/audio-mcp/server.json b/packages/audio-mcp/server.jsonnew file mode 100644index 000000000..5c145e6dc--- /dev/null+++ b/packages/audio-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/audio-mcp",+ "title": "three.ws Audio",+ "description": "Text-to-speech, speech-to-text, audio-to-face lipsync, and the motion-capture clip library for 3D agents.",+ "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/audio-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/audio-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 audio/animation endpoints. Override only when self-hosting or targeting a preview deployment.",+ "format": "string",+ "isRequired": false,+ "default": "https://three.ws"+ },+ {+ "name": "THREE_WS_API_KEY",+ "description": "Optional three.ws API key (bearer token). Raises the metered TTS/ASR/Audio2Face rate limits and unlocks your own private/unlisted motion-capture clips. Leave unset to use the public surface anonymously.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "THREE_WS_TIMEOUT_MS",+ "description": "Per-request timeout in milliseconds for the live audio/animation calls (synthesis and recognition are real upstream model calls).",+ "format": "number",+ "isRequired": false,+ "default": "60000"+ }+ ]+ }+ ]+}diff --git a/packages/audio-mcp/src/index.js b/packages/audio-mcp/src/index.jsnew file mode 100644index 000000000..8d90a709a--- /dev/null+++ b/packages/audio-mcp/src/index.js@@ -0,0 +1,125 @@+#!/usr/bin/env node+// @three-ws/audio-mcp — MCP server entry point.+//+// The voice and animation layer for three.ws 3D agents over stdio:+// • text_to_speech — synthesize speech from text (free Magpie, OpenAI backstop)+// • speech_to_text — transcribe spoken audio (free NVIDIA Riva)+// • audio_to_face — turn speech into an ARKit blendshape lipsync track (Audio2Face-3D)+// • motion_capture_clips — browse the stored motion-capture clip library+// • motion_capture_clip — fetch one clip's full per-frame animation track+//+// A thin wrapper over the three.ws API. No on-chain signer. The TTS/ASR/A2F+// lanes are free and metered; an optional THREE_WS_API_KEY raises the rate+// limits and unlocks your own private mocap clips — without it the whole public+// surface still works. Point THREE_WS_BASE at a deployment and go.+//+// Run standalone:+// node packages/audio-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 textToSpeech } from './tools/text-to-speech.js';+import { def as speechToText } from './tools/speech-to-text.js';+import { def as audioToFace } from './tools/audio-to-face.js';+import { def as motionCaptureClips } from './tools/motion-capture-clips.js';+import { def as motionCaptureClip } from './tools/motion-capture-clip.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 = [+ textToSpeech,+ speechToText,+ audioToFace,+ motionCaptureClips,+ motionCaptureClip,+];++/**+ * 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: 'audio-mcp', title: 'three.ws Audio', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Audio MCP — give a 3D agent a voice and a face. text_to_speech synthesizes spoken audio from text ' ++ '(free NVIDIA Magpie, OpenAI backstop) and returns it as a base64 data URL. speech_to_text transcribes spoken ' ++ 'audio to text with the free NVIDIA Riva recognizer. audio_to_face turns speech — text you pass, or audio you ' ++ 'already have — into a per-frame ARKit blendshape lipsync track via Audio2Face-3D, so the avatar\'s mouth matches ' ++ 'the words. motion_capture_clips browses the stored motion-capture library (face/pose/hand/VMC) and ' ++ 'motion_capture_clip fetches one clip\'s full per-frame track to play back on an avatar. The synthesis/recognition ' ++ 'lanes are free and metered; set THREE_WS_API_KEY for higher limits and access to your own private mocap clips. ' ++ 'Every tool is read-only — they transform input or read live data, never mutating platform state.',+ },+ );++ 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(`[audio-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('[audio-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/audio-mcp/src/lib/api.js b/packages/audio-mcp/src/lib/api.jsnew file mode 100644index 000000000..5d1ac618e--- /dev/null+++ b/packages/audio-mcp/src/lib/api.js@@ -0,0 +1,145 @@+// Real HTTP access to the three.ws audio/animation 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.+//+// Two transports because the pipeline has two response shapes:+// • apiRequest() — JSON in / JSON out (ASR, A2F, mocap clips).+// • apiRequestBinary() — JSON in / raw audio bytes out (TTS speech synthesis,+// which streams the encoded clip with a truthful content-type, not JSON).+// Both share the same base URL, timeout, user-agent, optional bearer auth, and+// error normalization — one HTTP client, two read modes.++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT, THREE_WS_API_KEY } from '../config.js';++function buildUrl(path, query) {+ 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));+ }+ }+ return url;+}++function baseHeaders(extra) {+ return {+ 'user-agent': USER_AGENT,+ ...(THREE_WS_API_KEY ? { authorization: `Bearer ${THREE_WS_API_KEY}` } : {}),+ ...extra,+ };+}++// Map a fetch-layer failure (abort/network) onto the normalized error shape.+function transportError(err, path) {+ if (err?.name === 'AbortError') {+ return Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), {+ code: 'timeout',+ });+ }+ return Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), {+ code: 'network_error',+ });+}++/**+ * Call a three.ws JSON endpoint and return its parsed JSON body.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/asr`).+ * @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 = buildUrl(path, query);++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);++ let res;+ try {+ res = await fetch(url, {+ method,+ headers: baseHeaders({+ accept: 'application/json',+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ }),+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: controller.signal,+ });+ } catch (err) {+ clearTimeout(timer);+ throw transportError(err, path);+ }+ clearTimeout(timer);++ const text = await res.text();+ let data;+ try {+ data = text ? JSON.parse(text) : {};+ } catch {+ data = { raw: text };+ }++ if (!res.ok) {+ const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });+ }+ return data;+}++/**+ * Call a three.ws endpoint that returns raw bytes (audio) and return the buffer+ * plus the response metadata. On an error status the body is JSON — it is parsed+ * and surfaced through the same normalized error shape as apiRequest().+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/tts/speak`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]+ * @returns {Promise<{ buffer: Buffer, contentType: string, headers: Headers }>}+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error').+ */+export async function apiRequestBinary(path, { method = 'POST', query, body } = {}) {+ const url = buildUrl(path, query);++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);++ let res;+ try {+ res = await fetch(url, {+ method,+ headers: baseHeaders({+ accept: 'application/octet-stream, audio/*, application/json',+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ }),+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: controller.signal,+ });+ } catch (err) {+ clearTimeout(timer);+ throw transportError(err, path);+ }+ clearTimeout(timer);++ if (!res.ok) {+ // Error responses from the API are JSON ({ error, message }); parse for a+ // clean message rather than leaking raw bytes into the MCP client.+ let data;+ try {+ data = JSON.parse(await res.text());+ } catch {+ data = {};+ }+ const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });+ }++ const buffer = Buffer.from(await res.arrayBuffer());+ return {+ buffer,+ contentType: res.headers.get('content-type') || 'application/octet-stream',+ headers: res.headers,+ };+}diff --git a/packages/audio-mcp/src/tools/audio-to-face.js b/packages/audio-mcp/src/tools/audio-to-face.jsnew file mode 100644index 000000000..f33b01d03--- /dev/null+++ b/packages/audio-mcp/src/tools/audio-to-face.js@@ -0,0 +1,85 @@+// `audio_to_face` — turn speech into a per-frame facial-animation (lipsync)+// track for a 3D avatar. Read-only: it transforms audio (or text→audio) into a+// blendshape track and mutates no platform state.+//+// Wraps POST /api/a2f (NVIDIA NIM Audio2Face-3D, free). Two ways to call it:+// • Animate audio you already have — pass base64 `audio` (wav or pcm). The+// lips match the exact bytes you will play.+// • One-shot text→speech→animation — pass `text` and the server synthesizes+// the line with Magpie TTS, animates that exact clip, and returns BOTH the+// audio and the animation so you can play and drive in sync.+//+// The animation is { fps, blendShapeNames, frames, durationSec }, where each+// frame is { t, w }: t = seconds from clip start, w = weights in the order of+// blendShapeNames (ARKit-52 naming — map onto the loaded GLB's convention).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++const VOICES = ['nova', 'alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'onyx', 'sage', 'shimmer', 'verse'];+const FORMATS = ['wav', 'pcm'];++export const def = {+ name: 'audio_to_face',+ title: 'Audio to face (lipsync)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Generate a per-frame ARKit blendshape lipsync track from speech using free NVIDIA NIM Audio2Face-3D. Provide either `text` ' ++ '(the server synthesizes it with Magpie TTS, then animates that clip and returns both the audio and the animation) or `audio` ' ++ '(base64 wav/pcm you already have, so the lips match the exact bytes you will play). Returns { animation: { fps, blendShapeNames, ' ++ 'frames, durationSec } } where each frame is { t, w } — t in seconds, w = weights ordered by blendShapeNames (ARKit-52). On the text ' ++ 'path it also returns { audio: { base64, contentType, format } }. Read-only — produces an animation track without changing platform state.',+ inputSchema: {+ text: z+ .string()+ .min(1)+ .max(4096)+ .optional()+ .describe('Text to synthesize and animate (1–4096 chars). Provide this OR `audio`. On this path the synthesized audio is returned alongside the animation.'),+ audio: z+ .string()+ .min(1)+ .optional()+ .describe('Pre-synthesized audio to animate, base64-encoded (raw or a data: URL). Provide this OR `text`. Set `format` to match the bytes.'),+ format: z+ .enum(FORMATS)+ .optional()+ .describe('Encoding of `audio` (default "wav"). Use "pcm" for raw 16-bit little-endian PCM and set `sampleRate`.'),+ sampleRate: z+ .number()+ .int()+ .positive()+ .optional()+ .describe('Sample rate in Hz for raw PCM `audio` (default 16000). Ignored for WAV.'),+ voice: z+ .enum(VOICES)+ .optional()+ .describe('Voice for the text path (default "nova"). Ignored when `audio` is supplied.'),+ language: z+ .string()+ .optional()+ .describe('BCP-47 language for the text path (default "en-US"). Ignored when `audio` is supplied.'),+ },+ async handler(args) {+ const text = typeof args?.text === 'string' ? args.text.trim() : '';+ const audio = typeof args?.audio === 'string' ? args.audio.trim() : '';+ if (!text && !audio) {+ throw Object.assign(new Error('provide `text` to synthesize and animate, or `audio` (base64) to animate'), {+ code: 'bad_request',+ });+ }++ const body = audio+ ? { audio, format: args?.format, sampleRate: args?.sampleRate }+ : { text, voice: args?.voice, language: args?.language };++ const data = await apiRequest('/api/a2f', { method: 'POST', body });++ return {+ ok: true,+ ...(data?.audio ? { audio: data.audio } : {}),+ animation: data?.animation ?? null,+ };+ },+};diff --git a/packages/audio-mcp/src/tools/motion-capture-clip.js b/packages/audio-mcp/src/tools/motion-capture-clip.jsnew file mode 100644index 000000000..10254f715--- /dev/null+++ b/packages/audio-mcp/src/tools/motion-capture-clip.js@@ -0,0 +1,38 @@+// `motion_capture_clip` — fetch one motion-capture clip including its frames.+// Read-only.+//+// Wraps GET /api/mocap/clips/:id. Returns the full clip: metadata plus the+// per-frame track an avatar plays back. Each frame is { t, shapes, mat? } —+// t = seconds from clip start, shapes = a name→weight map (ARKit blendshapes for+// face clips; bone/joint channels for pose/hand/vmc), mat = an optional 16-float+// transform. Public/unlisted clips are readable anonymously; a private clip+// returns not_found unless THREE_WS_API_KEY identifies its owner.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'motion_capture_clip',+ title: 'Get a motion-capture clip',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Fetch a single motion-capture clip by id, including its full per-frame animation track. Returns { clip } with metadata plus ' ++ '`frames`: each frame is { t, shapes, mat? } — t in seconds, shapes a name→weight map (ARKit blendshapes for face clips; joint ' ++ 'channels for pose/hand/vmc), and an optional 16-float transform matrix. Use this to drive an avatar from a clip discovered via ' ++ 'motion_capture_clips. Public and unlisted clips are readable anonymously; a private clip needs THREE_WS_API_KEY for its owner. Read-only.',+ inputSchema: {+ id: z+ .string()+ .min(8)+ .describe('The clip id (UUID) returned by motion_capture_clips.'),+ },+ async handler(args) {+ const id = String(args?.id ?? '').trim();+ const data = await apiRequest(`/api/mocap/clips/${encodeURIComponent(id)}`);+ return {+ ok: true,+ clip: data?.clip ?? null,+ };+ },+};diff --git a/packages/audio-mcp/src/tools/motion-capture-clips.js b/packages/audio-mcp/src/tools/motion-capture-clips.jsnew file mode 100644index 000000000..9034236ec--- /dev/null+++ b/packages/audio-mcp/src/tools/motion-capture-clips.js@@ -0,0 +1,67 @@+// `motion_capture_clips` — browse the stored motion-capture clip library.+// Read-only.+//+// Wraps GET /api/mocap/clips. Mocap clips are recorded client-side (FaceMocap /+// pose / hand / VMC) and stored as a per-frame track; this lists the catalog so+// an agent can discover clips to drive an avatar with. Anonymous callers see+// public clips only; set THREE_WS_API_KEY to also see your own clips (use+// include_public to widen that back to "mine + public"). Frames are NOT included+// here — fetch a single clip with motion_capture_clip to get the track.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { THREE_WS_API_KEY } from '../config.js';++const KINDS = ['face', 'pose', 'hand', 'vmc'];++export const def = {+ name: 'motion_capture_clips',+ title: 'List motion-capture clips',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List motion-capture clips from the three.ws library — recorded face/pose/hand/VMC tracks an avatar can play back. Returns clip ' ++ 'metadata (id, slug, name, kind, format, duration_ms, frame_count, tags, visibility, play_count, price) but NOT the frames; fetch a ' ++ 'clip by id with motion_capture_clip to get the animation track. Anonymous callers see only public clips; set THREE_WS_API_KEY to ' ++ 'include your own. Cursor-paginated via next_cursor. Read-only live data.',+ inputSchema: {+ kind: z+ .enum(KINDS)+ .optional()+ .describe('Filter by capture kind: "face" (blendshapes), "pose" (body), "hand", or "vmc".'),+ include_public: z+ .boolean()+ .optional()+ .describe('When authenticated (THREE_WS_API_KEY set), return your clips AND public ones instead of just your own. Ignored anonymously (always public-only).'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(100)+ .optional()+ .describe('How many clips to return (1–100, default 50).'),+ cursor: z+ .string()+ .optional()+ .describe('Pagination cursor from a previous response\'s next_cursor.'),+ },+ async handler(args) {+ const query = {+ kind: args?.kind,+ limit: args?.limit,+ cursor: args?.cursor,+ ...(args?.include_public ? { include_public: 'true' } : {}),+ };++ const data = await apiRequest('/api/mocap/clips', { query });+ const items = Array.isArray(data?.items) ? data.items : [];++ return {+ ok: true,+ authenticated: Boolean(THREE_WS_API_KEY),+ count: items.length,+ next_cursor: data?.next_cursor ?? null,+ clips: items,+ };+ },+};diff --git a/packages/audio-mcp/src/tools/speech-to-text.js b/packages/audio-mcp/src/tools/speech-to-text.jsnew file mode 100644index 000000000..1632e5389--- /dev/null+++ b/packages/audio-mcp/src/tools/speech-to-text.js@@ -0,0 +1,77 @@+// `speech_to_text` — transcribe spoken audio to text. Read-only: it transforms+// audio → transcript and mutates no platform state.+//+// Wraps POST /api/asr (NVIDIA NIM Riva ASR, free). The audio is passed as a+// base64 string (a raw base64 payload or a data: URL — the data prefix is+// stripped server-side). Riva does NOT accept the WebM/Opus container that+// Chrome's MediaRecorder emits by default: decode to WAV or PCM first. Returns+// the transcript with a confidence score and the recognized duration.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++// Encodings the Riva lane accepts (see api/asr.js ACCEPTED_ENCODINGS).+const FORMATS = ['wav', 'pcm', 'flac', 'ogg'];++export const def = {+ name: 'speech_to_text',+ title: 'Speech to text',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Transcribe spoken audio to text using the free NVIDIA NIM Riva recognizer. Pass the audio as base64 (raw or a data: URL). ' ++ 'Accepted encodings: wav, pcm (set sampleRate), flac, ogg/opus — the WebM container from a browser MediaRecorder must be decoded ' ++ 'to WAV or PCM first. Returns { text, confidence, language, model, durationSec } and, when `words` is set, per-word timestamps. ' ++ 'Audio is capped at ~8 MB. Read-only — recognizes speech without changing any platform state.',+ inputSchema: {+ audio: z+ .string()+ .min(1)+ .describe('The audio to transcribe, base64-encoded (a raw base64 string or a data:<mime>;base64,… URL). Max ~8 MB decoded.'),+ format: z+ .enum(FORMATS)+ .optional()+ .describe('Audio encoding of the supplied bytes (default "wav"). Use "pcm" for raw 16-bit little-endian PCM (set sampleRate).'),+ language: z+ .string()+ .optional()+ .describe('BCP-47 language hint for recognition (default "en-US").'),+ sampleRate: z+ .number()+ .int()+ .positive()+ .optional()+ .describe('Sample rate in Hz for raw PCM input (default 16000). Ignored for WAV, which carries its own rate in the header.'),+ words: z+ .boolean()+ .optional()+ .describe('When true, also return per-word timestamps in a `words` array.'),+ model: z+ .string()+ .optional()+ .describe('Override the Riva model name (advanced; defaults to the configured model).'),+ },+ async handler(args) {+ const audio = String(args?.audio ?? '').trim();+ const body = {+ audio,+ format: args?.format,+ language: args?.language,+ sampleRate: args?.sampleRate,+ words: args?.words === true,+ model: args?.model,+ };++ const data = await apiRequest('/api/asr', { method: 'POST', body });++ return {+ ok: true,+ text: data?.text ?? '',+ confidence: data?.confidence ?? null,+ language: data?.language ?? (args?.language || 'en-US'),+ model: data?.model ?? null,+ durationSec: data?.durationSec ?? null,+ ...(Array.isArray(data?.words) ? { words: data.words } : {}),+ };+ },+};diff --git a/packages/audio-mcp/src/tools/text-to-speech.js b/packages/audio-mcp/src/tools/text-to-speech.jsnew file mode 100644index 000000000..fc98970c7--- /dev/null+++ b/packages/audio-mcp/src/tools/text-to-speech.js@@ -0,0 +1,82 @@+// `text_to_speech` — synthesize speech from text and return it as a base64+// audio data URL the client can play or hand to an avatar. Read-only: it+// transforms text → audio and mutates no platform state.+//+// Wraps POST /api/tts/speak, which streams raw encoded audio (not JSON) with a+// truthful content-type and x-tts-* headers. Provider policy is the platform's:+// free NVIDIA NIM Magpie leads, OpenAI is the paid backstop. Magpie emits PCM,+// so every non-pcm request is served as WAV — the returned mime/format always+// describe the actual bytes.++import { z } from 'zod';++import { apiRequestBinary } from '../lib/api.js';++// Mirrors api/_lib/tts-voices.js (TTS_VOICE_IDS) — a voice that renders on either+// the free Magpie lane or the OpenAI backstop.+const VOICES = ['nova', 'alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'onyx', 'sage', 'shimmer', 'verse'];+const MODELS = ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'];+const FORMATS = ['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm'];++export const def = {+ name: 'text_to_speech',+ title: 'Text to speech',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Synthesize spoken audio from text for a 3D avatar and return it as a base64 audio data URL (data:<mime>;base64,…) plus metadata. ' ++ 'Free NVIDIA NIM Magpie TTS leads; OpenAI is the paid backstop. Because Magpie emits raw PCM, every non-pcm request is served as WAV — ' ++ 'the returned `mime`, `format`, and `voice` describe the bytes you actually get, not the request. Pair the audio with audio_to_face to ' ++ 'drive lipsync. Input text is capped at 4096 characters. Read-only — synthesizes audio without changing any platform state.',+ inputSchema: {+ text: z+ .string()+ .min(1)+ .max(4096)+ .describe('The text to speak (1–4096 characters).'),+ voice: z+ .enum(VOICES)+ .optional()+ .describe('Voice persona (default "nova"). The same id renders on either provider lane.'),+ format: z+ .enum(FORMATS)+ .optional()+ .describe('Requested audio container (default "mp3"). The free NVIDIA lane serves every non-pcm request as WAV; the response metadata reports what you actually received.'),+ model: z+ .enum(MODELS)+ .optional()+ .describe('OpenAI TTS model for the paid backstop lane (default "gpt-4o-mini-tts"). Ignored by the free NVIDIA lane, which always uses magpie-tts-multilingual.'),+ language: z+ .string()+ .optional()+ .describe('BCP-47 language for the free NVIDIA lane (default "en-US"; also es-US, fr-FR, de-DE, zh-CN, vi-VN, it-IT, hi-IN, ja-JP).'),+ speed: z+ .number()+ .min(0.5)+ .max(2.0)+ .optional()+ .describe('Playback speed multiplier, 0.5–2.0 (OpenAI backstop lane only; default 1.0).'),+ },+ async handler(args) {+ const text = String(args?.text ?? '').trim();+ const body = {+ text,+ voice: args?.voice,+ format: args?.format,+ model: args?.model,+ language: args?.language,+ speed: args?.speed,+ };++ const { buffer, contentType, headers } = await apiRequestBinary('/api/tts/speak', { method: 'POST', body });++ return {+ ok: true,+ voice: headers.get('x-tts-voice') || args?.voice || 'nova',+ model: headers.get('x-tts-model') || null,+ format: headers.get('x-tts-format') || args?.format || 'mp3',+ mime: contentType,+ sizeBytes: buffer.length,+ audio: `data:${contentType};base64,${buffer.toString('base64')}`,+ };+ },+};diff --git a/packages/audio-mcp/test/registration.test.mjs b/packages/audio-mcp/test/registration.test.mjsnew file mode 100644index 000000000..f61c4ec14--- /dev/null+++ b/packages/audio-mcp/test/registration.test.mjs@@ -0,0 +1,73 @@+// Tool-surface invariants for @three-ws/audio-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/audio-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = [+ 'text_to_speech',+ 'speech_to_text',+ 'audio_to_face',+ 'motion_capture_clips',+ 'motion_capture_clip',+];++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 5);+ 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('every tool is a read-only, live-data transform', () => {+ for (const tool of TOOLS) {+ // These tools synthesize/recognize audio or read the clip library — they+ // transform input or read live data, never mutating platform state.+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ // Live synthesis/recognition/library reads are never idempotent — the+ // audio bytes, transcript, and catalog move between calls.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} is not idempotent`);+ }+});++test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++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`);+ }+});diff --git a/packages/billing-mcp/README.md b/packages/billing-mcp/README.mdnew file mode 100644index 000000000..7d105d476--- /dev/null+++ b/packages/billing-mcp/README.md@@ -0,0 +1,138 @@+<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/billing-mcp</h1>++<p align="center"><strong>An AI agent's own account economics over MCP — plan quotas, metered usage, invoices, receipts, and earnings. Read-only and account-scoped.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/billing-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/billing-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/billing-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/billing-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 lets an AI agent self-serve its **own** account economics over stdio: how much of its plan quota is left, what its metered usage rolled up to this period, the line-item invoice and per-charge receipts behind every charge, and the earnings its agents have made — all without pulling in the human account owner.++Every read hits the live three.ws billing API — nothing is mocked. The account-scoped reads run against the account **you own**, resolved from your three.ws session. This server is **read-only**: it surfaces private billing data but never signs, charges, or moves funds.++## Install++```bash+npm install @three-ws/billing-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/billing-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add billing -- npx -y @three-ws/billing-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "billing": {+ "command": "npx",+ "args": ["-y", "@three-ws/billing-mcp"],+ "env": {+ "THREE_WS_SESSION": "<your __Host-sid cookie>"+ }+ }+ }+}+```++`THREE_WS_SESSION` is required for every read except the public fee rate — it's the value of the `__Host-sid` cookie from a signed-in three.ws browser session, and the API uses it to resolve your account and return only your data.++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/billing-mcp+```++## Tools++| Tool | Type | What it does |+| -------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------- |+| `get_billing_summary` | read · session | Your plan tier, its quota ceilings, and live usage against them (avatars + storage, agents, MCP calls, LLM calls) + headroom. |+| `query_usage` | read · session | Metered usage rolled into an invoice statement for a period — per-action line items, totals, and reconciliation. |+| `export_billing_history` | read · session | The same line items as a ready-to-save CSV payload (with a suggested filename and a parsed preview). |+| `get_receipt` | read · session | One itemized receipt — per-charge by `event_id` (with settlement tx + explorer link) or a signed skill-purchase receipt by `purchase_id`. |+| `get_revenue` | read · session | Earnings for the agents you own — gross/fee/net, per-skill and over time, plus creator-subscription income. |+| `get_fee_info` | read · **public** | The current platform fee rate (`fee_bps` + `fee_percent`). Needs no session. |++Everything reads live state — usage, invoices, and earnings all move between calls — so no tool is idempotent, and nothing here mutates anything.++### Input parameters++**`get_billing_summary`** — none.++**`query_usage`** — `period` (YYYY-MM, optional), `from` / `to` (ISO-8601, optional; ignored when `period` is set). Defaults to the current UTC calendar month.++**`export_billing_history`** — `period`, `from`, `to` (same as `query_usage`), `preview_rows` (0–100, default 5 — how many parsed rows to echo in `preview`; the full CSV is always returned).++**`get_receipt`** — exactly one of `event_id` (numeric, per-charge receipt) or `purchase_id` (UUID, signed skill-purchase receipt).++**`get_revenue`** — `agent_id` (UUID, optional — narrow to one agent), `from` / `to` (ISO-8601, default last 30 days), `granularity` (`day` | `week` | `month`, default `day`).++**`get_fee_info`** — none.++## What you owe vs. what you earned++Two sides of the same account, two tools:++- **"What did this cost me?"** → `query_usage` / `export_billing_history` / `get_receipt` — metered charges, the period statement, and the receipt behind any single charge.+- **"What did my agents make?"** → `get_revenue` — gross/fee/net earnings, per-skill and over time, plus creator-subscription income.++`get_billing_summary` sits above both: your plan, its quota ceilings, and how much headroom is left.++## Money & units++- Charge amounts are in **USDC atomics** (6 decimals) alongside a human `*_usd` string — e.g. `gross_atomics: "150000"` is `gross_usd: "0.15"`.+- `get_revenue` earnings totals are in the **token's atomic units** (`currency_mint` / `chain` identify the token); creator-subscription income is reported separately in **USD** because it settles directly to your wallet, never mixing units with the withdrawable pool.+- `reconciliation` on the usage and revenue reads tells you whether every metered charge maps to a real on-chain settlement (`all_reconciled`, plus counts).++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default |+| ----------------------- | -------------------------------- | -------------------- |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |+| `THREE_WS_SESSION` | yes (all reads but `get_fee_info`) | — |++`THREE_WS_SESSION` is the value of the `__Host-sid` cookie from a signed-in three.ws browser session. Treat it like a password — it grants read access to your private billing data.++## Links++- 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/billing-mcp/package.json b/packages/billing-mcp/package.jsonnew file mode 100644index 000000000..35558aa99--- /dev/null+++ b/packages/billing-mcp/package.json@@ -0,0 +1,58 @@+{+ "name": "@three-ws/billing-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/billing-mcp",+ "description": "An AI agent's own account economics over MCP — plan quotas, metered usage, invoices, receipts, and earnings. Read-only, account-scoped. Powered by three.ws.",+ "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/billing-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "billing",+ "quotas",+ "usage",+ "invoices",+ "receipts",+ "metering",+ "ai-agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "billing-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/billing-mcp/server.json b/packages/billing-mcp/server.jsonnew file mode 100644index 000000000..4f784ddc4--- /dev/null+++ b/packages/billing-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/billing-mcp",+ "title": "three.ws Billing",+ "description": "An agent's own account economics — plan quotas, metered usage, invoices, receipts, and earnings. Read-only and account-scoped.",+ "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/billing-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/billing-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 billing endpoints. 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 three.ws API reads.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ },+ {+ "name": "THREE_WS_SESSION",+ "description": "Your three.ws session token (the value of the `__Host-sid` cookie from a signed-in browser). REQUIRED — it exposes private billing data, so every account-scoped read (get_billing_summary, query_usage, export_billing_history, get_receipt, get_revenue) resolves the calling user from it and returns only your data. Only the public get_fee_info works without it. Treat like a password.",+ "format": "string",+ "isRequired": true,+ "isSecret": true+ }+ ]+ }+ ]+}diff --git a/packages/billing-mcp/src/index.js b/packages/billing-mcp/src/index.jsnew file mode 100644index 000000000..a820ca93c--- /dev/null+++ b/packages/billing-mcp/src/index.js@@ -0,0 +1,130 @@+#!/usr/bin/env node+// @three-ws/billing-mcp — MCP server entry point.+//+// Gives an AI agent programmatic access to its OWN account economics over stdio:+// • get_billing_summary — plan tier, quota ceilings, and usage against them+// • query_usage — metered usage rolled into an invoice statement+// • export_billing_history — that statement as a downloadable CSV+// • get_receipt — one itemized receipt (per-charge or per-purchase)+// • get_revenue — earnings for the agents you own (the income side)+// • get_fee_info — the current platform fee rate (public)+//+// Every read hits the live three.ws API (THREE_WS_BASE). The account-scoped reads+// resolve the caller from your three.ws session (THREE_WS_SESSION) and return only+// your data; get_fee_info is public. This server only ever reads — it never signs+// or moves funds.+//+// Run standalone:+// node packages/billing-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 getBillingSummary } from './tools/billing-summary.js';+import { def as queryUsage } from './tools/query-usage.js';+import { def as exportBillingHistory } from './tools/export-billing-history.js';+import { def as getReceipt } from './tools/get-receipt.js';+import { def as getRevenue } from './tools/get-revenue.js';+import { def as getFeeInfo } from './tools/fee-info.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 = [+ getBillingSummary,+ queryUsage,+ exportBillingHistory,+ getReceipt,+ getRevenue,+ getFeeInfo,+];++/**+ * 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: 'billing-mcp', title: 'three.ws Billing', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Billing MCP — an agent’s own account economics, read-only. get_billing_summary returns your ' ++ 'plan tier, its quota ceilings, and live usage against them (avatars + storage, agents, MCP tool calls ' ++ 'in 24h, LLM calls this month) with a remaining-headroom map. query_usage rolls your metered usage into ' ++ 'an invoice statement for a period — per-action line items, totals, and a reconciliation summary; ' ++ 'export_billing_history returns the same as a downloadable CSV. get_receipt fetches one itemized ' ++ 'receipt, either a per-charge receipt by event_id (with its settlement tx + explorer link) or the ' ++ 'signed receipt JSON of a skill purchase by purchase_id. get_revenue is the income side — earnings for ' ++ 'the agents you own, broken down by skill and over time, plus creator-subscription income. get_fee_info ' ++ 'is the public platform fee rate. Every account-scoped read needs THREE_WS_SESSION (your `__Host-sid` ' ++ 'cookie); only get_fee_info is public. This server never signs or moves funds — it only reads.',+ },+ );++ 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(`[billing-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('[billing-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/billing-mcp/src/tools/export-billing-history.js b/packages/billing-mcp/src/tools/export-billing-history.jsnew file mode 100644index 000000000..8464beb2b--- /dev/null+++ b/packages/billing-mcp/src/tools/export-billing-history.js@@ -0,0 +1,102 @@+// `export_billing_history` — the same invoice line items as query_usage, but as a+// ready-to-save CSV payload. Account-scoped (session). Read-only.+//+// Wraps GET /api/billing/invoices?format=csv. The route streams the period's line+// items plus a TOTAL row as text/csv with a download filename. We return the raw+// CSV string (so the agent can write it to disk or attach it) alongside the+// suggested filename and a small parsed preview of the rows. Same period+// selection as query_usage (period=YYYY-MM, or from/to ISO; default current month).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++// Parse the CSV header + rows into objects for a structured preview. The API+// quotes the `label` field (which may contain commas), so split on commas that+// are not inside double quotes, then unescape doubled quotes.+function parseCsv(text) {+ const lines = String(text || '')+ .split('\n')+ .filter((l) => l.length > 0);+ if (lines.length === 0) return { header: [], rows: [] };+ const splitRow = (line) => {+ const cells = line.match(/("(?:[^"]|"")*"|[^,]*)(?:,|$)/g) || [];+ // The regex yields a trailing empty match for the line end — drop it.+ if (cells.length && cells[cells.length - 1] === '') cells.pop();+ return cells.map((c) => {+ let v = c.replace(/,$/, '');+ if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1).replace(/""/g, '"');+ return v;+ });+ };+ const header = splitRow(lines[0]);+ const rows = lines.slice(1).map((l) => {+ const cells = splitRow(l);+ return Object.fromEntries(header.map((h, i) => [h, cells[i] ?? '']));+ });+ return { header, rows };+}++export const def = {+ name: 'export_billing_history',+ title: 'Export my billing history as CSV',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Export a billing period\'s usage line items as a ready-to-save CSV — the same charges query_usage returns, ' ++ 'in spreadsheet form. Returns `filename` (suggested download name, e.g. three-ws-invoice-2026-06.csv), ' ++ '`content_type` (text/csv), `csv` (the full CSV text, columns: action,label,count,units,gross_usd,fee_usd,' ++ 'discount_bps with a trailing TOTAL row), `row_count`, and `preview` (the first few parsed rows as objects ' ++ 'for a quick look). Same period selection as query_usage: pass `period` (YYYY-MM) or `from`/`to` (ISO-8601); ' ++ 'defaults to the current UTC calendar month. Requires THREE_WS_SESSION. Read-only.',+ inputSchema: {+ period: z+ .string()+ .regex(/^\d{4}-\d{2}$/, 'period must be YYYY-MM')+ .optional()+ .describe('A calendar month as YYYY-MM (e.g. 2026-06). Takes precedence over from/to. Omit for the current month.'),+ from: z+ .string()+ .optional()+ .describe('Window start, ISO-8601. Ignored when `period` is set.'),+ to: z+ .string()+ .optional()+ .describe('Window end (exclusive), ISO-8601. Ignored when `period` is set.'),+ preview_rows: z+ .number()+ .int()+ .min(0)+ .max(100)+ .default(5)+ .describe('How many parsed line-item rows to include in `preview` (0–100, default 5). The full CSV is always returned in `csv`.'),+ },+ async handler(args) {+ const query = { format: 'csv' };+ if (args?.period) query.period = args.period;+ else {+ if (args?.from) query.from = args.from;+ if (args?.to) query.to = args.to;+ }++ const { contentType, text } = await apiRequest('/api/billing/invoices', {+ auth: true,+ query,+ accept: 'text/csv',+ raw: true,+ });++ const { rows } = parseCsv(text);+ const previewN = args?.preview_rows ?? 5;+ // Derive the canonical filename the API offers; fall back to the period label.+ const label = args?.period || (args?.from || args?.to ? 'custom' : 'current');++ return {+ ok: true,+ filename: `three-ws-invoice-${label}.csv`,+ content_type: contentType || 'text/csv',+ row_count: rows.length,+ preview: rows.slice(0, previewN),+ csv: text,+ };+ },+};diff --git a/packages/billing-mcp/src/tools/fee-info.js b/packages/billing-mcp/src/tools/fee-info.jsnew file mode 100644index 000000000..3354d9dc5--- /dev/null+++ b/packages/billing-mcp/src/tools/fee-info.js@@ -0,0 +1,26 @@+// `get_fee_info` — the current platform fee rate. Public, no auth. Read-only.+//+// Wraps GET /api/billing/fee-info. The platform's cut on marketplace sales, used+// to reason about net vs gross before a charge settles. This is the one read on+// this server that needs no session — it returns no private data.++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_fee_info',+ title: 'Current platform fee rate',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'The current three.ws platform fee rate — the cut taken on marketplace sales, so an agent can reason about ' ++ 'net vs gross before a charge settles. Returns `fee_bps` (basis points, e.g. 250 = 2.5%) and `fee_percent` ' ++ '(the same rate as a human string, e.g. "2.5"). Public — needs no session or credential. Read-only.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/billing/fee-info');+ return {+ ok: true,+ fee_bps: data?.fee_bps ?? null,+ fee_percent: data?.fee_percent ?? null,+ };+ },+};diff --git a/packages/billing-mcp/src/tools/get-receipt.js b/packages/billing-mcp/src/tools/get-receipt.jsnew file mode 100644index 000000000..ceedb1f67--- /dev/null+++ b/packages/billing-mcp/src/tools/get-receipt.js@@ -0,0 +1,60 @@+// `get_receipt` — a single itemized receipt, by charge or by skill purchase.+// Account-scoped (session). Read-only.+//+// Wraps GET /api/billing/receipts. Two receipt forms, both owner-gated:+// • event_id — a per-CHARGE receipt from the usage ledger: action, units,+// price, fee, holder discount, the settlement tx (+ explorer+// link), and the timestamp.+// • purchase_id — the signed receipt JSON for a confirmed skill purchase.+// Exactly one of the two must be supplied.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_receipt',+ title: 'Get one receipt (per-charge or per-purchase)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Fetch a single itemized receipt you own, in one of two forms. Pass `event_id` (numeric, from a usage ' ++ 'line item) for a per-CHARGE receipt: action, label, units, gross_usd / fee_usd / net (with USDC atomics), ' ++ 'discount_bps + discount_percent, and a `settlement` block (kind, ref, tx_signature, network, explorer_url, ' ++ 'token_price_usd) plus issued_at. Pass `purchase_id` (UUID) instead for the cryptographically SIGNED receipt ' ++ 'JSON of a confirmed skill purchase (receipt + signature + issued_at). Supply exactly one. Returns the ' ++ '`receipt` object and which `kind` ("charge" | "purchase") it is. Requires THREE_WS_SESSION. Read-only.',+ inputSchema: {+ event_id: z+ .union([z.number().int().nonnegative(), z.string().regex(/^\d+$/, 'event_id must be numeric')])+ .optional()+ .describe('Numeric usage-event id for a per-charge receipt (from a query_usage line item). Mutually exclusive with purchase_id.'),+ purchase_id: z+ .string()+ .uuid('purchase_id must be a UUID')+ .optional()+ .describe('UUID of a confirmed skill purchase for its signed receipt JSON. Mutually exclusive with event_id.'),+ },+ async handler(args) {+ const eventId = args?.event_id;+ const purchaseId = args?.purchase_id;++ const hasEvent = eventId !== undefined && eventId !== null && String(eventId) !== '';+ const hasPurchase = !!purchaseId;++ if (hasEvent === hasPurchase) {+ throw Object.assign(+ new Error('Provide exactly one of `event_id` (per-charge receipt) or `purchase_id` (per-purchase receipt).'),+ { code: 'bad_request', status: 400 },+ );+ }++ const query = hasEvent ? { event_id: String(eventId) } : { purchase_id: purchaseId };+ const data = await apiRequest('/api/billing/receipts', { auth: true, query });++ return {+ ok: true,+ kind: hasEvent ? 'charge' : 'purchase',+ receipt: data?.data ?? null,+ };+ },+};diff --git a/packages/billing-mcp/src/tools/get-revenue.js b/packages/billing-mcp/src/tools/get-revenue.jsnew file mode 100644index 000000000..8e3c7fa99--- /dev/null+++ b/packages/billing-mcp/src/tools/get-revenue.js@@ -0,0 +1,67 @@+// `get_revenue` — earnings for the agents you own: the income side of billing.+// Account-scoped (session). Read-only.+//+// Wraps GET /api/billing/revenue. Aggregates agent_revenue_events for your+// agents over a window into gross/fee/net totals, a per-skill breakdown, and a+// time series at day/week/month granularity. Also surfaces creator-subscription+// income (USD, settled directly to your wallet — kept separate from the+// withdrawable pool) and a reconciliation summary.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_revenue',+ title: 'My agents’ earnings (revenue + subscriptions)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Earnings for the agents YOU own — the income side of your account economics (what you EARNED, vs what you ' ++ 'were charged in query_usage). Returns `summary` (gross_total, fee_total, net_total in token atomics, ' ++ 'plus payment_count, currency_mint, chain), `by_skill` (net_total + count per skill, top first), ' ++ '`timeseries` (net_total + count bucketed by granularity), `subscriptions` (creator-subscription income in ' ++ 'USD — income_usd, payment_count, active_subscribers, plan_count — settled directly to your wallet, kept ' ++ 'separate from the withdrawable pool so units never mix), `subscription_timeseries`, and `reconciliation`. ' ++ 'Optional `agent_id` narrows to one agent; `from`/`to` set the window (default last 30 days); `granularity` ' ++ 'is day | week | month (default day). Requires THREE_WS_SESSION. Read-only.',+ inputSchema: {+ agent_id: z+ .string()+ .uuid('agent_id must be a UUID')+ .optional()+ .describe('Limit to a single agent you own (UUID). Omit to aggregate across all your agents.'),+ from: z+ .string()+ .optional()+ .describe('Window start, ISO-8601. Defaults to 30 days ago.'),+ to: z+ .string()+ .optional()+ .describe('Window end, ISO-8601. Defaults to now.'),+ granularity: z+ .enum(['day', 'week', 'month'])+ .default('day')+ .describe('Time-series bucket size (default day).'),+ },+ async handler(args) {+ const data = await apiRequest('/api/billing/revenue', {+ auth: true,+ query: {+ agent_id: args?.agent_id,+ from: args?.from,+ to: args?.to,+ granularity: args?.granularity ?? 'day',+ },+ });++ return {+ ok: true,+ summary: data?.summary ?? null,+ by_skill: Array.isArray(data?.by_skill) ? data.by_skill : [],+ timeseries: Array.isArray(data?.timeseries) ? data.timeseries : [],+ subscriptions: data?.subscriptions ?? null,+ subscription_timeseries: Array.isArray(data?.subscription_timeseries) ? data.subscription_timeseries : [],+ reconciliation: data?.reconciliation ?? null,+ };+ },+};diff --git a/packages/billing-mcp/test/registration.test.mjs b/packages/billing-mcp/test/registration.test.mjsnew file mode 100644index 000000000..b7bc4bb2c--- /dev/null+++ b/packages/billing-mcp/test/registration.test.mjs@@ -0,0 +1,88 @@+// Tool-surface invariants for @three-ws/billing-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 session.+// These tests run offline — they never touch the network.+//+// Run: node --test packages/billing-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = [+ 'get_billing_summary',+ 'query_usage',+ 'export_billing_history',+ 'get_receipt',+ 'get_revenue',+ 'get_fee_info',+];++// This server is read-only by design: it exposes private billing data but never+// signs or moves funds. Adding a write tool? Add it here deliberately, same+// commit, and give it readOnlyHint:false.+const WRITE_TOOLS = new Set();++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, EXPECTED_NAMES.length);+ assert.deepEqual(new Set(TOOLS.map((t) => t.name)), new Set(EXPECTED_NAMES));+ assert.equal(new Set(TOOLS.map((t) => t.name)).size, EXPECTED_NAMES.length, 'tool names must be unique');+});++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('every tool is a read-only live query', () => {+ for (const tool of TOOLS) {+ const isWrite = WRITE_TOOLS.has(tool.name);+ assert.equal(tool.annotations.readOnlyHint, !isWrite, `${tool.name} readOnlyHint should be ${!isWrite}`);+ // Everything talks to the live three.ws API; nothing is idempotent — plan+ // usage, invoices, and earnings all move between calls.+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} is never idempotent`);+ }+});++test('read-only tools omit destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ if (tool.annotations.readOnlyHint === true) {+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+ }+});++test('no write tools on this server (it never signs or moves funds)', () => {+ assert.equal(WRITE_TOOLS.size, 0, 'billing-mcp is read-only by design');+ for (const tool of TOOLS) {+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} must be read-only`);+ }+});++test('buildServer registers every tool with its annotations, without a session', () => {+ 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`);+ }+});diff --git a/packages/brain-mcp/README.md b/packages/brain-mcp/README.mdnew file mode 100644index 000000000..1c598c096--- /dev/null+++ b/packages/brain-mcp/README.md@@ -0,0 +1,163 @@+<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/brain-mcp</h1>++<p align="center"><strong>Any model, one interface — discover LLM providers and run chat completions through the three.ws multi-provider router, from any AI agent.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/brain-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/brain-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/brain-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/brain-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 gives any AI assistant the three.ws **multi-provider LLM router** over stdio. Discover which models are available — Claude, GPT-4o, o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — and run a chat completion through whichever one fits, without wiring each vendor SDK yourself.++The router fronts every provider behind one endpoint and transparently falls back across mirrors and free tiers if the chosen model is briefly down. The free open-weight tiers (GPT-OSS 120B, NVIDIA NIM models) work with **no key**; the paid first-party flagships unlock with a three.ws API key.++## Install++```bash+npm install @three-ws/brain-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/brain-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add brain -- npx -y @three-ws/brain-mcp+```++To unlock the paid flagships, pass your three.ws API key:++```bash+claude mcp add brain -e THREE_WS_API_KEY=sk_live_… -- npx -y @three-ws/brain-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "brain": {+ "command": "npx",+ "args": ["-y", "@three-ws/brain-mcp"],+ "env": { "THREE_WS_API_KEY": "sk_live_…" }+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/brain-mcp+```++## Tools++| Tool | Type | What it does |+| ---------------- | --------- | ------------------------------------------------------------------------------------------------------------------ |+| `list_providers` | read-only | List every LLM the router can reach — key, network, tier, max output, live availability, and whether it needs auth. |+| `chat` | read-only | Run a chat completion through the chosen provider; returns the full reply, the route taken, token usage, and timing. |++Both tools read live data — the provider set and completions vary between calls, so neither is idempotent. `chat` does not mutate any platform state, so it is annotated read-only.++### Input parameters++**`list_providers`** — no parameters.++**`chat`** — `messages` (required: array of `{ role: "user" | "assistant", content }`), `provider` (provider key from `list_providers`, default `gpt-oss-120b`), `system` (optional system prompt), `maxTokens` (optional, 64–16384, clamped to the model's ceiling).++## Example++```jsonc+// list_providers+> {}+{+ "ok": true,+ "count": 18,+ "available": 11,+ "default_provider": "gpt-oss-120b",+ "providers": [+ { "key": "gpt-oss-120b", "label": "GPT-OSS 120B", "network": "OpenAI · OpenRouter", "tier": "balanced", "maxOutput": 8192, "available": true, "requiresAuth": false },+ { "key": "claude-sonnet-4-6", "label": "Claude Sonnet 4.6", "network": "Anthropic", "tier": "balanced", "maxOutput": 16384, "available": true, "requiresAuth": true },+ { "key": "deepseek-r1", "label": "DeepSeek R1", "network": "DeepSeek", "tier": "reasoning", "maxOutput": 8192, "available": true, "requiresAuth": true }+ /* … */+ ]+}+```++```jsonc+// chat+> {+ "provider": "claude-sonnet-4-6",+ "system": "You are terse.",+ "messages": [{ "role": "user", "content": "Name three Solana RPC methods." }]+ }+{+ "ok": true,+ "provider": "claude-sonnet-4-6",+ "model": "Claude Sonnet 4.6",+ "network": "Anthropic",+ "tier": "balanced",+ "routed_via": null,+ "content": "getBalance, getAccountInfo, getSignaturesForAddress.",+ "usage": { "input_tokens": 24, "output_tokens": 14, "total_tokens": 38 },+ "timing_ms": { "first_token": 412, "total": 980 }+}+```++`routed_via` is `null` when the requested provider answered directly; otherwise it names the mirror or free-tier route the router fell back to (so you always get an answer even if the first choice is briefly down).++> Model availability is dynamic. Always call `list_providers` first rather than hardcoding a key — the current Claude ids are `claude-fable-5`, `claude-opus-4-7`, `claude-sonnet-4-6`, and `claude-haiku-4-5`, but the live list is the source of truth.++## Authentication++| Model class | Needs a key? |+| ---------------------------------------------------------------------------- | --------------------------- |+| Free open-weight tiers (GPT-OSS 120B, NVIDIA NIM: Nemotron / Kimi / Llama 4) | No |+| Paid first-party flagships (Claude, GPT-4o, o3, Qwen Plus, DeepSeek, …) | Yes — set `THREE_WS_API_KEY` |++Create an API key at [three.ws/account](https://three.ws/account). Without it, paid models return a sign-in error and `list_providers` flags them with `requiresAuth: true`.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default | Purpose |+| --------------------- | -------- | ------------------ | ---------------------------------------------------------------- |+| `THREE_WS_BASE` | no | `https://three.ws` | API base URL (override to self-host or target a preview). |+| `THREE_WS_API_KEY` | no | — | Bearer credential that unlocks the paid first-party flagships. |+| `THREE_WS_TIMEOUT_MS` | no | `120000` | Per-request timeout (completions stream server-side). |++## Links++- 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/brain-mcp/src/index.js b/packages/brain-mcp/src/index.jsnew file mode 100644index 000000000..2fce0e927--- /dev/null+++ b/packages/brain-mcp/src/index.js@@ -0,0 +1,115 @@+#!/usr/bin/env node+// @three-ws/brain-mcp — MCP server entry point.+//+// "Any model, one interface." Gives any AI assistant the three.ws multi-provider+// LLM router over stdio:+// • list_providers — discover the providers/models the router can reach+// • chat — run a chat completion through whichever one fits+//+// A thin wrapper over the three.ws API (POST /api/brain/chat). The route fronts+// Claude, GPT-4o, o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more, and+// auto-falls-back across mirrors/free tiers on an upstream outage. The free+// open-weight tiers need no key; paid first-party flagships unlock with a+// three.ws API key (THREE_WS_API_KEY).+//+// Run standalone:+// node packages/brain-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 listProviders } from './tools/list-providers.js';+import { def as chat } from './tools/chat.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 = [listProviders, chat];++/**+ * 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: 'brain-mcp', title: 'three.ws Brain', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Brain MCP — any model, one interface. list_providers discovers every LLM the router can ' ++ 'run a completion through (Claude, GPT-4o, o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and ' ++ 'more), each with its key, network, tier, max output, live availability, and whether it needs auth. ' ++ 'chat runs a completion through the chosen provider and returns the full reply as one message, plus ' ++ 'the route actually taken, token usage, and timing — the router transparently falls back across ' ++ 'mirrors and free tiers if the requested model is briefly down. Free open-weight tiers (GPT-OSS ' ++ '120B, NVIDIA NIM models) need no key; paid first-party flagships need a three.ws API key set as ' ++ 'THREE_WS_API_KEY. Call list_providers first to choose a provider key. Both tools are read-only.',+ },+ );++ 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(`[brain-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('[brain-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/brain-mcp/src/lib/api.js b/packages/brain-mcp/src/lib/api.jsnew file mode 100644index 000000000..7fc7c3353--- /dev/null+++ b/packages/brain-mcp/src/lib/api.js@@ -0,0 +1,237 @@+// Real HTTP access to the three.ws 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, THREE_WS_API_KEY } from '../config.js';++// Shared request headers. The optional bearer credential authenticates the+// caller so the router will serve the paid first-party flagships (the free+// open-weight tiers are served without it). One auth source, no second client.+function authHeaders(extra = {}) {+ return {+ 'user-agent': USER_AGENT,+ ...(THREE_WS_API_KEY ? { authorization: `Bearer ${THREE_WS_API_KEY}` } : {}),+ ...extra,+ };+}++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/brain/chat`).+ * @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: authHeaders({+ accept: 'application/json',+ ...(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) {+ const message =+ data?.error_description || data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });+ }+ return data;+}++/**+ * POST to the streaming /api/brain/chat router and collapse its Server-Sent+ * Events into a single completion. MCP tool results are one payload, so we+ * consume the whole stream server-side — accumulating the text deltas, the+ * `meta` (provider/label/network/tier), any `fallback` route the router took,+ * timing, and the final `usage` — and return the finished message.+ *+ * SSE protocol emitted by api/brain/chat:+ * event: meta → { provider, label, network, tier }+ * event: first → { firstTokenMs }+ * (data-only) → a JSON-encoded text chunk+ * event: fallback → { route } (router rerouted around an upstream outage)+ * event: done → { elapsedMs, firstTokenMs, usage }+ * event: error → { message, elapsedMs }+ * data: [DONE]+ *+ * @param {{ provider: string, messages: Array<{role:string,content:string}>, system?: string, maxTokens?: number }} body+ * @returns {Promise<{ text: string, meta: object|null, usage: object|null, timing: object, fallbackRoute: string|null }>}+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error').+ */+export async function streamBrainChat(body) {+ const url = `${THREE_WS_BASE}/api/brain/chat`;++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);++ let res;+ try {+ res = await fetch(url, {+ method: 'POST',+ headers: authHeaders({ accept: 'text/event-stream', 'content-type': 'application/json' }),+ body: JSON.stringify(body),+ signal: controller.signal,+ });+ } catch (err) {+ clearTimeout(timer);+ if (err?.name === 'AbortError') {+ throw Object.assign(new Error(`three.ws /api/brain/chat timed out after ${HTTP_TIMEOUT_MS}ms`), {+ code: 'timeout',+ });+ }+ throw Object.assign(new Error(`three.ws /api/brain/chat request failed: ${err?.message || err}`), {+ code: 'network_error',+ });+ }++ // A request the router rejects before streaming (unknown provider, sign-in+ // required, no key configured, rate limited) comes back as a non-200 JSON+ // body — not SSE. Normalize it the same way apiRequest does.+ if (!res.ok || !res.body) {+ clearTimeout(timer);+ const raw = await res.text().catch(() => '');+ let data;+ try {+ data = raw ? JSON.parse(raw) : {};+ } catch {+ data = { raw };+ }+ const message =+ data?.error_description || data?.message || data?.error || `three.ws /api/brain/chat returned HTTP ${res.status}`;+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ let chunks = '';+ let meta = null;+ let usage = null;+ let fallbackRoute = null;+ let firstTokenMs = null;+ let elapsedMs = null;+ let streamError = null;++ // Dispatch one parsed SSE event (event name + joined data payload).+ const dispatch = (eventName, data) => {+ if (data === '' || data === '[DONE]') return;+ // Data-only events (no `event:` line) are the visible text chunks: each is+ // a JSON-encoded string fragment of the model's reply.+ if (!eventName || eventName === 'message') {+ try {+ const piece = JSON.parse(data);+ if (typeof piece === 'string') chunks += piece;+ } catch {+ // Non-JSON data line — ignore rather than corrupt the transcript.+ }+ return;+ }+ let payload;+ try {+ payload = JSON.parse(data);+ } catch {+ return;+ }+ if (eventName === 'meta') meta = payload;+ else if (eventName === 'first') firstTokenMs = payload?.firstTokenMs ?? firstTokenMs;+ else if (eventName === 'fallback') fallbackRoute = payload?.route ?? fallbackRoute;+ else if (eventName === 'done') {+ usage = payload?.usage ?? null;+ elapsedMs = payload?.elapsedMs ?? elapsedMs;+ firstTokenMs = payload?.firstTokenMs ?? firstTokenMs;+ } else if (eventName === 'error') {+ streamError = payload?.message || 'upstream stream error';+ }+ };++ // Parse a complete SSE block (the lines between blank-line separators).+ const flushBlock = (block) => {+ if (!block.trim()) return;+ let eventName = null;+ const dataLines = [];+ for (const line of block.split('\n')) {+ if (line.startsWith('event:')) eventName = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));+ }+ if (dataLines.length || eventName) dispatch(eventName, dataLines.join('\n'));+ };++ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ // SSE events are separated by a blank line. Process every complete block;+ // keep the trailing partial in the buffer for the next read.+ let sep;+ while ((sep = buf.indexOf('\n\n')) !== -1) {+ flushBlock(buf.slice(0, sep));+ buf = buf.slice(sep + 2);+ }+ }+ flushBlock(buf);+ } catch (err) {+ if (err?.name === 'AbortError') {+ throw Object.assign(new Error(`three.ws /api/brain/chat timed out after ${HTTP_TIMEOUT_MS}ms`), {+ code: 'timeout',+ });+ }+ throw Object.assign(new Error(`three.ws /api/brain/chat stream failed: ${err?.message || err}`), {+ code: 'network_error',+ });+ } finally {+ clearTimeout(timer);+ }++ // The router emits an `error` event only when no token streamed — surface it+ // as an upstream error so the caller doesn't mistake an empty reply for success.+ if (streamError && !chunks) {+ throw Object.assign(new Error(streamError), { code: 'upstream_error', status: 502 });+ }++ return {+ text: chunks,+ meta,+ usage,+ fallbackRoute,+ timing: { firstTokenMs, elapsedMs },+ };+}diff --git a/packages/brain-mcp/src/tools/chat.js b/packages/brain-mcp/src/tools/chat.jsnew file mode 100644index 000000000..6afb2e339--- /dev/null+++ b/packages/brain-mcp/src/tools/chat.js@@ -0,0 +1,92 @@+// `chat` — run a chat completion through the three.ws multi-provider router. Read-only.+//+// Wraps POST /api/brain/chat. The route streams Server-Sent Events; an MCP tool+// result is a single payload, so lib/streamBrainChat accumulates the stream+// server-side and we return the finished message plus the route metadata,+// token usage, and timing the router reported.++import { z } from 'zod';++import { streamBrainChat } from '../lib/api.js';++const messageSchema = z.object({+ role: z.enum(['user', 'assistant']).describe('Who authored the turn.'),+ content: z.string().min(1).max(16000).describe('The turn text.'),+});++export const def = {+ name: 'chat',+ title: 'Run a chat completion',+ // Running a completion returns generated text; it does not mutate any+ // three.ws platform state — hence read-only. Open-world (live model), and+ // not idempotent (the same messages yield different generations each call).+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Run a chat completion through the three.ws LLM router and get back the full reply as a single message. ' ++ 'Pick `provider` from `list_providers` (default `gpt-oss-120b`, a free open-weight model). `messages` is ' ++ 'the conversation so far (roles `user`/`assistant`); add system instructions via `system`. The route ' ++ 'streams and auto-falls-back across mirrors/free tiers if the chosen model is briefly down — this tool ' ++ 'collapses that into one reply and reports the actual route taken, token usage, and timing. ' ++ 'Paid first-party flagships (Claude, GPT-4o, o3, Qwen Plus, DeepSeek) need a three.ws API key ' ++ '(set THREE_WS_API_KEY); the free open-weight tiers (GPT-OSS 120B, NVIDIA NIM models) need none. ' ++ 'Read-only: a completion does not change any platform state.',+ inputSchema: {+ messages: z+ .array(messageSchema)+ .min(1)+ .max(100)+ .describe('Conversation turns in order, each { role: "user"|"assistant", content }. At least one.'),+ provider: z+ .string()+ .min(1)+ .optional()+ .describe('Provider/model key from list_providers (e.g. "claude-sonnet-4-6", "gpt-4o", "deepseek-r1"). Defaults to "gpt-oss-120b".'),+ system: z+ .string()+ .max(8000)+ .optional()+ .describe('Optional system prompt / instructions prepended to the conversation.'),+ maxTokens: z+ .number()+ .int()+ .min(64)+ .max(16384)+ .optional()+ .describe('Maximum output tokens. Clamped to the chosen model’s ceiling by the router. Defaults to 4096.'),+ },+ async handler(args) {+ const provider = String(args?.provider || 'gpt-oss-120b').trim();+ const messages = (Array.isArray(args?.messages) ? args.messages : []).map((m) => ({+ role: m?.role === 'assistant' ? 'assistant' : 'user',+ content: String(m?.content ?? ''),+ }));+ const body = { provider, messages };+ if (typeof args?.system === 'string' && args.system.trim()) body.system = args.system;+ if (Number.isFinite(args?.maxTokens)) body.maxTokens = Math.trunc(args.maxTokens);++ const { text, meta, usage, fallbackRoute, timing } = await streamBrainChat(body);++ return {+ ok: true,+ provider: meta?.provider ?? provider,+ model: meta?.label ?? null,+ network: meta?.network ?? null,+ tier: meta?.tier ?? null,+ // The route the answer actually came from. null when the requested+ // provider served it directly; otherwise the mirror/free-tier fallback.+ routed_via: fallbackRoute,+ content: text,+ usage: usage+ ? {+ input_tokens: usage.inputTokens ?? null,+ output_tokens: usage.outputTokens ?? null,+ total_tokens: usage.totalTokens ?? null,+ }+ : null,+ timing_ms: {+ first_token: timing?.firstTokenMs ?? null,+ total: timing?.elapsedMs ?? null,+ },+ };+ },+};diff --git a/packages/brain-mcp/src/tools/list-providers.js b/packages/brain-mcp/src/tools/list-providers.jsnew file mode 100644index 000000000..56df4f8f2--- /dev/null+++ b/packages/brain-mcp/src/tools/list-providers.js@@ -0,0 +1,56 @@+// `list_providers` — discover the LLM providers/models the router can reach. Read-only.+//+// Wraps GET /api/brain/chat, which returns every configured provider with its+// label, network, tier, max output, and a live `available` flag (true when the+// server holds a working key or OpenRouter mirror for it).++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'list_providers',+ title: 'List LLM providers and models',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List every LLM the three.ws router can run a completion through — one entry per provider/model. ' ++ 'Each entry has: `key` (the id you pass to `chat`), `label` (human name), `network` (e.g. Anthropic, ' ++ 'OpenAI, DashScope, NVIDIA NIM, IBM watsonx.ai), `tier` (flagship | balanced | fast | reasoning), ' ++ '`maxOutput` (max output tokens), `description`, `available` (true when the server currently holds a ' ++ 'working key/route for it), and `requiresAuth` (true when it is a paid first-party model that needs a ' ++ 'three.ws API key — set THREE_WS_API_KEY; false for the free open-weight tiers). Call this first to ' ++ 'pick a `key` for `chat`. The set is live, so availability moves between calls — not idempotent.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/brain/chat');+ const providers = Array.isArray(data?.providers) ? data.providers : [];+ // The router serves the free open-weight tiers anonymously; everything else+ // is a paid first-party model that needs a three.ws API key. Mirrors the+ // ANON_BRAIN_PROVIDERS gate in api/brain/chat.js.+ const ANON = new Set([+ 'gpt-oss-120b',+ 'nvidia-nemotron-120b',+ 'nvidia-nemotron-super-49b',+ 'nvidia-nemotron-nano',+ 'nvidia-deepseek-v4',+ 'nvidia-kimi-k2',+ 'nvidia-llama4-maverick',+ 'nvidia-minimax-m2',+ ]);+ const shaped = providers.map((p) => ({+ key: p.key,+ label: p.label,+ network: p.network,+ tier: p.tier,+ maxOutput: p.maxOutput,+ description: p.description,+ available: Boolean(p.available),+ requiresAuth: !ANON.has(p.key),+ }));+ return {+ ok: true,+ count: shaped.length,+ available: shaped.filter((p) => p.available).length,+ default_provider: 'gpt-oss-120b',+ providers: shaped,+ };+ },+};diff --git a/packages/brain-mcp/test/registration.test.mjs b/packages/brain-mcp/test/registration.test.mjsnew file mode 100644index 000000000..a2295c577--- /dev/null+++ b/packages/brain-mcp/test/registration.test.mjs@@ -0,0 +1,65 @@+// Tool-surface invariants for @three-ws/brain-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/brain-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = ['list_providers', 'chat'];++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 2);+ 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('every tool is a read-only, live-data query', () => {+ for (const tool of TOOLS) {+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ // A completion is non-deterministic and the provider set moves between+ // calls — neither tool is idempotent.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} is not idempotent`);+ }+});++test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++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`);+ }+});diff --git a/packages/clash-mcp/package-lock.json b/packages/clash-mcp/package-lock.jsonnew file mode 100644index 000000000..ca563bece--- /dev/null+++ b/packages/clash-mcp/package-lock.json@@ -0,0 +1,1199 @@+{+ "name": "@three-ws/clash-mcp",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@three-ws/clash-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "bs58": "^6.0.0",+ "tweetnacl": "^1.0.3",+ "zod": "^3.23.8"+ },+ "bin": {+ "clash-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.14",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",+ "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.29.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",+ "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/base-x": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz",+ "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==",+ "license": "MIT"+ },+ "node_modules/body-parser": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^2.0.0",+ "debug": "^4.4.3",+ "http-errors": "^2.0.1",+ "iconv-lite": "^0.7.2",+ "on-finished": "^2.4.1",+ "qs": "^6.15.2",+ "raw-body": "^3.0.2",+ "type-is": "^2.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/body-parser/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/bs58": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz",+ "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==",+ "license": "MIT",+ "dependencies": {+ "base-x": "^5.0.0"+ }+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz",+ "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.5.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",+ "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",+ "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hono": {+ "version": "4.12.27",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.27.tgz",+ "integrity": "sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ip-address": {+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",+ "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.15.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",+ "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4",+ "side-channel-list": "^1.0.1",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/tweetnacl": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",+ "license": "Unlicense"+ },+ "node_modules/type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }+ }+ }+}diff --git a/packages/clash-mcp/package.json b/packages/clash-mcp/package.jsonnew file mode 100644index 000000000..519e0ca7e--- /dev/null+++ b/packages/clash-mcp/package.json@@ -0,0 +1,58 @@+{+ "name": "@three-ws/clash-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/clash-mcp",+ "description": "Play three.ws Coin Clash — the community faction war backed by real holdings + pump.fun data — from any AI agent. Read the live battle board and leaderboard (public), or enlist your wallet and rally power for a faction (Solana-signed writes).",+ "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/clash-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "coin-clash",+ "pump.fun",+ "faction",+ "game",+ "siws"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "clash-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",+ "bs58": "^6.0.0",+ "tweetnacl": "^1.0.3",+ "zod": "^3.23.8"+ }+}diff --git a/packages/clash-mcp/server.json b/packages/clash-mcp/server.jsonnew file mode 100644index 000000000..c9bf76c25--- /dev/null+++ b/packages/clash-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/clash-mcp",+ "title": "three.ws Coin Clash",+ "description": "Play three.ws Coin Clash — read the live faction battle board and leaderboard, enlist your wallet, and rally power for a faction.",+ "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/clash-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/clash-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 Coin Clash endpoints. 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 Coin Clash reads and writes.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ },+ {+ "name": "SOLANA_SECRET_KEY",+ "description": "Base58 Solana secret key for the enlisting wallet. Required only for the write tools (enlist_faction, rally_faction) — reads work without it. Per-call `secret` arguments override this. The wallet must hold the faction coin it enlists for. Treat like cash.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ }+ ]+ }+ ]+}diff --git a/packages/clash-mcp/src/index.js b/packages/clash-mcp/src/index.jsnew file mode 100644index 000000000..5a7ebff65--- /dev/null+++ b/packages/clash-mcp/src/index.js@@ -0,0 +1,119 @@+#!/usr/bin/env node+// @three-ws/clash-mcp — MCP server entry point.+//+// Exposes Coin Clash — the three.ws community faction war, backed by real+// holdings + pump.fun data — to any AI agent over stdio:+// • get_clash_state — the live battle board: who fights whom, power, clock+// • get_clash_leaderboard — all-time faction war records (+ a faction's soldiers)+// • enlist_faction — prove an on-chain holding → get a war pass (write)+// • rally_faction — spend taps as battle power for your faction (write)+//+// Reads are public — point THREE_WS_BASE at a deployment and go. Writes are+// wallet-scoped: enlist signs a challenge with the soldier's Solana key (the+// `secret` arg or SOLANA_SECRET_KEY env) and the backend confirms a live holding+// of the faction coin before issuing a pass. Nothing is mocked.+//+// Run standalone:+// node packages/clash-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 getClashState } from './tools/get-clash-state.js';+import { def as getClashLeaderboard } from './tools/get-clash-leaderboard.js';+import { def as enlistFaction } from './tools/enlist-faction.js';+import { def as rallyFaction } from './tools/rally-faction.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 = [getClashState, getClashLeaderboard, enlistFaction, rallyFaction];++/**+ * 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: 'clash-mcp', title: 'three.ws Coin Clash', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Coin Clash MCP — play the community faction war from an agent. Coin Clash matches ' ++ 'two communities each round and the army that rallies more power before the clock runs out wins. ' ++ 'get_clash_state reads the live board (matchups, each army\'s power + momentum, the clock, who\'s ' ++ 'leading). get_clash_leaderboard ranks factions by all-time war record and can list a faction\'s top ' ++ 'soldiers. enlist_faction proves the signer\'s wallet holds the faction coin (it signs a challenge ' ++ 'with your Solana key; the backend confirms a live on-chain holding) and returns a war pass. ' ++ 'rally_faction spends taps from that pass as battle power for your faction — pass a war pass, or a ' ++ 'faction token to auto-enlist and rally in one call. Reads need no key; writes use the `secret` arg ' ++ 'or SOLANA_SECRET_KEY env. All data is live — power and standings move between calls.',+ },+ );++ 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(`[clash-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('[clash-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/clash-mcp/src/lib/clash.js b/packages/clash-mcp/src/lib/clash.jsnew file mode 100644index 000000000..ef8c09fb4--- /dev/null+++ b/packages/clash-mcp/src/lib/clash.js@@ -0,0 +1,77 @@+// Coin Clash flow helpers shared by the write tools.+//+// Enlisting is a three-step proof, collapsed here into one agent-facing call:+// 1. POST /api/clash/enlist → a challenge bound to wallet + faction+// 2. sign the challenge locally → ed25519 proof of wallet ownership+// 3. POST /api/clash/enlist-verify → server checks the signature + a live+// on-chain holding, then seals a war pass+// The war pass is the credential the rally endpoint trusts (so it never re-runs+// Solana RPC on every tap). rally_faction can take a pass directly, or auto-run+// this flow from a `secret` when none is supplied.++import { apiRequest } from './api.js';+import { loadSigner, signMessage } from './signer.js';++/**+ * Run the full enlist flow for a faction and return the verification result.+ * Resolves the signer's wallet from the secret, so the caller only needs the+ * faction mint.+ *+ * @param {{ token: string, secret?: string }} args+ * @returns {Promise<{+ * eligible: boolean,+ * wallet: string,+ * faction: string,+ * amount: number,+ * usd: number,+ * warPass: string|null,+ * reason: string|null,+ * challengeExpiresAt: number|null,+ * }>}+ */+export async function enlist({ token, secret }) {+ const faction = String(token || '').trim();+ if (!faction) {+ throw Object.assign(new Error('A faction token (mint) is required to enlist.'), {+ code: 'validation_error',+ });+ }++ // Resolve the wallet from the signer up front so a missing/invalid key fails+ // loudly before we issue a challenge.+ const { wallet } = loadSigner(secret);++ // 1) Issue a challenge bound to this exact wallet + faction.+ const issued = await apiRequest('/api/clash/enlist', {+ method: 'POST',+ body: { token: faction, wallet },+ });+ const message = issued?.data?.message;+ const challengeExpiresAt = issued?.data?.expiresAt ?? null;+ if (!message) {+ throw Object.assign(new Error('enlist did not return a challenge to sign.'), {+ code: 'upstream_error',+ });+ }++ // 2) Sign the exact challenge text.+ const { signature } = signMessage(message, secret);++ // 3) Verify the signature + prove a live holding → war pass (or ineligible).+ const verified = await apiRequest('/api/clash/enlist-verify', {+ method: 'POST',+ body: { token: faction, wallet, message, signature },+ });+ const d = verified?.data ?? {};++ return {+ eligible: Boolean(d.eligible),+ wallet,+ faction,+ amount: Number(d.amount) || 0,+ usd: Number(d.usd) || 0,+ warPass: d.warPass ?? null,+ reason: d.reason ?? (d.eligible ? null : 'not_eligible'),+ challengeExpiresAt,+ };+}diff --git a/packages/clash-mcp/src/tools/enlist-faction.js b/packages/clash-mcp/src/tools/enlist-faction.jsnew file mode 100644index 000000000..6b0bb24c3--- /dev/null+++ b/packages/clash-mcp/src/tools/enlist-faction.js@@ -0,0 +1,46 @@+// `enlist_faction` — prove you hold a faction's coin and get a war pass. Write.+//+// Runs the full enlist proof: requests a wallet-bound challenge, signs it+// locally with the soldier's Solana key, and submits the signature so the+// backend can verify it and confirm a live on-chain holding of the faction coin+// (api/clash enlist → enlist-verify). On success it returns a `warPass` — the+// credential rally_faction spends. Idempotent: re-enlisting the same wallet for+// the same faction just mints a fresh, equivalent pass; nothing accumulates and+// no funds move.++import { z } from 'zod';++import { enlist } from '../lib/clash.js';++export const def = {+ name: 'enlist_faction',+ title: 'Enlist in a Coin Clash faction',+ // Write, but non-destructive and idempotent: it proves a holding and issues a+ // pass; no value moves and re-running mints an equivalent pass.+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Enlist the signer\'s wallet as a soldier in a Coin Clash faction and return a war pass. Requires the wallet to hold the faction coin: the tool requests a challenge, signs it with the wallet\'s Solana key (from the `secret` arg, or SOLANA_SECRET_KEY env), and the backend verifies the signature then checks a live on-chain holding. Returns `{ eligible, wallet, faction, amount, usd, warPass }`. If `eligible` is false the wallet does not currently hold the coin (`reason: "not_a_holder"`) and `warPass` is null — buy/hold the coin and retry. Keep the `warPass`: pass it to rally_faction to spend taps as battle power. No funds move; the pass expires after ~30 minutes.',+ inputSchema: {+ token: z+ .string()+ .min(1)+ .describe('The faction coin mint to enlist for — must be a faction in get_clash_state.'),+ secret: z+ .string()+ .optional()+ .describe('Base58 Solana secret of the enlisting wallet. Falls back to SOLANA_SECRET_KEY env. The wallet must hold the faction coin.'),+ },+ async handler(args) {+ try {+ const result = await enlist({ token: args?.token, secret: args?.secret });+ return { ok: true, ...result };+ } catch (err) {+ return {+ ok: false,+ error: err?.code || 'enlist_failed',+ message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),+ };+ }+ },+};diff --git a/packages/clash-mcp/src/tools/get-clash-leaderboard.js b/packages/clash-mcp/src/tools/get-clash-leaderboard.jsnew file mode 100644index 000000000..ac4b66631--- /dev/null+++ b/packages/clash-mcp/src/tools/get-clash-leaderboard.js@@ -0,0 +1,35 @@+// `get_clash_leaderboard` — all-time faction war records, plus (optionally) a+// single faction's top soldiers this round. Read-only.+//+// Wraps GET /api/clash/leaderboard[?faction=<mint>].++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_clash_leaderboard',+ title: 'Coin Clash leaderboard',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Rank Coin Clash factions by their all-time war record. Returns `board`: factions sorted by wins then power, each with `token`, `symbol`, `image`, `members`, `w`/`l`/`d` (win/loss/draw), `battles`, cumulative `power`, and `winRate` (percent of decided battles won, or null if none decided yet). Pass `faction` (a faction mint) to also get `soldiers`: that faction\'s top rally contributors this round (wallet + power). Live data — records update as rounds settle. Use this to find the strongest armies and the heaviest hitters.',+ inputSchema: {+ faction: z+ .string()+ .min(1)+ .optional()+ .describe('Optional faction mint to also return that faction\'s top soldiers this round.'),+ },+ async handler(args) {+ const faction = args?.faction ? String(args.faction).trim() : undefined;+ const data = await apiRequest('/api/clash/leaderboard', {+ query: faction ? { faction } : undefined,+ });+ const d = data?.data ?? {};+ return {+ ok: true,+ board: Array.isArray(d.board) ? d.board : [],+ soldiers: d.soldiers ?? null,+ };+ },+};diff --git a/packages/clash-mcp/src/tools/get-clash-state.js b/packages/clash-mcp/src/tools/get-clash-state.jsnew file mode 100644index 000000000..4da81f6a9--- /dev/null+++ b/packages/clash-mcp/src/tools/get-clash-state.js@@ -0,0 +1,30 @@+// `get_clash_state` — the live Coin Clash battle board. Read-only.+//+// Wraps GET /api/clash/state. Returns the current round's bracket: which+// factions are matched, each army's accumulated rally power + live momentum,+// the tug-of-war share, who's leading, and how long is left on the clock.++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_clash_state',+ title: 'Coin Clash battle board',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read the live Coin Clash board for the current round. Coin Clash is three.ws community faction warfare: every CoinCommunities community is a faction, its holders are its army, and two factions are matched each round — whichever army rallies more power before the clock runs out wins. Returns `epoch` (round index), `endsAt`/`msLeft`/`epochMs` (the clock), and `arena`: an array of battles, each with sides `a` and `b` (token, symbol, image, members, posts, priceUsd, live `momentum` multiplier, accumulated `power`, all-time `record`), `aShare` (side a\'s share of the round\'s combined power for a tug-of-war bar), and `leader` (the winning side\'s token, or null if tied). `bye` is the unmatched faction this round (odd roster), `factionCount` the active army count. Live data — power and standings move between calls. Use this to see who\'s fighting and who\'s winning before enlisting or rallying.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/clash/state');+ const d = data?.data ?? {};+ return {+ ok: true,+ epoch: d.epoch ?? null,+ endsAt: d.endsAt ?? null,+ msLeft: d.msLeft ?? null,+ epochMs: d.epochMs ?? null,+ factionCount: d.factionCount ?? 0,+ arena: Array.isArray(d.arena) ? d.arena : [],+ bye: d.bye ?? null,+ };+ },+};diff --git a/packages/clash-mcp/src/tools/rally-faction.js b/packages/clash-mcp/src/tools/rally-faction.jsnew file mode 100644index 000000000..057cbec87--- /dev/null+++ b/packages/clash-mcp/src/tools/rally-faction.js@@ -0,0 +1,102 @@+// `rally_faction` — spend taps as battle power for your faction. Write.+//+// Wraps POST /api/clash/rally. A war pass authorizes the rally; taps convert to+// power for the pass's faction this round (folded with the faction's live+// momentum, clamped per call, capped per wallet per round). Provide a `pass`+// from enlist_faction, or a `token` (+ optional `secret`) to auto-enlist and+// rally in one call.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { enlist } from '../lib/clash.js';++export const def = {+ name: 'rally_faction',+ title: 'Rally power for a Coin Clash faction',+ // Write and NOT idempotent: every call appends power to the round. Not+ // destructive — no funds move and power can't be removed, it's a contribution.+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'Rally for a Coin Clash faction by spending taps as battle power for the current round. Authorize with either a `pass` (war pass from enlist_faction) or a `token` (+ optional `secret`) to auto-enlist first. `taps` (1–50 per call) convert to power, multiplied by the faction\'s live momentum and capped per wallet per round. Returns `{ epoch, mint, added, momentum, walletPower, walletCap, capped, factionPower, msLeft }` — `added` is the power this call contributed, `factionPower` the army\'s new round total, `capped` true once the wallet hits `walletCap`. Each call adds power (not idempotent); call repeatedly to keep rallying while the round clock (`msLeft`) runs.',+ inputSchema: {+ taps: z+ .number()+ .int()+ .min(1)+ .max(50)+ .describe('Taps to spend this call (1–50). Each tap is one base power point before momentum.'),+ pass: z+ .string()+ .optional()+ .describe('A war pass from enlist_faction. Provide this OR `token` to auto-enlist.'),+ token: z+ .string()+ .optional()+ .describe('Faction mint to auto-enlist for when no `pass` is given (uses `secret`/SOLANA_SECRET_KEY).'),+ secret: z+ .string()+ .optional()+ .describe('Base58 Solana secret, used only when auto-enlisting from `token`. Falls back to SOLANA_SECRET_KEY env.'),+ },+ async handler(args) {+ try {+ let pass = args?.pass ? String(args.pass).trim() : '';++ // Auto-enlist path: no pass but a faction token → run the full proof and+ // rally with the freshly minted pass.+ let enlistment = null;+ if (!pass) {+ if (!args?.token) {+ return {+ ok: false,+ error: 'validation_error',+ message: 'Provide a `pass` from enlist_faction, or a `token` to auto-enlist.',+ };+ }+ enlistment = await enlist({ token: args.token, secret: args.secret });+ if (!enlistment.eligible || !enlistment.warPass) {+ return {+ ok: false,+ error: 'not_eligible',+ message:+ enlistment.reason === 'not_a_holder'+ ? `Wallet ${enlistment.wallet} does not hold ${enlistment.faction} — cannot rally for it.`+ : 'Enlistment was not eligible; no war pass issued.',+ eligible: false,+ reason: enlistment.reason,+ wallet: enlistment.wallet,+ faction: enlistment.faction,+ };+ }+ pass = enlistment.warPass;+ }++ const data = await apiRequest('/api/clash/rally', {+ method: 'POST',+ body: { pass, taps: args.taps },+ });+ const d = data?.data ?? {};+ return {+ ok: true,+ ...(enlistment ? { enlisted: { wallet: enlistment.wallet, amount: enlistment.amount, usd: enlistment.usd } } : {}),+ epoch: d.epoch ?? null,+ mint: d.mint ?? null,+ added: d.added ?? 0,+ momentum: d.momentum ?? 1,+ walletPower: d.walletPower ?? 0,+ walletCap: d.walletCap ?? null,+ capped: Boolean(d.capped),+ factionPower: d.factionPower ?? 0,+ msLeft: d.msLeft ?? null,+ };+ } catch (err) {+ return {+ ok: false,+ error: err?.code || 'rally_failed',+ message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),+ };+ }+ },+};diff --git a/packages/clash-mcp/test/registration.test.mjs b/packages/clash-mcp/test/registration.test.mjsnew file mode 100644index 000000000..c79a9633f--- /dev/null+++ b/packages/clash-mcp/test/registration.test.mjs@@ -0,0 +1,79 @@+// Tool-surface invariants for @three-ws/clash-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/clash-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = ['get_clash_state', 'get_clash_leaderboard', 'enlist_faction', 'rally_faction'];++// The two write tools and their honest annotations.+const WRITE_TOOLS = new Set(['enlist_faction', 'rally_faction']);++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 4);+ 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`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ }+});++test('read tools are read-only, live, non-idempotent and omit destructiveHint', () => {+ for (const tool of TOOLS) {+ if (WRITE_TOOLS.has(tool.name)) continue;+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ // Live board/leaderboard data is never idempotent — power moves between calls.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++test('write tools set readOnlyHint:false and are not destructive (no funds move)', () => {+ for (const name of WRITE_TOOLS) {+ const tool = TOOLS.find((t) => t.name === name);+ assert.ok(tool, `${name} should exist`);+ assert.equal(tool.annotations.readOnlyHint, false, `${name} mutates game state — readOnlyHint must be false`);+ assert.notEqual(tool.annotations.destructiveHint, true, `${name} moves no funds — must not be destructive`);+ }+});++test('enlist is idempotent (re-mints an equivalent pass); rally is not (appends power)', () => {+ const enlist = TOOLS.find((t) => t.name === 'enlist_faction');+ const rally = TOOLS.find((t) => t.name === 'rally_faction');+ assert.equal(enlist.annotations.idempotentHint, true, 'enlist_faction should be idempotent');+ assert.equal(rally.annotations.idempotentHint, false, 'rally_faction appends power — not idempotent');+});++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`);+ }+});diff --git a/packages/kol-mcp/README.md b/packages/kol-mcp/README.mdnew file mode 100644index 000000000..db5d92d49--- /dev/null+++ b/packages/kol-mcp/README.md@@ -0,0 +1,140 @@+<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/kol-mcp</h1>++<p align="center"><strong>Track one smart trader — a tracked KOL wallet's portfolio P&L and its trades on a given mint, from any AI agent.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/kol-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/kol-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/kol-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/kol-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 for the **per-wallet KOL deep dive**. Where [`@three-ws/intel-mcp`](https://www.npmjs.com/package/@three-ws/intel-mcp) ranks the whole tracked KOL set (`kol_leaderboard`) and shows everyone's trades on a mint (`kol_trades`), this server zooms in on **one** smart trader: pull their live portfolio P&L card, then inspect their own buys/sells of a specific token — everything an agent needs to decide whether to copy or analyze them.++Portfolio P&L comes from the three.ws Birdeye proxy (the Birdeye key lives server-side); trade history comes from the three.ws Helius-backed KOL feed. All live, read-only — no API key, signer, or payment on the client. Point `THREE_WS_BASE` at a deployment and go.++## Install++```bash+npm install @three-ws/kol-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/kol-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add kol -- npx -y @three-ws/kol-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "kol": {+ "command": "npx",+ "args": ["-y", "@three-ws/kol-mcp"]+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/kol-mcp+```++## Tools++| Tool | Type | What it does |+| ---------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------- |+| `get_wallet_portfolio` | read-only | One KOL wallet's live portfolio P&L card: realized P&L, unrealized (open-position) P&L, win rate, total trades, top holding. |+| `get_wallet_trades` | read-only | That wallet's recent buys/sells of a given mint — side, SOL size, token amount, price, USD value, and timing, newest first. |++Both tools read live data: portfolio P&L and trade feeds move between calls, so neither is idempotent.++### Input parameters++**`get_wallet_portfolio`** — `wallet` (required).++**`get_wallet_trades`** — `wallet` (required), `mint` (required), `limit` (1–100, default 20).++> The three.ws trade feed is mint-keyed (it scans every tracked KOL wallet for activity on one mint), so a per-wallet view is that feed narrowed to your wallet. `get_wallet_trades` therefore needs both a `wallet` and a `mint`. To see *every* tracked wallet's trades on a mint, use `kol_trades` in [`@three-ws/intel-mcp`](https://www.npmjs.com/package/@three-ws/intel-mcp).++## Example++```jsonc+// get_wallet_portfolio+> { "wallet": "5xY…KoL" }+{+ "ok": true,+ "wallet": "5xY…KoL",+ "has_activity": true,+ "realized_pnl_usd": 124300,+ "unrealized_pnl_usd": 38120,+ "win_rate": 0.64,+ "total_trades": 412,+ "top_token": { "symbol": "THREE", "pnl": 38120 }+}+```++```jsonc+// get_wallet_trades+> { "wallet": "5xY…KoL", "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "limit": 3 }+{+ "ok": true,+ "wallet": "5xY…KoL",+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "count": 2,+ "trades": [+ { "side": "buy", "amountSol": 4.2, "amountToken": 1830000, "price": 0.0000022, "usd": 612.4, "time": "2026-06-24T09:12:03.000Z", "source": "kol", "label": "Top Trader" }+ ]+}+```++`has_activity: false` on a portfolio (all-zero P&L, no trades, no holding) means the proxy has no recorded history for that address yet — an honest "no data", not a failure.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default |+| --------------------- | -------- | ------------------ |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |++No key on the client: the Birdeye key that backs portfolio P&L and the Helius key behind the trade feed both live server-side on three.ws.++## Links++- 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/kol-mcp/package.json b/packages/kol-mcp/package.jsonnew file mode 100644index 000000000..531125eb0--- /dev/null+++ b/packages/kol-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/kol-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/kol-mcp",+ "description": "Track one smart trader from any AI agent — a tracked KOL wallet's portfolio P&L (realized/unrealized, win rate, top holding) and its trades on a given mint. Read-only over the live public three.ws KOL API. No key, no signer, no payment.",+ "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/kol-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "kol",+ "smart-money",+ "portfolio",+ "pnl",+ "copy-trading"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "kol-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/kol-mcp/server.json b/packages/kol-mcp/server.jsonnew file mode 100644index 000000000..f89848e64--- /dev/null+++ b/packages/kol-mcp/server.json@@ -0,0 +1,49 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/kol-mcp",+ "title": "three.ws KOL",+ "description": "Per-wallet KOL deep dive — a tracked trader's portfolio P&L and its trades on a given mint.",+ "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/kol-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/kol-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 KOL endpoints. 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 KOL reads.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ }+ ]+ }+ ]+}diff --git a/packages/kol-mcp/src/tools/get-wallet-portfolio.js b/packages/kol-mcp/src/tools/get-wallet-portfolio.jsindex 262e6ad73..49215f9be 100644--- a/packages/kol-mcp/src/tools/get-wallet-portfolio.js+++ b/packages/kol-mcp/src/tools/get-wallet-portfolio.js@@ -18,8 +18,9 @@ export const def = {'trades, and the single highest-value token the wallet holds (symbol + USD value). Use ' +'this to size up a specific smart trader before copying or analyzing them. For ranking ' +'many traders at once use intel-mcp `kol_leaderboard`; this is the per-wallet deep dive. ' +- '`found:false` means the proxy returned no portfolio for that address (unknown wallet, ' +- 'or Birdeye had nothing). Read-only live data.',+ '`has_activity:false` (all-zero P&L, no trades, no holding) means the proxy has no ' ++ 'recorded portfolio for that address yet — an honest "no data", not a failure. ' ++ 'Read-only live data.',inputSchema: {wallet: z.string()@@ -29,20 +30,26 @@ export const def = {async handler(args) {const wallet = String(args?.wallet ?? '').trim();const data = await apiRequest('/api/kol/wallets', { query: { addresses: wallet } });+ // The proxy returns one normalized row per requested address (zeros when+ // Birdeye has no history for it), so match ours out of the batch.const rows = Array.isArray(data?.data) ? data.data : [];- const row = rows.find((r) => r?.address === wallet) ?? rows[0] ?? null;- if (!row) {- return { ok: true, wallet, found: false };- }+ const row = rows.find((r) => r?.address === wallet) ?? rows[0] ?? {};++ const realizedPnl = row.realizedPnl ?? 0;+ const unrealizedPnl = row.unrealizedPnl ?? 0;+ const winRate = row.winRate ?? 0;+ const totalTrades = row.totalTrades ?? 0;+ const topToken = row.topToken ?? null;+return {ok: true,wallet: row.address ?? wallet,- found: true,- realized_pnl_usd: row.realizedPnl ?? 0,- unrealized_pnl_usd: row.unrealizedPnl ?? 0,- win_rate: row.winRate ?? 0,- total_trades: row.totalTrades ?? 0,- top_token: row.topToken ?? null,+ has_activity: totalTrades > 0 || realizedPnl !== 0 || unrealizedPnl !== 0 || topToken !== null,+ realized_pnl_usd: realizedPnl,+ unrealized_pnl_usd: unrealizedPnl,+ win_rate: winRate,+ total_trades: totalTrades,+ top_token: topToken,};},};diff --git a/packages/kol-mcp/test/registration.test.mjs b/packages/kol-mcp/test/registration.test.mjsnew file mode 100644index 000000000..f248a58aa--- /dev/null+++ b/packages/kol-mcp/test/registration.test.mjs@@ -0,0 +1,64 @@+// Tool-surface invariants for @three-ws/kol-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/kol-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = ['get_wallet_portfolio', 'get_wallet_trades'];++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 2);+ 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('every tool is a read-only, live-data query', () => {+ for (const tool of TOOLS) {+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ // Live portfolio P&L and trade feeds move between calls — never idempotent.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);+ }+});++test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++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`);+ }+});diff --git a/packages/loom-mcp/package.json b/packages/loom-mcp/package.jsonnew file mode 100644index 000000000..d8424484d--- /dev/null+++ b/packages/loom-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/loom-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/loom-mcp",+ "description": "Loom — the three.ws community 3D-creation gallery from any AI agent. Browse the public feed of community-forged GLB creations, fetch one with its viewer URL, and submit your own. Public API, no key required.",+ "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/loom-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "3d",+ "glb",+ "gallery",+ "loom",+ "forge",+ "generative-3d"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "loom-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/loom-mcp/server.json b/packages/loom-mcp/server.jsonnew file mode 100644index 000000000..8852183e6--- /dev/null+++ b/packages/loom-mcp/server.json@@ -0,0 +1,49 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/loom-mcp",+ "title": "three.ws Loom",+ "description": "The community 3D-creation gallery: browse community-forged GLB creations, fetch one with its viewer URL, and submit your own.",+ "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/loom-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/loom-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 Loom gallery (/api/loom). 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 Loom reads and submissions.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ }+ ]+ }+ ]+}diff --git a/packages/loom-mcp/src/index.js b/packages/loom-mcp/src/index.jsnew file mode 100644index 000000000..41dfa17b7--- /dev/null+++ b/packages/loom-mcp/src/index.js@@ -0,0 +1,122 @@+#!/usr/bin/env node+// @three-ws/loom-mcp — MCP server entry point.+//+// Exposes Loom, the three.ws community 3D-creation gallery (the public forge+// feed), over stdio so any AI assistant can:+// • get_loom_feed — browse community-forged creations, newest-first+// • get_creation — fetch one creation + its /forge/embed viewer URL+// • submit_creation — contribute a forged GLB to the public gallery+//+// A thin wrapper over the PUBLIC three.ws API (/api/loom). Reads need no key;+// submission needs no key or account either — it is gated server-side only by an+// IP rate limit. Closes the loop with scene-mcp (compose) and avatar-agent+// (generate): forge a GLB, then publish it here for the whole platform to see.+//+// Run standalone:+// node packages/loom-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 getLoomFeed } from './tools/get-loom-feed.js';+import { def as getCreation } from './tools/get-creation.js';+import { def as submitCreation } from './tools/submit-creation.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 = [getLoomFeed, getCreation, submitCreation];++/**+ * 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: 'loom-mcp', title: 'three.ws Loom', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Loom MCP — the community 3D-creation gallery. get_loom_feed browses the public, ' ++ 'world-readable feed of community-forged GLB creations (newest-first, paginated via the ' ++ 'nextBefore cursor); every item comes with a /forge/embed viewer_url and a paste-ready ' ++ 'iframe_snippet so you can preview it inline. get_creation fetches a single creation by id with ' ++ 'the same viewer extras. submit_creation contributes a forged GLB to the gallery — it needs ' ++ 'just a prompt and an https glbUrl on an allowed host (three.ws, r2.dev, cloudflarestorage.com, ' ++ 'replicate.delivery, githubusercontent.com); no key or account is required, but submissions are ' ++ 'PUBLIC and rate-limited (~20/hour per IP), and `author` is free-text attribution, not identity. ' ++ 'This closes the loop with scene-mcp (compose worlds) and avatar-agent (generate GLBs): forge a ' ++ 'model elsewhere, then publish it here. The only coin this platform references is $THREE.',+ },+ );++ for (const tool of TOOLS) {+ server.registerTool(+ tool.name,+ {+ title: tool.title,+ description: tool.description,+ inputSchema: tool.inputSchema,+ // MCP ToolAnnotations (readOnlyHint / destructiveHint / idempotentHint /+ // openWorldHint) — lets clients gate confirmation prompts per tool+ // instead of treating every call as a destructive write.+ 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 } : {}),+ ...(err?.body ? { detail: err.body } : {}),+ };+ 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(`[loom-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('[loom-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/loom-mcp/src/tools/get-creation.js b/packages/loom-mcp/src/tools/get-creation.jsnew file mode 100644index 000000000..640e0e40a--- /dev/null+++ b/packages/loom-mcp/src/tools/get-creation.js@@ -0,0 +1,35 @@+// `get_creation` — fetch one Loom creation by id. Read-only.+//+// Wraps GET /api/loom?c=<id> → { creation }.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { decorateCreation } from '../lib/viewer.js';++export const def = {+ name: 'get_creation',+ title: 'Fetch one Loom creation by id',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Fetch a single Loom creation by its id. Returns the full record — prompt, glbUrl, previewImageUrl, ' ++ 'author, tier, backend, createdAt — together with a `viewer_url` (the /forge/embed orbit+AR viewer for ' ++ 'the GLB), an `og_image_url`, and a paste-ready `iframe_snippet` so the model can be previewed inline. ' ++ 'Returns a not_found error if no creation has that id. Read-only, no key required.',+ inputSchema: {+ id: z+ .string()+ .min(1)+ .describe('The creation id (a UUID) from the feed or from a prior submit_creation.'),+ },+ async handler(args) {+ const id = String(args?.id ?? '').trim();+ if (!id) throw Object.assign(new Error('id is required.'), { code: 'invalid_input', status: 400 });+ const data = await apiRequest('/api/loom', { query: { c: id } });+ const creation = decorateCreation(data?.creation);+ if (!creation) {+ throw Object.assign(new Error(`No Loom creation found with id "${id}".`), { code: 'not_found', status: 404 });+ }+ return { ok: true, creation };+ },+};diff --git a/packages/loom-mcp/src/tools/get-loom-feed.js b/packages/loom-mcp/src/tools/get-loom-feed.jsnew file mode 100644index 000000000..1a3664fd1--- /dev/null+++ b/packages/loom-mcp/src/tools/get-loom-feed.js@@ -0,0 +1,51 @@+// `get_loom_feed` — browse the public Loom gallery of community-forged 3D+// creations, newest-first. Read-only.+//+// Wraps GET /api/loom?limit=&before= → { creations, nextBefore }.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { decorateCreation } from '../lib/viewer.js';++export const def = {+ name: 'get_loom_feed',+ title: 'Browse the Loom 3D-creation gallery',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Browse Loom — the public, world-readable gallery of community-forged 3D creations (a forged GLB plus ' ++ 'the prompt that made it and a bit of attribution), returned newest-first. Each creation includes its ' ++ 'id, prompt, glbUrl, previewImageUrl, author, tier, backend, createdAt (ms epoch), plus a ready-to-use ' ++ '`viewer_url` (the /forge/embed orbit+AR viewer), `og_image_url`, and a paste-ready `iframe_snippet`. ' ++ 'Paginate backwards with `before`: pass the `nextBefore` cursor from the previous page to load older ' ++ 'items; a null `nextBefore` means you reached the end. Read-only, no key required.',+ inputSchema: {+ limit: z+ .number()+ .int()+ .min(1)+ .max(120)+ .optional()+ .describe('How many creations to return (1–120, default 60).'),+ before: z+ .number()+ .int()+ .positive()+ .optional()+ .describe('Pagination cursor (ms epoch): return only creations older than this. Pass the prior page\'s nextBefore.'),+ },+ async handler(args) {+ const query = {};+ if (args?.limit != null) query.limit = args.limit;+ if (args?.before != null) query.before = args.before;+ const data = await apiRequest('/api/loom', { query });+ const creations = Array.isArray(data?.creations) ? data.creations.map(decorateCreation).filter(Boolean) : [];+ return {+ ok: true,+ count: creations.length,+ creations,+ nextBefore: data?.nextBefore ?? null,+ has_more: data?.nextBefore != null,+ };+ },+};diff --git a/packages/loom-mcp/src/tools/submit-creation.js b/packages/loom-mcp/src/tools/submit-creation.jsnew file mode 100644index 000000000..f89e5b3c3--- /dev/null+++ b/packages/loom-mcp/src/tools/submit-creation.js@@ -0,0 +1,85 @@+// `submit_creation` — contribute a forged GLB to the public Loom gallery. Write.+//+// Wraps POST /api/loom { prompt, glbUrl, previewImageUrl?, author?, tier?, backend? }+// → { creation } (201 new, or 200 with the existing record on dedup).+//+// Auth model (verified against api/loom.js): there is NO account, key, or signer.+// The endpoint is public and gated server-side ONLY by an IP rate limit (~20/hr)+// and strict input sanitization. `author` is free-text attribution, not identity.+// The GLB URL must be https on an allowlisted host — we validate that here too so+// a bad URL fails immediately with a clear message instead of a round-trip 400.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { decorateCreation, validateGlbUrl, ALLOWED_GLB_HOST_SUFFIXES } from '../lib/viewer.js';++const PROMPT_MAX = 1000;+const AUTHOR_MAX = 40;++export const def = {+ name: 'submit_creation',+ title: 'Submit a creation to the Loom gallery',+ // Write: appends to a WORLD-READABLE public feed. Not destructive/irreversible+ // in the funds sense, and not reliably idempotent (each accepted POST is a new+ // public record; only an identical glbUrl re-posted within the newest few dedupes).+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'Contribute a forged 3D creation to Loom, the PUBLIC, world-readable community gallery. ⚠️ Anything you ' ++ 'submit becomes visible to everyone on the platform, so only post models you intend to share. Requires ' ++ '`prompt` (the text that forged it, ≤1000 chars) and `glbUrl` (an https URL to the GLB, hosted on an ' ++ 'allowed domain: ' + ALLOWED_GLB_HOST_SUFFIXES.join(', ') + '). Optional: `author` attribution (free ' ++ 'text, ≤40 chars — NOT an authenticated identity; defaults to "anon"), `previewImageUrl`, `tier`, and ' ++ '`backend`. No key or account is needed; the endpoint is rate-limited to ~20 submissions per hour per ' ++ 'IP. Re-submitting the exact same glbUrl returns the existing creation instead of duplicating it. ' ++ 'Returns the stored creation with its id and a ready-to-use viewer_url + iframe_snippet. The only coin ' ++ 'this platform references is $THREE — never put any other token in a prompt.',+ inputSchema: {+ prompt: z+ .string()+ .min(1)+ .max(PROMPT_MAX)+ .describe('The prompt that forged the model. Required, 1–1000 chars. Shown publicly under the creation.'),+ glbUrl: z+ .string()+ .min(1)+ .describe(`https URL to the GLB. Must be hosted on an allowed domain: ${ALLOWED_GLB_HOST_SUFFIXES.join(', ')}.`),+ author: z+ .string()+ .max(AUTHOR_MAX)+ .optional()+ .describe('Attribution shown on the creation (free text, ≤40 chars). Not an authenticated identity. Defaults to "anon".'),+ previewImageUrl: z+ .string()+ .optional()+ .describe('Optional URL of a preview/thumbnail image for the feed.'),+ tier: z.string().optional().describe('Optional forge tier/quality label (e.g. the model preset used).'),+ backend: z.string().optional().describe('Optional name of the forge backend that produced the GLB.'),+ },+ async handler(args) {+ const prompt = String(args?.prompt ?? '').trim();+ if (!prompt) throw Object.assign(new Error('prompt is required.'), { code: 'invalid_input', status: 400 });++ // Validate the GLB URL against the same allowlist the server enforces, so a+ // bad host fails fast with an actionable message rather than an opaque 400.+ const glbUrl = validateGlbUrl(args?.glbUrl);+ if (!glbUrl) {+ throw Object.assign(+ new Error(+ `glbUrl must be an https URL hosted on an allowed domain (${ALLOWED_GLB_HOST_SUFFIXES.join(', ')}).`,+ ),+ { code: 'invalid_glb_url', status: 400 },+ );+ }++ const body = { prompt, glbUrl };+ if (args?.author != null) body.author = String(args.author);+ if (args?.previewImageUrl != null) body.previewImageUrl = String(args.previewImageUrl);+ if (args?.tier != null) body.tier = String(args.tier);+ if (args?.backend != null) body.backend = String(args.backend);++ const data = await apiRequest('/api/loom', { method: 'POST', body });+ const creation = decorateCreation(data?.creation);+ return { ok: true, creation };+ },+};diff --git a/packages/loom-mcp/test/registration.test.mjs b/packages/loom-mcp/test/registration.test.mjsnew file mode 100644index 000000000..055fa6cfc--- /dev/null+++ b/packages/loom-mcp/test/registration.test.mjs@@ -0,0 +1,103 @@+// Tool-surface invariants for @three-ws/loom-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. These+// tests run offline — they never touch the network.+//+// Run: node --test packages/loom-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';+import { validateGlbUrl, viewerUrl, decorateCreation } from '../src/lib/viewer.js';++const EXPECTED_NAMES = ['get_loom_feed', 'get_creation', 'submit_creation'];+const WRITE_NAMES = new Set(['submit_creation']);++test('exactly the expected 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`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ }+});++test('read tools are read-only and omit destructiveHint; the write tool is marked correctly', () => {+ for (const tool of TOOLS) {+ const expectWrite = WRITE_NAMES.has(tool.name);+ assert.equal(tool.annotations.readOnlyHint, !expectWrite, `${tool.name} readOnlyHint should be ${!expectWrite}`);+ if (!expectWrite) {+ // Read-only tools must not set destructiveHint (spec ignores it when readOnlyHint is true).+ assert.equal(tool.annotations.destructiveHint, undefined, `${tool.name} is read-only — destructiveHint should be omitted`);+ // Live feed/lookup move between calls — not idempotent.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);+ }+ }+});++test('submit_creation is a non-idempotent, non-destructive public write', () => {+ const submit = TOOLS.find((t) => t.name === 'submit_creation');+ assert.ok(submit);+ assert.equal(submit.annotations.readOnlyHint, false);+ assert.equal(submit.annotations.idempotentHint, false);+ assert.equal(submit.annotations.destructiveHint, false);+});++test('validateGlbUrl enforces https + the host allowlist', () => {+ // Accepted hosts (mirror api/loom.js)+ assert.ok(validateGlbUrl('https://three.ws/models/x.glb'));+ assert.ok(validateGlbUrl('https://pub-abc.r2.dev/x.glb'));+ assert.ok(validateGlbUrl('https://replicate.delivery/abc/x.glb'));+ assert.ok(validateGlbUrl('https://raw.githubusercontent.com/o/r/main/x.glb'));+ // Rejected: http, bad host, garbage+ assert.equal(validateGlbUrl('http://three.ws/x.glb'), null);+ assert.equal(validateGlbUrl('https://evil.example.com/x.glb'), null);+ assert.equal(validateGlbUrl('not-a-url'), null);+ assert.equal(validateGlbUrl(''), null);+ assert.equal(validateGlbUrl(null), null);+ // No suffix-spoofing: notthree.ws must not pass as three.ws+ assert.equal(validateGlbUrl('https://notthree.ws/x.glb'), null);+});++test('decorateCreation adds a /forge/embed viewer URL + iframe', () => {+ const d = decorateCreation({ id: 'abc', prompt: 'a red cube', glbUrl: 'https://three.ws/x.glb', createdAt: 1 });+ assert.ok(d.viewer_url.startsWith('https://three.ws/forge/embed?src='));+ assert.ok(d.viewer_url.includes('title='));+ assert.ok(d.iframe_snippet.includes('<iframe'));+ assert.ok(d.og_image_url.includes('/api/avatar-og?src='));+ // A record without a GLB still decorates cleanly (nulls, no throw).+ const n = decorateCreation({ id: 'x' });+ assert.equal(n.viewer_url, null);+ assert.equal(decorateCreation(null), null);+});++test('viewerUrl encodes the GLB into the src param', () => {+ const u = viewerUrl('https://three.ws/a b.glb');+ assert.ok(u.includes('src=https'));+ assert.ok(!u.includes('a b.glb')); // space must be encoded+});++test('buildServer registers every tool with its annotations, without a key', () => {+ 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`);+ }+});diff --git a/packages/notifications-mcp/.gitignore b/packages/notifications-mcp/.gitignorenew file mode 100644index 000000000..ed45f7354--- /dev/null+++ b/packages/notifications-mcp/.gitignore@@ -0,0 +1,6 @@+node_modules/+.env+.env.*+!.env.example+*.log+.DS_Storediff --git a/packages/notifications-mcp/LICENSE b/packages/notifications-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/notifications-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/notifications-mcp/src/config.js b/packages/notifications-mcp/src/config.jsnew file mode 100644index 000000000..8e7de8044--- /dev/null+++ b/packages/notifications-mcp/src/config.js@@ -0,0 +1,42 @@+// Centralized env + HTTP base for the notifications MCP.+//+// This server is the agent's own inbound-event surface: it reads and writes the+// real three.ws notification inbox, delivery preferences, and web-push device+// registry over live HTTP. Every route is account-scoped, so the server is+// authenticated — it carries a three.ws API key (or OAuth access token) as a+// Bearer credential on every request. It signs nothing locally and holds no+// other secret; all read/unread state lives server-side.++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(/\/+$/, '');++// The agent owner's three.ws credential. Either a three.ws API key (sk_live_… /+// sk_test_…) or an OAuth access token — both authenticate as the owning user via+// `Authorization: Bearer`. REQUIRED: every notification/push endpoint is+// account-scoped and returns 401 without it. THREE_WS_TOKEN / THREE_WS_BEARER+// are accepted aliases.+export const THREE_WS_API_KEY =+ env('THREE_WS_API_KEY') || env('THREE_WS_TOKEN') || env('THREE_WS_BEARER') || '';++// Per-request timeout (ms). These are small inbox reads and preference writes —+// generous enough to ride out a cold edge, 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;+})();++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/notifications-mcp';diff --git a/packages/notifications-mcp/src/lib/api.js b/packages/notifications-mcp/src/lib/api.jsnew file mode 100644index 000000000..db5876c11--- /dev/null+++ b/packages/notifications-mcp/src/lib/api.js@@ -0,0 +1,90 @@+// Real HTTP access to the three.ws autopilot API. No mocks, no fixtures — every+// call is a live, authenticated request to THREE_WS_BASE. The agent's Bearer+// credential is attached here (single HTTP client, single auth path); errors are+// normalized into one shape so tool handlers can surface a clean message ++// status to the MCP client.++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT, THREE_WS_API_KEY } from '../config.js';++// Thrown before any request when the server has no credential. Every autopilot+// route is owner-only, so a missing key is a config error, not an upstream 401.+export class MissingCredentialError extends Error {+ constructor() {+ super(+ 'No three.ws credential configured. Set THREE_WS_API_KEY to a three.ws API key ' ++ '(sk_live_… / sk_test_…) or OAuth access token for the agent owner — every autopilot ' ++ 'endpoint is owner-scoped and rejects unauthenticated requests.',+ );+ this.code = 'missing_credential';+ this.status = 401;+ }+}++/**+ * Call a three.ws autopilot endpoint and return its parsed JSON body. The+ * Authorization: Bearer header is added here from THREE_WS_API_KEY. Bearer auth+ * is exempt from CSRF server-side, so writes work without a CSRF token.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/autopilot/config`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]+ * @returns {Promise<any>} Parsed JSON response.+ * @throws {MissingCredentialError} when no credential is configured.+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),+ * and on upstream errors `.status` + `.body`.+ */+export async function apiRequest(path, { method = 'GET', query, body } = {}) {+ if (!THREE_WS_API_KEY) throw new MissingCredentialError();++ 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,+ // Capital-B "Bearer " — the server's CSRF guard exempts requests on+ // this exact prefix, so authenticated writes need no CSRF token.+ authorization: `Bearer ${THREE_WS_API_KEY}`,+ ...(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) {+ const message = data?.message || data?.error || `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/notifications-mcp/src/tools/get-preferences.js b/packages/notifications-mcp/src/tools/get-preferences.jsnew file mode 100644index 000000000..b1c5dee07--- /dev/null+++ b/packages/notifications-mcp/src/tools/get-preferences.js@@ -0,0 +1,34 @@+// `get_preferences` — read the agent's notification delivery preferences. Read-only.+//+// Wraps GET /api/notifications/preferences →+// { categories[], channels[], prefs: { categories, telegram_chat_id }, push }.+// The resolved matrix is what set_preferences edits: for each user-facing+// category, which channels (in_app / push / email / telegram) deliver it.++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_preferences',+ title: 'Get notification preferences',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Read the account's notification delivery preferences — the resolved channel matrix the platform " ++ 'uses to decide how each kind of event reaches the owner. Returns `categories` (the catalog of ' ++ 'user-facing groups: sales, purchases, social, irl, alerts, account — each with a label and ' ++ 'description), `channels` (the deliverable channels: in_app, push, email, telegram), `prefs` (the ' ++ 'effective per-category → per-channel on/off matrix with sparse user overrides already merged onto ' ++ 'defaults, plus the linked `telegram_chat_id` if any), and `push` (how many web-push devices are ' ++ 'registered). Read this before calling set_preferences so you patch from the real current state. ' ++ 'Read-only.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/notifications/preferences');+ return {+ ok: true,+ categories: Array.isArray(data?.categories) ? data.categories : [],+ channels: Array.isArray(data?.channels) ? data.channels : [],+ prefs: data?.prefs ?? { categories: {}, telegram_chat_id: null },+ push: data?.push ?? { subscribed_devices: 0 },+ };+ },+};diff --git a/packages/notifications-mcp/src/tools/list-notifications.js b/packages/notifications-mcp/src/tools/list-notifications.jsnew file mode 100644index 000000000..b24da194c--- /dev/null+++ b/packages/notifications-mcp/src/tools/list-notifications.js@@ -0,0 +1,65 @@+// `list_notifications` — read the agent's own notification inbox. Read-only.+//+// Wraps GET /api/notifications?limit=&type= → { notifications[], unread_count }.+// The inbox aggregates every inbound event for the account: pump/market alerts,+// sales & earnings, purchases, social mentions, IRL interactions, and account /+// security notices. Each row carries its delivered `payload` and a `read_at`+// timestamp (null ⇒ unread).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'list_notifications',+ title: 'List notifications',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Read the authenticated agent's notification inbox — the inbound-event feed the platform delivers " ++ 'to the account: market/pump alerts, sales & earnings, purchase receipts, social mentions, IRL ' ++ 'interactions, and account/security notices. Returns the most recent notifications (newest first), ' ++ 'each with its `id`, `type`, the event `payload`, a `read` boolean and `read_at` timestamp (null ⇒ ' ++ 'unread), and `created_at`; plus `unread_count`, the total number of unread items in the inbox. Pass ' ++ '`type` to return only one notification type (e.g. "pump_alert", "skill_purchased", ' ++ '"security_alert"), and `limit` (1–50, default 20) to cap how many rows come back. Read-only — use it ' ++ 'to surface alerts without polling, then mark_read / delete_notification to manage them.',+ inputSchema: {+ type: z+ .string()+ .regex(/^[a-z0-9_]{1,40}$/, 'type must be a lower_snake_case notification type')+ .optional()+ .describe(+ 'Optional filter: return only this notification type (e.g. "pump_alert", "skill_purchased", ' ++ '"referral_earned", "security_alert"). Lower_snake_case, ≤40 chars. Omit for all types.',+ ),+ limit: z+ .number()+ .int()+ .min(1)+ .max(50)+ .optional()+ .describe('How many notifications to return, newest first. 1–50, default 20.'),+ },+ async handler(args) {+ const type = args?.type ? String(args.type).trim() : undefined;+ const limit = args?.limit !== undefined ? Math.min(50, Math.max(1, Math.trunc(args.limit))) : undefined;++ const data = await apiRequest('/api/notifications', { query: { type, limit } });+ const notifications = Array.isArray(data?.notifications) ? data.notifications : [];++ return {+ ok: true,+ ...(type ? { type } : {}),+ unread_count: typeof data?.unread_count === 'number' ? data.unread_count : 0,+ count: notifications.length,+ notifications: notifications.map((n) => ({+ id: n.id,+ type: n.type,+ payload: n.payload ?? {},+ read: n.read_at != null,+ read_at: n.read_at ?? null,+ created_at: n.created_at,+ })),+ };+ },+};diff --git a/packages/notifications-mcp/src/tools/mark-read.js b/packages/notifications-mcp/src/tools/mark-read.jsnew file mode 100644index 000000000..bc0631645--- /dev/null+++ b/packages/notifications-mcp/src/tools/mark-read.js@@ -0,0 +1,61 @@+// `mark_read` — mark notifications read. Write, idempotent, non-destructive.+//+// Wraps two real endpoints:+// • POST /api/notifications/:id/read → mark one notification read+// • POST /api/notifications/read-all → mark every unread notification read+// Marking read only sets `read_at` (coalesced server-side), so re-running with+// the same args is a no-op — idempotent. It removes nothing.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'mark_read',+ title: 'Mark notifications read',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Mark notifications as read in the inbox. Pass `id` to mark a single notification read, or `all: ' ++ 'true` to mark every unread notification read at once (exactly one of the two is required). Marking ' ++ 'read only updates the read timestamp — it does not delete anything, and re-running with the same ' ++ 'arguments has no further effect (idempotent). When `id` is given, returns the notification id and ' ++ 'its `read_at`; when `all` is given, returns `marked_read`, the number of notifications newly marked ' ++ 'read. To remove a notification entirely use delete_notification instead.',+ inputSchema: {+ id: z+ .string()+ .uuid()+ .optional()+ .describe('UUID of a single notification to mark read (from list_notifications). Mutually exclusive with `all`.'),+ all: z+ .boolean()+ .optional()+ .describe('When true, mark every unread notification in the inbox read. Mutually exclusive with `id`.'),+ },+ async handler(args) {+ const id = args?.id ? String(args.id).trim() : '';+ const all = args?.all === true;++ if (all && id) {+ throw Object.assign(new Error('Pass either `id` (one notification) or `all: true` — not both.'), {+ code: 'validation_error',+ status: 400,+ });+ }++ if (all) {+ const data = await apiRequest('/api/notifications/read-all', { method: 'POST' });+ return { ok: true, scope: 'all', marked_read: typeof data?.marked_read === 'number' ? data.marked_read : 0 };+ }++ if (!id) {+ throw Object.assign(+ new Error('Provide `id` to mark one notification read, or `all: true` to mark every unread one read.'),+ { code: 'validation_error', status: 400 },+ );+ }++ const data = await apiRequest(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST' });+ return { ok: true, scope: 'one', id: data?.id ?? id, read_at: data?.read_at ?? null };+ },+};diff --git a/packages/tutor-mcp/README.md b/packages/tutor-mcp/README.mdnew file mode 100644index 000000000..1dfb8bf76--- /dev/null+++ b/packages/tutor-mcp/README.md@@ -0,0 +1,141 @@+<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/tutor-mcp</h1>++<p align="center"><strong>Manage a Pay-As-You-Learn tutoring session from any AI agent — read its itemized running tab and close it for an attested invoice.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/tutor-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/tutor-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/tutor-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/tutor-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 exposes the three.ws **Pay-As-You-Learn tutor ledger** over stdio. Read a tutoring session's itemized tab — one line item per answered question, with per-item cost and a running total — and close the session to seal an attested invoice.++The tutor bills per answered question; **this server's tools are free**. Viewing the running tab and closing the session never charge the learner — a learner must never pay to see what they owe or to end the session. Sessions are addressed by an opaque `sessionId`, so no API key and no signer are required — point `THREE_WS_BASE` at a deployment and go.++## Install++```bash+npm install @three-ws/tutor-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/tutor-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add tutor -- npx -y @three-ws/tutor-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "tutor": {+ "command": "npx",+ "args": ["-y", "@three-ws/tutor-mcp"]+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/tutor-mcp+```++## Tools++| Tool | Type | What it does |+| --------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------- |+| `load_session` | read | Read a session's itemized running tab by `sessionId` — line items (question, level, tokens, cost), status, and running total. |+| `close_session` | write | Finalize a session and return its attested invoice — seals the ledger with a SHA-256 attestation and locks further billing. |++Both tools are **free** and move no funds: the per-question answers are the paid action (handled elsewhere). `load_session` reads live data — the tab grows as questions are billed, so it is not idempotent. `close_session` mutates state (open → closed) but is itself idempotent: re-closing returns the same itemized total.++### Input parameters++**`load_session`** — `sessionId` (required, ≤100 chars).++**`close_session`** — `sessionId` (required, ≤100 chars).++## Example++```jsonc+// load_session+> { "sessionId": "learn-abc123" }+{+ "ok": true,+ "sessionId": "learn-abc123",+ "status": "open",+ "createdAt": "2026-06-24T03:40:00.000Z",+ "questionCount": 2,+ "lineItems": [+ { "n": 1, "question": "What is a Solana PDA?", "level": "intro", "outputTokens": 180, "costAtomics": 10000, "costUsd": "0.010000", "at": "2026-06-24T03:41:00.000Z" },+ { "n": 2, "question": "How do CPIs work?", "level": "intro", "outputTokens": 220, "costAtomics": 10000, "costUsd": "0.010000", "at": "2026-06-24T03:42:00.000Z" }+ ],+ "totalAtomics": 20000,+ "totalUsd": "0.020000"+}+```++```jsonc+// close_session+> { "sessionId": "learn-abc123" }+{+ "ok": true,+ "sessionId": "learn-abc123",+ "createdAt": "2026-06-24T03:40:00.000Z",+ "closedAt": "2026-06-24T03:45:00.000Z",+ "questionCount": 2,+ "lineItems": [ /* same itemized line items */ ],+ "totalAtomics": 20000,+ "totalUsd": "0.020000",+ "attestation": "sha256:…"+}+```++A `sessionId` with no stored history returns an empty open session (`questionCount: 0`) rather than an error — an honest "nothing billed yet", not a failure.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default |+| --------------------- | -------- | ------------------ |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |++## Links++- 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/tutor-mcp/server.json b/packages/tutor-mcp/server.jsonnew file mode 100644index 000000000..7cc30a174--- /dev/null+++ b/packages/tutor-mcp/server.json@@ -0,0 +1,49 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/tutor-mcp",+ "title": "three.ws Tutor",+ "description": "Read a Pay-As-You-Learn tutoring session's itemized tab and close it for an attested invoice.",+ "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/tutor-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/tutor-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 tutor session endpoint. 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 tutor session reads and the close call.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ }+ ]+ }+ ]+}diff --git a/packages/tutor-mcp/test/registration.test.mjs b/packages/tutor-mcp/test/registration.test.mjsnew file mode 100644index 000000000..de3d0505d--- /dev/null+++ b/packages/tutor-mcp/test/registration.test.mjs@@ -0,0 +1,76 @@+// Tool-surface invariants for @three-ws/tutor-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/tutor-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const EXPECTED_NAMES = [+ 'load_session',+ 'close_session',+];++// The single write tool — closing a session finalizes its ledger.+const WRITE_TOOLS = new Set(['close_session']);++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 2);+ 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`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ }+});++test('read tools are read-only and omit destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ if (WRITE_TOOLS.has(tool.name)) continue;+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ // Live ledger data moves between calls (the tab grows as questions are billed).+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++test('write tools declare readOnlyHint:false and an honest destructiveHint', () => {+ for (const tool of TOOLS) {+ if (!WRITE_TOOLS.has(tool.name)) continue;+ assert.equal(tool.annotations.readOnlyHint, false, `${tool.name} mutates state — readOnlyHint must be false`);+ // Closing is a non-funds-moving, idempotent seal, so it is explicitly non-destructive.+ assert.equal(typeof tool.annotations.destructiveHint, 'boolean', `${tool.name} must declare destructiveHint`);+ assert.equal(tool.annotations.destructiveHint, false, `${tool.name} closes (seals) a session — not destructive`);+ }+});++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`);+ }+});diff --git a/packages/vision-mcp/src/index.js b/packages/vision-mcp/src/index.jsnew file mode 100644index 000000000..c24d46669--- /dev/null+++ b/packages/vision-mcp/src/index.js@@ -0,0 +1,119 @@+#!/usr/bin/env node+// @three-ws/vision-mcp — MCP server entry point.+//+// Gives any AI assistant image understanding over stdio — the "let an agent see"+// surface of three.ws:+// • analyze_image — answer a prompt about an image (VQA, OCR, critique)+// • describe_image — natural-language description / alt text / caption+// • get_vision_status — is vision live, and what formats does it accept+//+// A thin wrapper over the PUBLIC /api/vision endpoint: a free-first NVIDIA NIM+// VLM chain with an automatic, server-side paid backstop. The caller never pays+// and needs no key — set THREE_WS_API_KEY only to raise the rate limit.+//+// Run standalone:+// node packages/vision-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 analyzeImage } from './tools/analyze-image.js';+import { def as describeImage } from './tools/describe-image.js';+import { def as visionStatus } from './tools/vision-status.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 = [+ analyzeImage,+ describeImage,+ visionStatus,+];++/**+ * 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: 'vision-mcp', title: 'three.ws Vision', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Vision MCP — let the agent see. analyze_image answers a prompt about an image (visual ' ++ 'Q&A, reading text in a screenshot, critiquing a 3D/avatar render); describe_image returns a ' ++ 'natural-language description for alt text or a caption, steerable by detail level and focus. Pass ' ++ 'each image as a public https `imageUrl` OR a base64 `image` (JPEG/PNG/WebP/GIF, up to 12 MB). ' ++ 'get_vision_status reports whether a VLM provider is live and which formats are accepted. The ' ++ 'platform runs every request against free NVIDIA NIM lanes first and an automatic paid backstop ' ++ 'otherwise — the caller never pays and needs no key. Set THREE_WS_API_KEY only to raise the rate ' ++ 'limit. Every tool is read-only: it analyzes images, it never stores or mutates anything.',+ },+ );++ 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(`[vision-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('[vision-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/vision-mcp/src/tools/describe-image.js b/packages/vision-mcp/src/tools/describe-image.jsnew file mode 100644index 000000000..b301e9e0c--- /dev/null+++ b/packages/vision-mcp/src/tools/describe-image.js@@ -0,0 +1,84 @@+// `describe_image` — get a natural-language description of an image. Read-only.+//+// Wraps POST /api/vision with a describe-oriented prompt the caller can steer+// with `detail` and `focus`. The convenience twin of analyze_image: when you+// don't have a specific question and just want to know what an image shows+// (alt text, a caption, a content summary), this returns prose, not a Q&A.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { buildVisionBody, ACCEPTED_IMAGE_TYPES } from '../lib/image.js';++const DETAIL_PROMPTS = {+ brief: 'Describe this image in one concise sentence. Be concrete; name the main subject and style.',+ standard:+ 'Describe this image in two to three sentences: the subject, the style, and the most notable details. Be concrete and concise.',+ detailed:+ 'Describe this image thoroughly: the main subject, composition, colors, style, setting, and any notable details or text. Write a few clear sentences.',+};++function buildDescribePrompt(detail, focus) {+ const base = DETAIL_PROMPTS[detail] || DETAIL_PROMPTS.standard;+ const lens = typeof focus === 'string' && focus.trim() ? ` Pay particular attention to: ${focus.trim().slice(0, 400)}.` : '';+ return `${base}${lens}`;+}++export const def = {+ name: 'describe_image',+ title: 'Describe an image in natural language',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Get a plain-language description of an image — ideal for alt text, captions, or a quick "what is this?" ' ++ 'read when you have no specific question. Supply the image as `imageUrl` (a public https URL) OR `image` ' ++ '(raw base64 / data: URI). Use `detail` to pick brief / standard / detailed, and `focus` to steer the ' ++ 'description toward something specific (e.g. "the clothing", "any visible text"). Returns the prose as ' ++ '`description`, plus the `provider` and `model` that served it (free NVIDIA NIM first, automatic paid ' ++ 'backstop otherwise — the caller never pays). Read-only; accepts JPEG, PNG, WebP, or GIF up to 12 MB.',+ inputSchema: {+ imageUrl: z+ .string()+ .url()+ .optional()+ .describe('Public https URL of the image to describe. Provide this OR `image`, not both.'),+ image: z+ .string()+ .optional()+ .describe('The image as raw base64 or a `data:image/...;base64,...` URI. Provide this OR `imageUrl`, not both.'),+ imageType: z+ .enum(ACCEPTED_IMAGE_TYPES)+ .optional()+ .describe('MIME type of a raw base64 `image` (ignored for data URIs / `imageUrl`). Defaults to image/jpeg.'),+ detail: z+ .enum(['brief', 'standard', 'detailed'])+ .default('standard')+ .describe('How much description to return: brief (one sentence), standard (2–3 sentences), or detailed (a full paragraph).'),+ focus: z+ .string()+ .max(400)+ .optional()+ .describe('Optional aspect to emphasize in the description (e.g. "any visible text", "the background", "the pose").'),+ },+ async handler(args) {+ const detail = ['brief', 'standard', 'detailed'].includes(args?.detail) ? args.detail : 'standard';+ const prompt = buildDescribePrompt(detail, args?.focus);+ // brief → fewer tokens, detailed → more headroom.+ const maxTokens = detail === 'brief' ? 128 : detail === 'detailed' ? 768 : 384;+ const { body, source } = buildVisionBody({+ imageUrl: args?.imageUrl,+ image: args?.image,+ imageType: args?.imageType,+ prompt,+ maxTokens,+ });+ const data = await apiRequest('/api/vision', { method: 'POST', body });+ return {+ ok: true,+ description: typeof data?.text === 'string' ? data.text : '',+ detail,+ provider: data?.provider ?? null,+ model: data?.model ?? null,+ image_source: source,+ };+ },+};diff --git a/packages/vision-mcp/src/tools/vision-status.js b/packages/vision-mcp/src/tools/vision-status.jsnew file mode 100644index 000000000..f8814e1aa--- /dev/null+++ b/packages/vision-mcp/src/tools/vision-status.js@@ -0,0 +1,31 @@+// `get_vision_status` — is image understanding live, and what does it accept?+// Read-only.+//+// Wraps GET /api/vision (the capability probe). Cheap and unauthenticated — call+// it before offering a describe/analyze affordance, or to confirm the deployment+// has a vision provider configured at all.++import { apiRequest } from '../lib/api.js';+import { ACCEPTED_IMAGE_TYPES } from '../lib/image.js';++export const def = {+ name: 'get_vision_status',+ title: 'Vision availability + accepted formats',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Check whether the three.ws vision pipeline is live on the target deployment and which image formats it ' ++ 'accepts. Returns `configured` (true when at least one VLM provider — a free NVIDIA NIM lane or the paid ' ++ 'backstop — can serve a request) and `image_types` (the accepted MIME types). Use this before calling ' ++ 'analyze_image / describe_image so the agent can decide whether to offer a "describe this image" action. ' ++ 'No image, no key, no cost.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/vision', { method: 'GET' });+ return {+ ok: true,+ configured: Boolean(data?.configured),+ image_types: Array.isArray(data?.imageTypes) ? data.imageTypes : ACCEPTED_IMAGE_TYPES,+ max_image_mb: 12,+ };+ },+};diff --git a/packages/vision-mcp/test/registration.test.mjs b/packages/vision-mcp/test/registration.test.mjsnew file mode 100644index 000000000..21333f96d--- /dev/null+++ b/packages/vision-mcp/test/registration.test.mjs@@ -0,0 +1,98 @@+// Tool-surface invariants for @three-ws/vision-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. These tests run offline — they never touch the network.+//+// Run: node --test packages/vision-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';+import { buildVisionBody } from '../src/lib/image.js';++const EXPECTED_NAMES = ['analyze_image', 'describe_image', 'get_vision_status'];++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 3);+ 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('every tool is a read-only, live-data query', () => {+ for (const tool of TOOLS) {+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live model`);+ // A VLM is non-deterministic and the live provider chain moves — never idempotent.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} is non-deterministic, not idempotent`);+ }+});++test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ assert.equal(+ tool.annotations.destructiveHint,+ undefined,+ `${tool.name} is read-only — destructiveHint should be omitted`,+ );+ }+});++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('buildVisionBody validates image input at the boundary', () => {+ // Exactly one source is required.+ assert.throws(() => buildVisionBody({ prompt: 'hi' }), /image is required/);+ assert.throws(+ () => buildVisionBody({ imageUrl: 'https://three.ws/a.png', image: 'AAAA' }),+ /not both/,+ );+ // URL: https only, no private hosts.+ assert.throws(() => buildVisionBody({ imageUrl: 'http://three.ws/a.png' }), /https/);+ assert.throws(() => buildVisionBody({ imageUrl: 'https://localhost/a.png' }), /public host/);+ assert.throws(() => buildVisionBody({ imageUrl: 'https://192.168.1.5/a.png' }), /public host/);+ // Base64: must be valid base64.+ assert.throws(() => buildVisionBody({ image: 'not valid base64 !!!' }), /base64/);++ // Happy paths produce the endpoint's body shape.+ const url = buildVisionBody({ imageUrl: 'https://three.ws/render.png', prompt: 'what is this?' });+ assert.equal(url.source, 'url');+ assert.equal(url.body.imageUrl, 'https://three.ws/render.png');+ assert.equal(url.body.prompt, 'what is this?');++ const b64 = buildVisionBody({ image: 'iVBORw0KGgo=', imageType: 'image/png', maxTokens: 99999 });+ assert.equal(b64.source, 'base64');+ assert.equal(b64.body.image, 'iVBORw0KGgo=');+ assert.equal(b64.body.imageType, 'image/png');+ // maxTokens clamped to the endpoint's ceiling.+ assert.equal(b64.body.maxTokens, 2048);++ // data: URI carries its own mime type.+ const dataUri = buildVisionBody({ image: 'data:image/webp;base64,UklGRg==' });+ assert.equal(dataUri.body.imageType, 'image/webp');+ assert.equal(dataUri.body.image, 'UklGRg==');+});diff --git a/public/changelog.json b/public/changelog.jsonindex 2ed9ad6c1..fd510a2e7 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T06:13:28.247Z",+ "generated_at": "2026-06-24T06:17:04.845Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -69,6 +69,17 @@"feature"]},+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "AI agents can now manage a Pay-As-You-Learn tutoring session over MCP — read the running tab, close it for an attested invoice",+ "summary": "A new Model Context Protocol server, @three-ws/tutor-mcp, exposes the tutor session ledger to any AI assistant. An agent can load a learning session's itemized running tab by its id — every answered question listed as a line item with its level, output tokens, per-question cost, and timestamp, plus the running total — and close the session to seal a finalized, SHA-256-attested invoice that locks any further billing to it. Both tools are free and move no funds: answering questions is the paid action, but a learner is never charged to see what they owe or to end the session. Sessions are addressed by an opaque id, so there's no key or signer to configure; everything runs live against the real three.ws tutor API.",+ "link": null,+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-24","type": "update",@@ -102,6 +113,17 @@"feature"]},+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "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",+ "summary": "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`.",+ "link": "/changelog",+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-24","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 57ef5f4e0..2b22d1596 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -54,6 +54,14 @@<category>sdk</category><description>New @three-ws/signals-mcp server puts the whole signal marketplace in any AI agent's hands. Agents can browse the public feed directory ranked by proven realized edge, rank publishers by real on-chain performance on the mirror leaderboard, subscribe one of their own agents to a feed (simulate mode to shadow it for free, or live mode to pay the publisher in USDC over x402 and auto-mirror real trades), track their subscriptions with delivery history and realized ROI, and flip an instant kill switch to halt all paying and trading on the spot. Discovery and the leaderboard are open to everyone; subscribing needs a three.ws API key. Everything is live from the real API — nothing mocked.</description></item>+ <item>+ <title>AI agents can now manage a Pay-As-You-Learn tutoring session over MCP — read the running tab, close it for an attested invoice</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:AI agents can now manage a Pay-As-You-Learn tutoring session over MCP — read the running tab, close it for an attested invoice</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>A new Model Context Protocol server, @three-ws/tutor-mcp, exposes the tutor session ledger to any AI assistant. An agent can load a learning session's itemized running tab by its id — every answered question listed as a line item with its level, output tokens, per-question cost, and timestamp, plus the running total — and close the session to seal a finalized, SHA-256-attested invoice that locks any further billing to it. Both tools are free and move no funds: answering questions is the paid action, but a learner is never charged to see what they owe or to end the session. Sessions are addressed by an opaque id, so there's no key or signer to configure; everything runs live against the real three.ws tutor API.</description>+ </item><item><title>AI agents can now manage their own autopilot scopes and spend limits over MCP</title><link>https://three.ws/changelog</link>@@ -78,6 +86,14 @@<category>sdk</category><description>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.</description></item>+ <item>+ <title>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</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24: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</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <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>Buy live $THREE market intel over x402 — right on the IBM partnership page</title><link>https://three.ws/bazaar</link>diff --git a/public/features.json b/public/features.jsonindex 039c511e3..c3355b193 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T06:13:28.211Z",+ "generated_at": "2026-06-24T06:17:04.811Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",