Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add MCP server packages, idle avatar, and showcase/agent-detail updates
nirholas07c089e4723f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b4f019d5b..5d973b288 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,15 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-24- **Docs · SAS Credentialed Attestations** (`/docs/sas-attestations`) — Set up the three.ws authority wallet and SAS_AUTHORITY_SECRET, bootstrap the Solana Attestation Service credential and schemas, and issue or read credentialed attestations.+- **Agent profile avatars now stand and breathe instead of freezing in a T-pose** — Open any agent's profile and its 3D body is alive: the avatar settles into a natural standing idle — arms down, weight on its feet, subtle breathing and blinks — and turns slowly on a turntable, instead of hanging in the stiff arms-out T-pose the old static viewer showed. The profile now runs the same real-time animation engine as the rest of the platform, so the idle and gesture clips are retargeted onto whatever rig your avatar uses. Tap the avatar to open it full-screen and orbit it freely. If a device can't run 3D, it cleanly falls back to a still image. (`/agents`) `[improvement]`+- **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 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]`+- **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]`## 2026-06-23diff --git a/data/changelog.json b/data/changelog.jsonindex eb60298b4..a40d4b783 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,80 @@{"$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 run your copy-trading over MCP — follow leaders, tune guard rules, and track fees owed",+ "summary": "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.",+ "tags": [+ "sdk",+ "feature"+ ],+ "link": "/changelog"+ },+ {+ "date": "2026-06-24",+ "title": "AI agents can now manage their own portfolio, PnL, and on-chain transfers over MCP",+ "summary": "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.",+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "title": "Agents can now record and verify each other's actions over MCP — signed, on-chain-provable provenance",+ "summary": "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.",+ "tags": [+ "sdk",+ "feature",+ "security"+ ]+ },+ {+ "date": "2026-06-24",+ "title": "AI agents can now find and follow copy-trade signal feeds over MCP",+ "summary": "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.",+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "title": "AI agents can now manage their own autopilot scopes and spend limits over MCP",+ "summary": "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.",+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "title": "Agent profile avatars now stand and breathe instead of freezing in a T-pose",+ "summary": "Open any agent's profile and its 3D body is alive: the avatar settles into a natural standing idle — arms down, weight on its feet, subtle breathing and blinks — and turns slowly on a turntable, instead of hanging in the stiff arms-out T-pose the old static viewer showed. The profile now runs the same real-time animation engine as the rest of the platform, so the idle and gesture clips are retargeted onto whatever rig your avatar uses. Tap the avatar to open it full-screen and orbit it freely. If a device can't run 3D, it cleanly falls back to a still image.",+ "tags": [+ "improvement"+ ],+ "link": "/agents"+ },+ {+ "date": "2026-06-24",+ "title": "Agent Studio's Brain editor now has a clear Save & exit",+ "summary": "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.",+ "tags": [+ "improvement"+ ],+ "link": "/agent-studio"+ },+ {+ "date": "2026-06-24",+ "title": "Buy live $THREE market intel over x402 — right on the IBM partnership page",+ "summary": "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.",+ "tags": [+ "feature"+ ],+ "link": "/bazaar"+ },{"date": "2026-06-24","title": "Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase",diff --git a/mcp-prompts/00-INDEX.md b/mcp-prompts/00-INDEX.mdnew file mode 100644index 000000000..36d953907--- /dev/null+++ b/mcp-prompts/00-INDEX.md@@ -0,0 +1,53 @@+# three.ws MCP buildout — full coverage prompts++Goal: take MCP coverage from the **14 shipped servers** to **100% of three.ws's real backends**. Each file below is a self-contained prompt — open a **new chat**, paste the file's contents, and let the agent build that one server end to end.++## How to run++1. Open a fresh chat in this repo.+2. Paste the **entire contents** of one `NN-*.md` file as your message.+3. The agent will read `_SHARED-CONVENTIONS.md`, the reference packages, and the real API route, then build + test the server.+4. One server per chat keeps context clean. Run them in any order — they don't depend on each other.++Every prompt points at [`_SHARED-CONVENTIONS.md`](_SHARED-CONVENTIONS.md), which encodes the exact package pattern (copied from `packages/intel-mcp`). Read that file first if you want to know what every build has in common.++## The servers (each wraps a real, existing endpoint)++### Tier 1 — the autonomous-agent control plane (highest impact)+| # | Server | Wraps | What it unlocks |+|---|--------|-------|-----------------|+| 01 | `autopilot-mcp` | `api/autopilot/` | An agent setting its own scopes, spend limits, and propose/execute/undo |+| 02 | `portfolio-mcp` | `api/portfolio/`, `api/trades/` | Read/write its own positions, PnL, balances, transfers |+| 03 | `provenance-mcp` | `api/agent-actions.js` | Append-only, signed, on-chain-verifiable action log |+| 04 | `copy-mcp` | `api/copy/` | Manage copy-trade follows + read executions/earnings |+| 05 | `signals-mcp` | `api/signals/`, `api/mirror/` | Discover, subscribe to, and rank trading-signal feeds |+| 06 | `alerts-mcp` | `api/alerts/` | Create/manage pump.fun alert rules + delivery history |++### Tier 2 — account, surface, and discovery+| # | Server | Wraps | What it unlocks |+|---|--------|-------|-----------------|+| 07 | `notifications-mcp` | `api/notifications/`, `api/push/` | Query the inbox, manage prefs, register push devices |+| 08 | `billing-mcp` | `api/billing/` | Self-query quotas, usage rollups, invoices |+| 09 | `activity-mcp` | `api/trending.js`, `api/leaderboard.js`, `api/feed.js` | Trending agents/coins, $THREE holder board, activity ticker |+| 10 | `agenc-mcp` | `api/agenc/` | On-chain task marketplace + agent registry (ERC-8004 coordination) |++### Tier 3 — AI capability surfaces+| # | Server | Wraps | What it unlocks |+|---|--------|-------|-----------------|+| 11 | `vision-mcp` | `api/vision.js` | Image understanding (NVIDIA NIM VLM + fallback) |+| 12 | `brain-mcp` | `api/brain/` | Multi-provider LLM router (Claude / GPT / Qwen / Nemotron …) |+| 13 | `audio-mcp` | `api/a2f.js`, `api/asr.js`, `api/tts/`, `api/mocap/` | Audio-to-face lipsync, speech-to-text, TTS, motion capture |+| 14 | `kol-mcp` | `api/kol/` | Per-wallet KOL portfolio + trade analytics (Birdeye proxy) |++### Tier 4 — product surfaces with real backends+| # | Server | Wraps | What it unlocks |+|---|--------|-------|-----------------|+| 15 | `clash-mcp` | `api/clash/` | Coin Clash faction game state + enlist/rally |+| 16 | `tutor-mcp` | `api/tutor/` | Learning-session ledger (load/close, itemized billing) |+| 17 | `loom-mcp` | `api/loom.js` | 3D creation gallery (feed, submit, fetch) |++## After all 17 ship++Coverage goes from 14 → **31 servers**. The launch story becomes "three.ws is the operating layer for autonomous agents" — they create in 3D, pay per call, run their own portfolio, set their own limits, and prove their own track record on-chain. That's the X article worth writing. (See the discussion that produced these prompts.)++> Note: tool lists in each prompt are **proposed** — the first instruction in every prompt is to read the real route and build against what the code actually exposes. If a backend turns out thinner or richer than described, the agent adapts. No mocks, ever.diff --git a/mcp-prompts/01-autopilot-mcp.md b/mcp-prompts/01-autopilot-mcp.mdnew file mode 100644index 000000000..c4e881821--- /dev/null+++ b/mcp-prompts/01-autopilot-mcp.md@@ -0,0 +1,32 @@+# Build `@three-ws/autopilot-mcp` — an agent's own execution control plane over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server lets an AI agent configure and drive its **own** autonomous-execution boundaries: scopes, daily spend limits, auto-execute settings, and the propose → execute → undo loop.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — the exact package pattern. Follow it precisely; copy `packages/intel-mcp` for structure.+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (the reference for authenticated/write tools and how this platform authorizes agent actions).+4. **The real backend:** everything under `api/autopilot/`. Read every handler. Confirm the exact request/response shapes, how an agent authenticates, where config lives (`agent_identities.meta.autopilot`), and how the append-only `agent_actions` log records execution. Build tools against what the code actually does.++## What this server is+The keystone of the autonomous-agent story. Today autopilot config and execution are only reachable through the UI/API. This server exposes them so an agent can manage its own guardrails and act within them — without a human in the loop, but bounded by real scopes and spend caps enforced server-side.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_autopilot_config` | read | GET autopilot config | scopes, daily spend limit, auto-execute flags |+| `set_autopilot_config` | write (idempotent) | PUT/POST config | updated config |+| `generate_proposals` | write | proposal generation | candidate actions the agent could take |+| `execute_proposal` | write (destructive) | execute | execution result + action-log id |+| `undo_action` | write | undo/revert | revert result |+| `list_autopilot_activity` | read | activity/`agent_actions` | recent autopilot actions + outcomes |+| `compute_trust` | read | trust score | the agent's computed trust/reputation |++## Auth / writes+This is a **write-heavy, funds-touching** server. `execute_proposal` moves real value — annotate `readOnlyHint:false`, `destructiveHint:true`, and say so loudly in the description. Read how `api/autopilot` authenticates the agent (API key / agent token / wallet signature) and mirror `packages/avatar-agent-mcp`'s approach exactly. Add the required credential as an env var in `server.json` (`isRequired` true for write paths). Never bypass server-side scope/spend enforcement.++## Package identity+- npm `@three-ws/autopilot-mcp` · mcpName `io.github.nirholas/autopilot-mcp` · dir `packages/autopilot-mcp` · bin `autopilot-mcp`++## Done means+Everything in `_SHARED-CONVENTIONS.md` → Definition of done. Verify with `npm run inspect` that read tools return real config/activity. Add a `data/changelog.json` entry (tags `sdk`,`feature`) — plain-language, e.g. "AI agents can now set their own autopilot scopes and spend limits over MCP." Run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/02-portfolio-mcp.md b/mcp-prompts/02-portfolio-mcp.mdnew file mode 100644index 000000000..c103afc08--- /dev/null+++ b/mcp-prompts/02-portfolio-mcp.md@@ -0,0 +1,30 @@+# Build `@three-ws/portfolio-mcp` — an agent's portfolio, PnL, and transfers over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server gives an AI agent programmatic read/write access to its **own** trading state: positions, realized PnL, wallet balances, the public trade feed, and signed on-chain transfers.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (the reference for wallet/signer/transfer tools).+4. **The real backend:** `api/portfolio/` and `api/trades/`. Read every handler. Confirm shapes for portfolio summary/history, the trades feed (closed positions w/ PnL), balance snapshots (Helius/Alchemy), and the signed-transfer route. Build against the real behavior.++## What this server is+The "what do I hold and how am I doing" surface for autonomous agents. Read-only analytics (summary, history, feed, balances) plus one real write: initiating a signed transfer. Pairs with `autopilot-mcp` (config) and `provenance-mcp` (audit).++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_portfolio_summary` | read | portfolio summary | holdings, value, unrealized/realized PnL |+| `get_portfolio_history` | read | portfolio history | time-series snapshots |+| `get_trades_feed` | read | `api/trades/feed` | closed positions with PnL |+| `get_wallet_balances` | read | balances | per-token balances (live) |+| `send_transfer` | write (destructive) | signed transfer | tx signature + status |++## Auth / writes+Read tools may be public or key-scoped — check the route. `send_transfer` is **funds-moving**: `readOnlyHint:false`, `destructiveHint:true`, idempotent:false, and a description that states it broadcasts a real Solana transaction. Mirror how `packages/avatar-agent-mcp` handles the signer/key. Add the signer credential as a `server.json` env var (`isRequired` true for the transfer tool). $THREE is the only coin you may name; the transfer tool accepts an arbitrary mint **as runtime input** only — never hardcode a non-`$THREE` mint.++## Package identity+- npm `@three-ws/portfolio-mcp` · mcpName `io.github.nirholas/portfolio-mcp` · dir `packages/portfolio-mcp` · bin `portfolio-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify read tools return real data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/03-provenance-mcp.md b/mcp-prompts/03-provenance-mcp.mdnew file mode 100644index 000000000..36922f5a0--- /dev/null+++ b/mcp-prompts/03-provenance-mcp.md@@ -0,0 +1,28 @@+# Build `@three-ws/provenance-mcp` — the agent action-provenance log over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes the **append-only, signed, on-chain-verifiable** agent action log so agents can record what they did and audit each other.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (for the authenticated append path + signatures).+4. **The real backend:** `api/agent-actions.js`. Read the handler. Confirm the record shape (signature, actor, action type, outcome), cursor pagination, append semantics, and how appends are authenticated/signed. This is an immutable log — records are never deleted.++## What this server is+The trust layer. Every agent action is recorded in an append-only `agent_actions` table with a signature and outcome, cursor-paginated and on-chain verifiable. This server lets one agent append its own actions and lets any agent read/verify another's provenance — the foundation for agent-to-agent trust.++## Proposed tools (confirm/adjust against the real route)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_agent_actions` | read | GET (paginated) | action records + next cursor |+| `query_action` | read | GET one | a single action + signature/outcome |+| `append_agent_action` | write (non-idempotent, non-destructive) | POST | the appended record + id |++## Auth / writes+`append_agent_action` writes to an immutable ledger — `readOnlyHint:false`, `idempotentHint:false`, `destructiveHint:false` (it never overwrites/deletes). It must produce a real signature exactly as the route expects; mirror `packages/avatar-agent-mcp`'s signing. Read tools are public/verification-grade. Add any signer/key as a `server.json` env var, required only for the append tool.++## Package identity+- npm `@three-ws/provenance-mcp` · mcpName `io.github.nirholas/provenance-mcp` · dir `packages/provenance-mcp` · bin `provenance-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `list`/`query` return real ledger records via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`,`security`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/04-copy-mcp.md b/mcp-prompts/04-copy-mcp.mdnew file mode 100644index 000000000..1f3ec16b8--- /dev/null+++ b/mcp-prompts/04-copy-mcp.md@@ -0,0 +1,31 @@+# Build `@three-ws/copy-mcp` — copy-trading follows over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server lets an AI agent manage its **own** copy-trade relationships: follow/unfollow leaders, tune guard rules, and read executions + earnings — all headless, no UI.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template; note it already has `copy_smart_wallets` for *discovery* — this server is for *managing subscriptions*, don't duplicate discovery) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The real backend:** `api/copy/subscriptions` and `api/copy/executions`. Read the handlers. Confirm the subscription shape (leader, status, guard rules), execution log shape, and earnings. Build against the real behavior.++## What this server is+The copy-trading control surface. `copy_subscriptions` and `copy_executions` tables back a full follow/guard/earn system reachable only via UI today. This server makes it agent-drivable.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_subscriptions` | read | GET subscriptions | follows + leader info + status |+| `create_subscription` | write (idempotent) | POST | created/updated subscription |+| `update_subscription` | write (idempotent) | PATCH | updated subscription (guard rules, pause) |+| `cancel_subscription` | write (destructive) | DELETE | cancellation result |+| `get_executions` | read | GET executions | copy-execution log |+| `get_earnings` | read | GET earnings | earnings rollup |++## Auth / writes+Subscriptions belong to a user/agent — every tool is account-scoped. Read how `api/copy` authenticates and mirror `packages/avatar-agent-mcp`. Writes that change money flow (`create`/`update`/`cancel`) annotate `readOnlyHint:false`; `cancel` is `destructiveHint:true`. Add the credential as a required `server.json` env var.++## Package identity+- npm `@three-ws/copy-mcp` · mcpName `io.github.nirholas/copy-mcp` · dir `packages/copy-mcp` · bin `copy-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify reads return real subscription/execution data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/05-signals-mcp.md b/mcp-prompts/05-signals-mcp.mdnew file mode 100644index 000000000..2a4f6a369--- /dev/null+++ b/mcp-prompts/05-signals-mcp.md@@ -0,0 +1,31 @@+# Build `@three-ws/signals-mcp` — trading-signal feeds + publisher leaderboard over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server lets an AI agent discover trading-signal feeds, subscribe to them, read delivery history + performance, and rank signal publishers.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template; it has `signal_feed` for reading *one* feed's accuracy — this server adds discovery + subscription + the publisher board, don't duplicate the single-feed read) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The real backend:** `api/signals/` (subscribe, feed, stream) and `api/mirror/` (publisher leaderboard). Read the handlers. Confirm feed list shape, per-signal pricing, delivery tracking, performance metrics, and the mirror leaderboard. Build against reality.++## What this server is+The signal-marketplace surface. `signal_subscriptions`, `signal_deliveries`, `signal_feeds` back a full subscribe-and-track system; `api/mirror` ranks publishers by realized performance. Reachable only via UI today.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_signal_feeds` | read | GET feeds | feeds + pricing + performance summary |+| `get_signal_detail` | read | GET one | a feed's detail + recent deliveries |+| `subscribe_signal` | write (idempotent) | POST subscribe | subscription result |+| `get_delivery_history` | read | GET deliveries | delivery log with realized ROI |+| `get_feed_performance` | read | GET performance | accuracy/ROI metrics |+| `get_mirror_leaderboard` | read | `api/mirror` | publishers ranked by performance |++## Auth / writes+Discovery/leaderboard are public/read-only. `subscribe_signal` is account-scoped (and may settle payment) — read how `api/signals` authenticates and whether subscription costs money; if it does, state it in the description and mirror the platform's payment handling. Add credentials as `server.json` env vars, required only for the write tool.++## Package identity+- npm `@three-ws/signals-mcp` · mcpName `io.github.nirholas/signals-mcp` · dir `packages/signals-mcp` · bin `signals-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify reads return real feeds/leaderboard via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/06-alerts-mcp.md b/mcp-prompts/06-alerts-mcp.mdnew file mode 100644index 000000000..68c1f9d91--- /dev/null+++ b/mcp-prompts/06-alerts-mcp.md@@ -0,0 +1,30 @@+# Build `@three-ws/alerts-mcp` — pump.fun alert rules over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server lets an AI agent define and manage its **own** pump.fun monitoring rules with multi-channel delivery (in-app, webhook, Telegram), and read alert history.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The real backend:** `api/alerts/` (esp. `rules`). Read the handlers. Confirm the rule shape (event type, thresholds, delivery channel config), how rules are evaluated by the `pumpfun-monitor` cron, and the delivery/history shape. Build against reality.++## What this server is+The market-monitoring control surface. Users define alert rules on pump.fun events; a cron evaluates them and delivers via in-app/webhook/Telegram with delivery tracking. This server makes rule management agent-drivable so an agent can watch the market without UI friction.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_alert_rules` | read | GET rules | the agent's rules |+| `create_alert_rule` | write (idempotent) | POST | created rule |+| `update_alert_rule` | write (idempotent) | PATCH | updated rule |+| `delete_alert_rule` | write (destructive) | DELETE | deletion result |+| `get_alert_history` | read | GET history | fired alerts + delivery status |++## Auth / writes+Rules are account-scoped. Read how `api/alerts` authenticates and mirror `packages/avatar-agent-mcp`. `create`/`update`/`delete` are writes (`delete` is destructive). Webhook/Telegram targets are runtime input — validate them at the boundary. Add the credential as a required `server.json` env var. Any coin referenced in a rule is **runtime input**; never hardcode a non-`$THREE` mint.++## Package identity+- npm `@three-ws/alerts-mcp` · mcpName `io.github.nirholas/alerts-mcp` · dir `packages/alerts-mcp` · bin `alerts-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify list/history return real data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/07-notifications-mcp.md b/mcp-prompts/07-notifications-mcp.mdnew file mode 100644index 000000000..4da6e965b--- /dev/null+++ b/mcp-prompts/07-notifications-mcp.md@@ -0,0 +1,32 @@+# Build `@three-ws/notifications-mcp` — the agent notification inbox + push over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server lets an AI agent read its **own** notification inbox (pump alerts, trades, agent events), manage read state and preferences, and register/unregister web-push devices.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The real backend:** `api/notifications/` and `api/push/`. Read the handlers. Confirm the `user_notifications` record shape (type, source, read status), preference shape, and the push device-registration flow. Build against reality.++## What this server is+The inbound-event surface. A persistent inbox aggregates pump alerts, trades, and agent events with read tracking and type filtering; `api/push` registers devices for web push. This server lets an agent query inbound alerts without polling and manage delivery prefs.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_notifications` | read | GET inbox | notifications (filter by type/read) |+| `mark_read` | write (idempotent) | POST/PATCH | updated read state |+| `delete_notification` | write (destructive) | DELETE | deletion result |+| `get_preferences` | read | GET prefs | notification preferences |+| `set_preferences` | write (idempotent) | PUT prefs | updated preferences |+| `register_push_device` | write (idempotent) | POST `api/push/subscribe` | registration result |+| `unregister_push_device` | write (destructive) | DELETE | result |++## Auth / writes+Everything is account-scoped. Read how `api/notifications`/`api/push` authenticate and mirror `packages/avatar-agent-mcp`. Annotate writes honestly (`delete`/`unregister` are destructive). Add the credential as a required `server.json` env var.++## Package identity+- npm `@three-ws/notifications-mcp` · mcpName `io.github.nirholas/notifications-mcp` · dir `packages/notifications-mcp` · bin `notifications-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `list_notifications` returns real inbox data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/08-billing-mcp.md b/mcp-prompts/08-billing-mcp.mdnew file mode 100644index 000000000..9da50cd24--- /dev/null+++ b/mcp-prompts/08-billing-mcp.md@@ -0,0 +1,30 @@+# Build `@three-ws/billing-mcp` — quotas, usage, and invoices over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server lets an AI agent self-query its **own** plan quotas, usage rollups (avatars, agents, MCP calls, LLM calls), and invoices/receipts — without needing the human account owner.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (for how account-scoped calls authenticate).+4. **The real backend:** `api/billing/`. Read the handlers. Confirm shapes for plan quotas, usage rollups (`usage_events`), and invoice/receipt generation. Build against reality.++## What this server is+The account-economics surface. `plan_quotas`, `usage_events`, and billing tables back real quota/usage/invoice data. This server lets an agent check how much of its quota it has left and pull billing history programmatically — mostly read-only, with optional export.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_billing_summary` | read | GET summary | plan, quotas, current usage |+| `query_usage` | read | GET usage | usage rollups by metric/period |+| `list_invoices` | read | GET invoices | invoice list |+| `get_receipt` | read | GET one | a single receipt |+| `export_billing_history` | read | GET export | exportable history payload |++## Auth / writes+This is essentially **read-only but account-scoped** — it exposes private billing data, so it requires the account credential. Read how `api/billing` authenticates and mirror `packages/avatar-agent-mcp`. All tools `readOnlyHint:true`, `openWorldHint:true`, `idempotentHint:false`. Add the credential as a **required** `server.json` env var (without it the server can't read anything).++## Package identity+- npm `@three-ws/billing-mcp` · mcpName `io.github.nirholas/billing-mcp` · dir `packages/billing-mcp` · bin `billing-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify summary/usage return real data via `npm run inspect` with a real credential. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/09-activity-mcp.md b/mcp-prompts/09-activity-mcp.mdnew file mode 100644index 000000000..f41c9139c--- /dev/null+++ b/mcp-prompts/09-activity-mcp.md@@ -0,0 +1,33 @@+# Build `@three-ws/activity-mcp` — trending, leaderboards, and the activity ticker over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server gives an AI agent the platform's live discovery surface: trending agents and coins, the $THREE holder leaderboard, and the site-wide activity ticker.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` — the closest analog; this server is also fully **read-only**.+4. **The real backend:** `api/trending.js`, `api/leaderboard.js`, `api/feed.js`, `api/feed-stream.js`. Read each handler. Confirm shapes for trending agents (by chat activity), trending coins (by oracle conviction), $THREE holder rankings + tier info, and the activity feed events. Build against reality.++## What this server is+The "what's hot right now" surface. Trending agents/coins, the $THREE holder board with tiers, and the activity ticker (agent chats, trades, launches) are all live and public. This server makes them agent-queryable for discovery and situational awareness.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_trending_agents` | read | `api/trending.js` | agents ranked by activity |+| `get_trending_coins` | read | `api/trending.js` | coins ranked by oracle conviction |+| `get_holder_leaderboard` | read | `api/leaderboard.js` | $THREE holder rankings |+| `get_tier_info` | read | `api/leaderboard.js` | holder tier thresholds/benefits |+| `get_feed_events` | read | `api/feed.js` | recent site-wide activity events |++## Coin rule+The holder leaderboard is for **$THREE** — the only coin. Trending-coins data is platform launch-directory data rendered from real launch records at runtime (allowed per CLAUDE.md); never hardcode, market, or recommend any specific non-$THREE mint in code or copy.++## Auth / writes+Fully **read-only**, public data. Every tool: `readOnlyHint:true`, `openWorldHint:true`, `idempotentHint:false`, no `destructiveHint`. No key/signer required (mirror intel-mcp's "no key" posture). Do **not** wrap `feed-stream` as a streaming tool unless the MCP shape supports it cleanly — a paginated `get_feed_events` is the right surface.++## Package identity+- npm `@three-ws/activity-mcp` · mcpName `io.github.nirholas/activity-mcp` · dir `packages/activity-mcp` · bin `activity-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify all tools return real live data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/10-agenc-mcp.md b/mcp-prompts/10-agenc-mcp.mdnew file mode 100644index 000000000..b4881a3b7--- /dev/null+++ b/mcp-prompts/10-agenc-mcp.md@@ -0,0 +1,31 @@+# Build `@three-ws/agenc-mcp` — the AgenC task marketplace + agent registry over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes the AgenC on-chain coordination protocol: the task marketplace, the agent registry, and task lifecycle — so agents can find work, post work, and resolve other agents' identities.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The flagship `mcp-server/`** — it already has `agenc_list_tasks`, `agenc_get_task`, `agenc_get_agent` as paid x402 tools. **Do not duplicate those verbatim.** This standalone server is the *free, read-first* AgenC surface plus the write/link paths; reuse the dispatch logic, don't re-charge for reads that are free elsewhere. Check `api/agenc/` for the real routes and confirm which are free vs paid.+5. **The real backend:** everything under `api/agenc/`. Read the handlers; confirm task shape, registry shape, lifecycle states, and how linking/posting authenticates.++## What this server is+The agent-to-agent coordination surface. AgenC is an on-chain task marketplace + agent registry (ERC-8004-style identity). This server lets agents browse and query tasks/agents (read) and link/post (write), forming the coordination backbone alongside `provenance-mcp`.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_tasks` | read | GET tasks | open/active tasks |+| `get_task` | read | GET one | task detail + lifecycle state |+| `get_agent` | read | GET agent | registry entry / identity |+| `link_agent` | write | POST link | link result |+| `query_x402_services` | read | GET services | x402 service directory (if exposed here) |++## Auth / writes+Reads should be free (no key) where the route allows. Writes (`link_agent`) are account/identity-scoped — read how `api/agenc` authenticates and mirror `packages/avatar-agent-mcp`. Add credentials as `server.json` env vars, required only for writes.++## Package identity+- npm `@three-ws/agenc-mcp` · mcpName `io.github.nirholas/agenc-mcp` · dir `packages/agenc-mcp` · bin `agenc-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify reads return real tasks/agents via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/11-vision-mcp.md b/mcp-prompts/11-vision-mcp.mdnew file mode 100644index 000000000..e433e3b28--- /dev/null+++ b/mcp-prompts/11-vision-mcp.md@@ -0,0 +1,28 @@+# Build `@three-ws/vision-mcp` — image understanding over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server gives an AI agent image-understanding: analyze/describe an image via the platform's vision pipeline (free NVIDIA NIM VLM with a paid fallback).++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) and `packages/ibm-x402-mcp/` (reference for an AI-capability server with a free tier + paid fallback).+4. **The real backend:** `api/vision.js`. Read the handler. Confirm the request shape (image URL vs base64), which model serves free vs paid, response shape, and any size/format limits. Build against reality.++## What this server is+The "let an agent see" surface. `api/vision.js` runs a VLM (free NIM, paid fallback). This server exposes it so any MCP client can pass an image and get a structured description/analysis.++## Proposed tools (confirm/adjust against the real route)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `analyze_image` | read | POST `api/vision` | structured analysis for a prompt+image |+| `describe_image` | read | POST `api/vision` | natural-language description |+| `get_vision_status` | read | GET status | which backend/model is live, free-vs-paid |++## Inputs / auth+Tools take an image as **runtime input** (URL or base64) plus an optional instruction prompt. Validate input at the boundary (size/format/scheme). If the paid fallback requires payment/credentials, surface that in the description and wire it for real (mirror `ibm-x402-mcp`); the free path needs no key. Annotate as `readOnlyHint:true` (analysis doesn't mutate state), `openWorldHint:true`, `idempotentHint:false`.++## Package identity+- npm `@three-ws/vision-mcp` · mcpName `io.github.nirholas/vision-mcp` · dir `packages/vision-mcp` · bin `vision-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `analyze_image` returns a real VLM result for a test image via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/12-brain-mcp.md b/mcp-prompts/12-brain-mcp.mdnew file mode 100644index 000000000..8910bf7ac--- /dev/null+++ b/mcp-prompts/12-brain-mcp.md@@ -0,0 +1,29 @@+# Build `@three-ws/brain-mcp` — the multi-provider LLM router over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes the platform's multi-provider LLM router so an agent can list available providers/models and run a chat completion through whichever one fits.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) and `packages/ibm-watsonx-mcp/` + `packages/ibm-x402-mcp/` (references for LLM-bridge servers).+4. **The real backend:** `api/brain/` (esp. `chat`). Read the handler. Confirm the provider list (the router fronts Claude, GPT-4o, Qwen, Nemotron, etc.), the request shape (provider/model, messages), how streaming works, and how it authenticates. Build against reality.++> Per CLAUDE.md's LLM guidance: when describing the Anthropic option, use correct current model IDs (e.g. Opus 4.8 = `claude-opus-4-8`, Sonnet 4.6 = `claude-sonnet-4-6`, Haiku 4.5 = `claude-haiku-4-5-20251001`, Fable 5 = `claude-fable-5`). Don't invent model names — list whatever the route actually supports.++## What this server is+The "any model, one interface" surface. `api/brain/chat` routes to multiple providers. This server lets an MCP client discover providers and run completions without each client wiring every vendor SDK.++## Proposed tools (confirm/adjust against the real route)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `list_providers` | read | GET providers/models | available providers + model IDs |+| `chat` | read | POST `api/brain/chat` | a completion (collapse streaming into a final message for MCP) |++## Inputs / auth+`chat` takes messages + an optional provider/model selector as runtime input. The route is streaming; MCP tool results are a single payload, so accumulate the stream server-side and return the final text (note token usage if the route reports it). Wire real auth/keys exactly as the route expects (env vars in `server.json`). `readOnlyHint:true` (a completion doesn't mutate platform state), `openWorldHint:true`, `idempotentHint:false`.++## Package identity+- npm `@three-ws/brain-mcp` · mcpName `io.github.nirholas/brain-mcp` · dir `packages/brain-mcp` · bin `brain-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `list_providers` and a real `chat` round-trip via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/13-audio-mcp.md b/mcp-prompts/13-audio-mcp.mdnew file mode 100644index 000000000..8f448a1ca--- /dev/null+++ b/mcp-prompts/13-audio-mcp.md@@ -0,0 +1,29 @@+# Build `@three-ws/audio-mcp` — speech, lipsync, and motion capture over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes the platform's audio/animation pipeline: text-to-speech, speech-to-text, audio-to-face lipsync, and motion capture — the voice/animation layer for 3D agents.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) and `packages/avatar-agent-mcp/` (it has a `speak`/TTS tool — reuse the same pattern, don't contradict it).+4. **The real backend:** `api/tts/`, `api/asr.js`, `api/a2f.js` (audio-to-face), `api/mocap/` (motion capture). Read each handler. Confirm input/output shapes (audio in/out encoding, blendshape/animation output for a2f, mocap output format) and any size limits. Build against reality.++## What this server is+The "agents that talk and move" surface. TTS, ASR, audio-to-face lipsync (blendshapes), and mocap all exist as real endpoints. This server packages them so an MCP client can drive a 3D avatar's voice and animation.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `text_to_speech` | read | POST `api/tts` | synthesized audio (URL or encoded) |+| `speech_to_text` | read | POST `api/asr` | transcript |+| `audio_to_face` | read | POST `api/a2f` | lipsync blendshape/animation track |+| `motion_capture` | read | POST `api/mocap` | extracted motion/animation data |++## Inputs / auth+All inputs are **runtime** (text, audio, references). Be deliberate about payload size — prefer URLs/handles over inlining large base64 audio where the route allows. Wire any real keys via `server.json` env vars. These transform input → output without mutating platform state, so `readOnlyHint:true`, `openWorldHint:true`, `idempotentHint:false`.++## Package identity+- npm `@three-ws/audio-mcp` · mcpName `io.github.nirholas/audio-mcp` · dir `packages/audio-mcp` · bin `audio-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `text_to_speech` and `speech_to_text` round-trip via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/14-kol-mcp.md b/mcp-prompts/14-kol-mcp.mdnew file mode 100644index 000000000..06f5fa5a4--- /dev/null+++ b/mcp-prompts/14-kol-mcp.md@@ -0,0 +1,30 @@+# Build `@three-ws/kol-mcp` — per-wallet KOL portfolio + trade analytics over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server gives an AI agent deep per-wallet analytics on tracked KOL traders: portfolio P&L and trade history (Birdeye-backed).++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` — **important:** it already owns the KOL *leaderboard* and *recent-trades-on-a-mint* surface (`kol_leaderboard`, `kol_trades`). This server is the complementary **per-wallet deep dive** (one KOL's full portfolio + P&L). Do **not** duplicate the leaderboard; scope this to wallet-level analytics.+4. **The real backend:** `api/kol/` (esp. `wallets`). Read the handler. Confirm the portfolio/P&L shape and trade-history shape (Birdeye proxy). Build against reality.++## What this server is+The "track one smart trader" surface. `api/kol/wallets` proxies Birdeye portfolio P&L for tracked KOL wallets. This server lets an agent pull a specific KOL's holdings, realized/unrealized P&L, and trade history for copy/analysis decisions.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_wallet_portfolio` | read | GET `api/kol/wallets` | a KOL wallet's holdings + P&L |+| `get_wallet_trades` | read | GET trades | that wallet's trade history |++## Coin rule+Wallet/mint identifiers are **runtime input**. Never hardcode, market, or recommend any specific non-$THREE mint in code or copy. $THREE is the only coin the platform promotes.++## Auth / writes+Fully **read-only**. If `api/kol` requires a Birdeye/API key server-side, wire it via a `server.json` env var; otherwise no key. `readOnlyHint:true`, `openWorldHint:true`, `idempotentHint:false`.++## Package identity+- npm `@three-ws/kol-mcp` · mcpName `io.github.nirholas/kol-mcp` · dir `packages/kol-mcp` · bin `kol-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify both tools return real wallet analytics via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/15-clash-mcp.md b/mcp-prompts/15-clash-mcp.mdnew file mode 100644index 000000000..89127c995--- /dev/null+++ b/mcp-prompts/15-clash-mcp.md@@ -0,0 +1,32 @@+# Build `@three-ws/clash-mcp` — Coin Clash faction game over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes Coin Clash — the community faction-war game backed by real holdings + pump.fun data — so an agent can read game state, enlist, and rally a faction.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The real backend:** `api/clash/`. Read the handlers. Confirm the game-state shape, faction model, how enlist/rally work, the leaderboard, and how participation authenticates. Build against reality.++## What this server is+The game surface. Coin Clash runs faction warfare on real holdings + pump.fun data. This server lets an agent check the board and participate (enlist/rally) programmatically.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_clash_state` | read | GET state | current battle state + factions |+| `get_clash_leaderboard` | read | GET leaderboard | faction/player rankings |+| `enlist_faction` | write (idempotent) | POST enlist | enlistment result |+| `rally_faction` | write | POST rally | rally result |++## Coin rule+Coin Clash references coins as **runtime game data** rendered from real platform records — allowed per CLAUDE.md. Never hardcode, market, or recommend any specific non-$THREE mint in code or copy.++## Auth / writes+Reads are public. `enlist`/`rally` are account-scoped writes — read how `api/clash` authenticates and mirror `packages/avatar-agent-mcp`. Add credentials as `server.json` env vars, required only for writes.++## Package identity+- npm `@three-ws/clash-mcp` · mcpName `io.github.nirholas/clash-mcp` · dir `packages/clash-mcp` · bin `clash-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `get_clash_state` returns real game data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/16-tutor-mcp.md b/mcp-prompts/16-tutor-mcp.mdnew file mode 100644index 000000000..feedb7187--- /dev/null+++ b/mcp-prompts/16-tutor-mcp.md@@ -0,0 +1,27 @@+# Build `@three-ws/tutor-mcp` — learning-session ledger over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes the tutor session ledger so an agent can open, read, and close itemized learning sessions with real per-session billing.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/avatar-agent-mcp/` (auth/write reference).+4. **The real backend:** `api/tutor/` (esp. `session`). Read the handlers. Confirm the session shape, itemized line items, billing/settlement, and how load/close authenticate. Build against reality.++## What this server is+The tutoring-economics surface. `api/tutor/session` tracks itemized learning sessions and bills them. This server lets an agent manage a session lifecycle and read its ledger.++## Proposed tools (confirm/adjust against the real routes)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `load_session` | read | GET session | session + itemized ledger |+| `close_session` | write | POST close | finalized session + total |++## Auth / writes+Sessions are account-scoped. `close_session` finalizes billing — annotate `readOnlyHint:false` and describe any settlement clearly. Read how `api/tutor` authenticates and mirror `packages/avatar-agent-mcp`. Add credentials as `server.json` env vars. If settlement involves $THREE, that's fine — $THREE is the only coin; never reference another.++## Package identity+- npm `@three-ws/tutor-mcp` · mcpName `io.github.nirholas/tutor-mcp` · dir `packages/tutor-mcp` · bin `tutor-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `load_session` returns a real session ledger via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/17-loom-mcp.md b/mcp-prompts/17-loom-mcp.mdnew file mode 100644index 000000000..b1e150e00--- /dev/null+++ b/mcp-prompts/17-loom-mcp.md@@ -0,0 +1,28 @@+# Build `@three-ws/loom-mcp` — the 3D creation gallery over MCP++You are building a new MCP server for **three.ws** (read `CLAUDE.md` — its rules override defaults). This server exposes Loom, the community 3D-creation gallery, so an agent can browse the feed, fetch a creation, and submit its own.++## Read first (in order)+1. `CLAUDE.md`+2. `mcp-prompts/_SHARED-CONVENTIONS.md` — follow the package pattern precisely (copy `packages/intel-mcp`).+3. `packages/intel-mcp/` (read-only template) **and** `packages/scene-mcp/` + `packages/threews-avatar-mcp/` (references for 3D-content servers and viewer/embed shapes — reuse, don't contradict).+4. **The real backend:** `api/loom.js`. Read the handler. Confirm the gallery feed shape, a single creation's shape (GLB/scene reference, metadata), and how submission authenticates. Build against reality.++## What this server is+The community 3D-gallery surface. `api/loom.js` backs the forge creation gallery. This server lets agents discover what others have built and contribute — closing the loop with `scene-mcp` (compose) and `avatar-agent` (generate).++## Proposed tools (confirm/adjust against the real route)+| Tool | R/W | Wraps | Returns |+|------|-----|-------|---------|+| `get_loom_feed` | read | GET feed | paginated gallery creations |+| `get_creation` | read | GET one | a creation's metadata + GLB/scene + viewer URL |+| `submit_creation` | write | POST | submission result |++## Auth / writes+Feed/fetch are public/read-only. `submit_creation` is account-scoped — read how `api/loom` authenticates and mirror `packages/avatar-agent-mcp`. Validate submission input at the boundary (asset reference, metadata). Add credentials as `server.json` env vars, required only for submit. Where it helps, return a `viewer_url` like `threews-avatar-mcp` does so clients can preview inline.++## Package identity+- npm `@three-ws/loom-mcp` · mcpName `io.github.nirholas/loom-mcp` · dir `packages/loom-mcp` · bin `loom-mcp`++## Done means+`_SHARED-CONVENTIONS.md` → Definition of done. Verify `get_loom_feed` returns real gallery data via `npm run inspect`. Add a `data/changelog.json` entry (tags `sdk`,`feature`), run `npm run build:pages`. **Do not commit or push** unless asked.diff --git a/mcp-prompts/_SHARED-CONVENTIONS.md b/mcp-prompts/_SHARED-CONVENTIONS.mdnew file mode 100644index 000000000..bd7e83f77--- /dev/null+++ b/mcp-prompts/_SHARED-CONVENTIONS.md@@ -0,0 +1,100 @@+# three.ws MCP server — shared build conventions++> Every prompt in this folder references this file. Read it once at the start of each build. It is the single source of truth for how a three.ws MCP server is structured, so the new server is indistinguishable from the 14 already shipped.++## Ground rules (from CLAUDE.md — non-negotiable)++- **No mocks, no fake data, no placeholders.** Every tool wraps a **real** three.ws API endpoint over live HTTP. If the endpoint needs a key/signer, wire it for real.+- **No TODOs, no stubs, no `throw new Error("not implemented")`, no commented-out code.** Finish everything you write.+- **The only coin is `$THREE`** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Never name, hardcode, or reference any other coin anywhere — code, comments, tests, README, copy. Runtime-supplied mints (user passes a mint as input) are the only exception; never hardcode a non-`$THREE` mint.+- **Stage explicit paths only** when committing (never `git add -A`). Other agents share this worktree.+- This is a buildout task, not a commit task — **do not commit or push** unless the user explicitly says so.++## Canonical reference++Read these before writing a line:++1. `packages/intel-mcp/` — the gold-standard **read-only** template. Copy its shape exactly.+2. `packages/avatar-agent-mcp/` — the reference for **authenticated / write** tools (wallet, signer, on-chain actions). Study how it authenticates and how it marks write tools' annotations.+3. The **real API route(s)** your server wraps (named in your prompt). Read the handler, confirm the request/response shape, query params, auth, and error format. Build tools against what the code actually does — not what the prompt guesses.++## Package layout (match exactly)++```+packages/<name>-mcp/+ package.json # @three-ws/<name>-mcp, mcpName io.github.nirholas/<name>-mcp+ server.json # MCP Registry manifest (2025-12-11 schema)+ README.md # same structure/badges as intel-mcp's README+ LICENSE # copy Apache-2.0 LICENSE from intel-mcp verbatim+ src/+ index.js # entry point — buildServer() + stdio main(), copy intel-mcp's exactly+ config.js # THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT from env+ lib/api.js # apiRequest() — copy intel-mcp's verbatim (normalized errors, AbortController timeout)+ tools/<tool>.js # one file per tool, each `export const def = { name, title, annotations, description, inputSchema, handler }`+ test/+ registration.test.mjs # offline tool-surface invariants — copy intel-mcp's and update EXPECTED_NAMES+```++### package.json++Clone `packages/intel-mcp/package.json` and change: `name`, `mcpName`, `description`, `keywords`, `bin` key. Keep `type: module`, `engines.node >=20`, the `start`/`test`/`inspect` scripts, and deps `@modelcontextprotocol/sdk ^1.29.0` + `zod ^3.23.8` (add a signer dep like `@solana/web3.js` only if the server actually signs).++### server.json++Clone `packages/intel-mcp/server.json`. Update `name`, `title`, `description`, `packages[0].identifier`, `subfolder`. Keep the icon (`https://three.ws/three-ws-mcp-icon.svg`), `websiteUrl`, the `THREE_WS_BASE` + `THREE_WS_TIMEOUT_MS` env vars. **Add any new env var your server needs** (e.g. an API key or signer key) with `isRequired` set correctly and a clear `description`.++### src/index.js++Copy intel-mcp's `index.js` structure verbatim — the only changes are: the header comment, the tool imports, the `TOOLS` array, the server `name`/`title`, and the `instructions` string. Keep `buildServer()` exported (tests import it), keep the try/catch tool wrapper, keep the `isProcessEntryPoint()` stdio guard.++### lib/api.js & config.js++Copy both **verbatim** from intel-mcp. `apiRequest(path, { method, query, body })` already handles GET/POST, timeouts, and normalized errors (`.code` = `timeout`|`network_error`|`upstream_error`, `.status`, `.body`). Reuse it for every tool. If your server authenticates, add the auth header inside `apiRequest` (read from config) — do not invent a second HTTP client.++## Tool definition shape++Each `src/tools/<tool>.js`:++```js+import { z } from 'zod';+import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'snake_case_name',+ title: 'Human Title',+ annotations: { readOnlyHint: <bool>, idempotentHint: <bool>, openWorldHint: true },+ description: 'Precise, agent-facing. What it returns, what each field means, when to use it.',+ inputSchema: { /* zod fields with .describe() on every one */ },+ async handler(args) {+ const data = await apiRequest('/api/<real-path>', { query: { /* ... */ } });+ return { ok: true, /* shaped, documented fields */ };+ },+};+```++### Annotation rules++- **Read-only tool:** `readOnlyHint: true`, `openWorldHint: true`, `idempotentHint: false` (live data moves between calls). **Omit `destructiveHint`** when read-only.+- **Write tool:** `readOnlyHint: false`. Set `idempotentHint` honestly (e.g. "set config" is idempotent; "execute trade" / "append action" is not). Set `destructiveHint: true` only for irreversible/funds-moving actions. Spend-money or on-chain tools must say so loudly in the `description`.++## Tests++Copy `packages/intel-mcp/test/registration.test.mjs`. Update `EXPECTED_NAMES` and the count. These are **offline** invariants (no network): every tool has title/description/inputSchema/handler + complete annotations, and `buildServer()` registers them all. Add a small assertion that write tools set `readOnlyHint:false`. Run `node --test "packages/<name>-mcp/test/**/*.test.mjs"` — it must pass before you call the server done.++## README++Mirror intel-mcp's README: centered logo + badges (npm, license, node, MCP Registry, built-by), a one-line pitch, **Install** (`npm install` + `npx`), **Quick start** (`claude mcp add <name> -- npx -y @three-ws/<name>-mcp`), a **Tools** table (name → what it does), env-var table, and a note on auth/payment if any. No other coin, ever.++## Changelog (required — these are user-visible)++Append an entry to `data/changelog.json`: today's date, a holder-readable title + summary (plain language — "AI agents can now manage their copy-trade follows over MCP", not commit jargon), tags including `sdk` (+ `feature`). Then run `npm run build:pages` — it validates the entry and regenerates the changelog artifacts; the build fails on a malformed entry. Do **not** run `changelog:push` (that posts to Telegram; only after deploy).++## Definition of done++- [ ] `packages/<name>-mcp/` matches the layout above; no stubs, no TODOs, no other coin.+- [ ] Every tool wraps a **real** endpoint and returns real data (verify with `npm run inspect` against `THREE_WS_BASE=https://three.ws`, or a local dev server).+- [ ] Write/auth tools actually authenticate and are annotated honestly.+- [ ] `node --test "packages/<name>-mcp/test/**/*.test.mjs"` passes.+- [ ] README + server.json + package.json identity all agree on the name/version.+- [ ] `data/changelog.json` entry added and `npm run build:pages` passes.+- [ ] `git diff` reviewed; every changed line justified. Report what you built, what's wired, and how you verified — do not claim done for anything you couldn't verify.diff --git a/package.json b/package.jsonindex 73606e4b7..a7e9f5ce3 100644--- a/package.json+++ b/package.json@@ -59,6 +59,7 @@"packages/intel-mcp","packages/marketplace-mcp","packages/x402-mcp",+ "packages/provenance-mcp","walk-sdk","tour-sdk"],diff --git a/packages/autopilot-mcp/LICENSE b/packages/autopilot-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/autopilot-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/autopilot-mcp/README.md b/packages/autopilot-mcp/README.mdnew file mode 100644index 000000000..b2ed2e610--- /dev/null+++ b/packages/autopilot-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/autopilot-mcp</h1>++<p align="center"><strong>An AI agent's own autonomous-execution control plane — set autopilot scopes, daily $THREE spend caps, and auto-execute, then run the propose → execute → undo loop, all from any MCP client.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/autopilot-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/autopilot-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/autopilot-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/autopilot-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 an AI agent **its own execution control plane** over stdio. The agent configures the boundaries it is allowed to act within — capability scopes, a daily $THREE spend ceiling, auto-execute and confirmation policy — then drives the full **propose → review → execute → undo** loop. No human in the loop, but every boundary is **enforced server-side**: an out-of-scope or over-budget action is denied, never executed.++This is the keystone of the autonomous-agent story. Autopilot config and execution used to live only behind the three.ws UI/API; this server exposes them so an agent can manage its own guardrails and act within them.++> ⚠️ **This server is authenticated and write-heavy.** `execute_proposal` can move **real $THREE** on Solana mainnet and is **irreversible**. Scopes, the daily spend cap, and confirmation are all enforced on the three.ws backend — this server cannot bypass them.++## Install++```bash+npm install @three-ws/autopilot-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/autopilot-mcp+```++## Quick start++**Claude Code**, one line (supply your three.ws credential):++```bash+THREE_WS_API_KEY=sk_live_… claude mcp add autopilot -- npx -y @three-ws/autopilot-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "autopilot": {+ "command": "npx",+ "args": ["-y", "@three-ws/autopilot-mcp"],+ "env": {+ "THREE_WS_API_KEY": "sk_live_…"+ }+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+THREE_WS_API_KEY=sk_live_… npx -y @modelcontextprotocol/inspector npx @three-ws/autopilot-mcp+```++## Authentication++Every autopilot endpoint is **owner-only**, so this server is authenticated. Set **`THREE_WS_API_KEY`** to the agent owner's three.ws credential — either a three.ws **API key** (`sk_live_…` / `sk_test_…`) or an **OAuth access token**. It is sent as `Authorization: Bearer …` on every request and identifies the owning user; the agent can only manage agents that user owns. The credential can authorize **real $THREE transfers** via `execute_proposal` — store it like a password. `THREE_WS_TOKEN` and `THREE_WS_BEARER` are accepted as aliases.++## Tools++| Tool | Type | What it does |+| ------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------ |+| `get_autopilot_config` | read-only | Read the agent's guardrails: enabled, scopes, auto-execute, daily $THREE cap, confirmation policy — plus trust. |+| `set_autopilot_config` | write · idempotent | Update those guardrails with a partial patch (grant scopes, set the daily $THREE ceiling, arm/disarm). No action taken. |+| `generate_proposals` | write | Run the agent's mind: turn high-salience memories + reflections into real, provenance-cited candidate actions. |+| `list_proposals` | read-only | The proposal queue — ids, kinds, rationales, params, status, cited sources. Filter by status. |+| `dryrun_proposal` | read-only | Preview what executing a proposal *would* do (scope / cap / balance checks), without taking any action. |+| `adjust_proposal` | write · idempotent | Edit a pending proposal's params before executing (tune a threshold, amount, cadence). Validated server-side. |+| `execute_proposal` | **write · destructive** | Take the real action. ⚠️ A `wallet_transfer` moves real $THREE on mainnet, irreversible — needs `confirm:true`. |+| `dismiss_proposal` | write | Drop a pending proposal; records a feedback memory so the agent stops proposing it. |+| `undo_action` | write | Reverse a reversible execution (delete the alert rule / briefing); records a feedback memory. $THREE transfers can't be undone. |+| `list_autopilot_activity` | read-only | The append-only signed receipts log — every autonomous action, its outcome, provenance, and signature. |+| `compute_trust` | read-only | The agent's earned trust level (sandbox → trusted → autonomous), computed from real action history. |++The five read tools reflect live state (proposals, receipts, trust move between calls), so none are idempotent. `set_autopilot_config` and `adjust_proposal` are idempotent writes (re-applying the same values is a no-op). `generate_proposals`, `execute_proposal`, `dismiss_proposal`, and `undo_action` each take a real action.++### Input parameters++Every tool takes **`agentId`** (the UUID of an agent you own) except `list_autopilot_activity`, where it is optional (omit to aggregate across all your agents).++- **`get_autopilot_config`** / **`compute_trust`** / **`generate_proposals`** — `agentId`.+- **`set_autopilot_config`** — `agentId`, plus any of: `enabled` (bool), `scopes` (`{ create_alert?, briefing?, wallet_transfer? }`), `autoExecute` (`{ create_alert?, briefing? }`), `dailySpendThree` (number, whole $THREE; 0 disables spending), `requireConfirm` (bool).+- **`list_proposals`** — `agentId`, `status` (`pending` | `executed` | `dismissed` | `undone` | `failed`), `limit` (1–200).+- **`dryrun_proposal`** / **`dismiss_proposal`** / **`undo_action`** — `agentId`, `proposalId`.+- **`adjust_proposal`** — `agentId`, `proposalId`, `params` (full replacement params for the proposal's kind).+- **`execute_proposal`** — `agentId`, `proposalId`, `confirm` (bool — required for an irreversible $THREE transfer).+- **`list_autopilot_activity`** — `agentId` (optional), `limit` (1–200), `cursor` (from a prior `next_cursor`).++## The loop++```jsonc+// 1. Grant the agent a reversible capability+// set_autopilot_config+> { "agentId": "…", "enabled": true, "scopes": { "create_alert": true } }+{ "ok": true, "config": { "enabled": true, "scopes": { "create_alert": true, "briefing": false, "wallet_transfer": false }, "daily_spend_three": 0, "require_confirm": true } }++// 2. Let the agent propose actions from its memory+// generate_proposals+> { "agentId": "…" }+{ "ok": true, "createdCount": 1, "source": "memory",+ "created": [ { "id": "p_…", "kind": "create_alert", "title": "Alert when $THREE crosses $0.01",+ "rationale": "You noted interest in $THREE around $0.01 — I'll watch it.", "status": "pending" } ] }++// 3. Preview before acting+// dryrun_proposal+> { "agentId": "…", "proposalId": "p_…" }+{ "ok": true, "preview": { "kind": "create_alert", "willDo": "Create a real alert rule… Reversible.",+ "checks": [ { "label": "Scope \"create_alert\" granted", "ok": true } ], "blocked": false } }++// 4. Execute for real (reversible kind — no confirm needed)+// execute_proposal+> { "agentId": "…", "proposalId": "p_…" }+{ "ok": true, "receipt": "Created a price above alert.", "actionId": "1843", "proposal": { "status": "executed" } }++// 5. Changed your mind? Undo it.+// undo_action+> { "agentId": "…", "proposalId": "p_…" }+{ "ok": true, "proposal": { "status": "undone" } }+```++Spending real $THREE requires the owner to have granted `scopes.wallet_transfer`, set a positive `dailySpendThree`, and (unless pre-authorized) `execute_proposal` must be re-issued with `confirm:true`. All three are checked server-side.++## Requirements++- **Node.js >= 20.**+- A three.ws credential (`THREE_WS_API_KEY`) for the agent owner.+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default | Notes |+| --------------------- | -------- | ------------------ | ---------------------------------------------------------------- |+| `THREE_WS_API_KEY` | **yes** | — | three.ws API key (`sk_live_…`) or OAuth access token. Secret. Can move real $THREE. |+| `THREE_WS_BASE` | no | `https://three.ws` | Override only when self-hosting or targeting a preview. |+| `THREE_WS_TIMEOUT_MS` | no | `60000` | Per-request timeout (generation runs a server-side LLM pass). |++## 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/autopilot-mcp/package.json b/packages/autopilot-mcp/package.jsonnew file mode 100644index 000000000..110e3e017--- /dev/null+++ b/packages/autopilot-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/autopilot-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/autopilot-mcp",+ "description": "An AI agent's own autonomous-execution control plane over MCP — set autopilot scopes, daily $THREE spend caps, and auto-execute, then run the propose → execute → undo loop. Authenticated, write-heavy; scope + spend enforcement is server-side.",+ "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/autopilot-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "autopilot",+ "autonomous-agents",+ "agent-guardrails",+ "spend-limits",+ "ai-agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "autopilot-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/autopilot-mcp/server.json b/packages/autopilot-mcp/server.jsonnew file mode 100644index 000000000..d7ee579c0--- /dev/null+++ b/packages/autopilot-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/autopilot-mcp",+ "title": "three.ws Autopilot",+ "description": "An agent's own execution control plane: set autopilot scopes + daily $THREE spend caps, then propose, execute, and undo actions.",+ "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/autopilot-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/autopilot-mcp",+ "version": "0.1.0",+ "runtimeHint": "npx",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "THREE_WS_API_KEY",+ "description": "REQUIRED. The agent owner's three.ws credential — a three.ws API key (sk_live_… / sk_test_…) or an OAuth access token. Sent as Authorization: Bearer on every request; every autopilot endpoint is owner-scoped and rejects unauthenticated calls. This credential can move real $THREE via execute_proposal — treat it like a password. THREE_WS_TOKEN / THREE_WS_BEARER are accepted aliases.",+ "format": "string",+ "isRequired": true,+ "isSecret": true+ },+ {+ "name": "THREE_WS_BASE",+ "description": "Base URL of the three.ws API that serves the autopilot 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. Proposal generation runs a real server-side LLM pass, so the default is generous.",+ "format": "number",+ "isRequired": false,+ "default": "60000"+ }+ ]+ }+ ]+}diff --git a/packages/autopilot-mcp/src/config.js b/packages/autopilot-mcp/src/config.jsnew file mode 100644index 000000000..a8f4e91ad--- /dev/null+++ b/packages/autopilot-mcp/src/config.js@@ -0,0 +1,42 @@+// Centralized env + HTTP base for the autopilot MCP.+//+// This server is the agent's OWN execution control plane: it reads and writes+// the real three.ws autopilot surface (scopes, daily $THREE spend caps, the+// propose → execute → undo loop) over live HTTP. Every autopilot route is+// owner-only, so this 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; all scope and spend enforcement happens 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'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 autopilot endpoint is owner-scoped and+// returns 401 without it. Treat it like a password; it can move real $THREE.+export const THREE_WS_API_KEY =+ env('THREE_WS_API_KEY') || env('THREE_WS_TOKEN') || env('THREE_WS_BEARER') || '';++// Per-request timeout (ms). Proposal generation runs a real LLM synthesis pass+// server-side (maxDuration 60s upstream), so the default is generous enough to+// ride out a cold edge + model call without tripping a false timeout.+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 60000;+ 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/autopilot-mcp';diff --git a/packages/autopilot-mcp/src/index.js b/packages/autopilot-mcp/src/index.jsnew file mode 100644index 000000000..a5624b9bd--- /dev/null+++ b/packages/autopilot-mcp/src/index.js@@ -0,0 +1,157 @@+#!/usr/bin/env node+// @three-ws/autopilot-mcp — MCP server entry point.+//+// An AI agent's own autonomous-execution control plane over the Model Context+// Protocol. It lets the agent manage its OWN guardrails and act within them —+// no human in the loop, but every boundary enforced server-side:+// • get_autopilot_config / set_autopilot_config — scopes, daily $THREE spend+// cap, auto-execute flags, confirmation policy+// • generate_proposals — turn high-salience memories into real candidate actions+// • list_proposals / dryrun_proposal / adjust_proposal — review the queue+// • execute_proposal — take the real action (⚠️ can move real $THREE; irreversible)+// • undo_action / dismiss_proposal — close the trust loop+// • list_autopilot_activity — the signed receipts log+// • compute_trust — the agent's earned reputation+//+// AUTHENTICATED + WRITE-HEAVY. Every route is owner-only; the agent's three.ws+// API key (or OAuth access token) is supplied via THREE_WS_API_KEY and carried as+// a Bearer credential. Scope/spend/confirmation enforcement lives server-side —+// this server never bypasses it. $THREE is the only coin referenced.+//+// Run standalone:+// THREE_WS_API_KEY=sk_live_… node packages/autopilot-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 getConfig } from './tools/get-config.js';+import { def as setConfig } from './tools/set-config.js';+import { def as generateProposals } from './tools/generate-proposals.js';+import { def as listProposals } from './tools/list-proposals.js';+import { def as dryrunProposal } from './tools/dryrun-proposal.js';+import { def as adjustProposal } from './tools/adjust-proposal.js';+import { def as executeProposal } from './tools/execute-proposal.js';+import { def as dismissProposal } from './tools/dismiss-proposal.js';+import { def as undoAction } from './tools/undo-action.js';+import { def as listActivity } from './tools/list-activity.js';+import { def as computeTrust } from './tools/compute-trust.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 = [+ // Config / guardrails+ getConfig,+ setConfig,+ // Propose → review+ generateProposals,+ listProposals,+ dryrunProposal,+ adjustProposal,+ // Act → close the loop+ executeProposal,+ dismissProposal,+ undoAction,+ // Audit / reputation+ listActivity,+ computeTrust,+];++/**+ * Construct a fully-registered McpServer without connecting a transport.+ * Registration is env-free (no key needed to advertise the tool surface), so this+ * is safe to import from tests. A credential is required only when a tool runs.+ * @returns {McpServer}+ */+export function buildServer() {+ const server = new McpServer(+ { name: 'autopilot-mcp', title: 'three.ws Autopilot', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ "three.ws Autopilot MCP — an agent's own execution control plane. The agent manages its OWN " ++ 'autonomy boundaries and acts within them, bounded by real, server-enforced scopes and spend ' ++ 'caps. Flow: get_autopilot_config to read scopes + daily $THREE cap + trust; set_autopilot_config ' ++ 'to grant capabilities (create_alert, briefing, wallet_transfer), set auto-execute, and the daily ' ++ 'spend ceiling; generate_proposals to turn high-salience memories into real, provenance-cited ' ++ 'candidate actions; list_proposals to read the queue; dryrun_proposal to preview a proposal ' ++ '(scope/cap/balance checks) without acting; adjust_proposal to tune a pending one; execute_proposal ' ++ 'to take the real action — ⚠️ a wallet_transfer moves REAL $THREE on Solana mainnet, is ' ++ 'IRREVERSIBLE, requires confirm:true, and is capped by the daily budget; undo_action reverses a ' ++ 'reversible execution; dismiss_proposal drops one (both record feedback memories so the agent ' ++ 'learns the boundary); list_autopilot_activity is the append-only signed receipts log; ' ++ 'compute_trust is the agent\'s earned reputation. Every scope, confirmation, and spend cap is ' ++ 'enforced server-side — these tools cannot bypass it. Requires THREE_WS_API_KEY (a three.ws API ' ++ 'key or OAuth access token for the agent owner). $THREE is the only coin.',+ },+ );++ 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(`[autopilot-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('[autopilot-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/autopilot-mcp/src/lib/api.js b/packages/autopilot-mcp/src/lib/api.jsnew file mode 100644index 000000000..db5876c11--- /dev/null+++ b/packages/autopilot-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/autopilot-mcp/src/tools/adjust-proposal.js b/packages/autopilot-mcp/src/tools/adjust-proposal.jsnew file mode 100644index 000000000..f39220661--- /dev/null+++ b/packages/autopilot-mcp/src/tools/adjust-proposal.js@@ -0,0 +1,50 @@+// `adjust_proposal` — edit a pending proposal's params before executing. Write, idempotent.+//+// Wraps POST /api/autopilot/proposals { action:'adjust', agentId, proposalId, params }+// → { proposal }. The new params are validated server-side against the proposal's+// kind; an invalid edit is rejected with the reason. Only a pending proposal can be+// adjusted. Re-applying the same params yields the same proposal — idempotent.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'adjust_proposal',+ title: 'Adjust a pending autopilot proposal',+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },+ description:+ "Edit a pending proposal's params before executing it — tune a threshold, swap a briefing cadence, " ++ 'correct a transfer amount/recipient. The new params are validated SERVER-SIDE against the proposal ' ++ 'kind and shape: ' ++ 'create_alert → { asset:"three"|<mint>, condition:"price_above"|"price_below"|"graduation"|"whale_buy", ' ++ 'threshold_usd?|threshold_sol? }; ' ++ 'briefing → { summary, cadence:"once"|"daily"|"weekly", topic }; ' ++ 'wallet_transfer → { recipient:<solana addr>, amount_three:number, reason? }. ' ++ 'An invalid edit is rejected with the reason and nothing changes. Only a pending proposal can be ' ++ 'adjusted. WRITE but idempotent (no action taken; re-applying the same params is a no-op). The only ' ++ 'coin is $THREE — use asset:"three" for a $THREE alert. Returns the updated proposal.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the agent that owns the proposal. Must be an agent owned by the credential.'),+ proposalId: z+ .string()+ .min(1)+ .describe('UUID of the pending proposal to adjust.'),+ params: z+ .record(z.any())+ .describe('The full replacement params object for the proposal, matching its kind (see description). Validated server-side.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const proposalId = String(args?.proposalId ?? '').trim();+ const params = args?.params && typeof args.params === 'object' ? args.params : {};+ const data = await apiRequest('/api/autopilot/proposals', {+ method: 'POST',+ body: { action: 'adjust', agentId, proposalId, params },+ });+ return { ok: true, agentId, proposalId, proposal: data?.proposal ?? null };+ },+};diff --git a/packages/autopilot-mcp/src/tools/compute-trust.js b/packages/autopilot-mcp/src/tools/compute-trust.jsnew file mode 100644index 000000000..bae558a12--- /dev/null+++ b/packages/autopilot-mcp/src/tools/compute-trust.js@@ -0,0 +1,36 @@+// `compute_trust` — the agent's computed trust/reputation level. Read-only.+//+// Wraps GET /api/autopilot/config?agentId=<id> and returns just the trust block.+// Trust is derived server-side from REAL action history (executions kept vs.+// undone/dismissed), not a vanity number.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'compute_trust',+ title: 'Compute autopilot trust level',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "The agent's earned trust level, computed from its REAL autopilot history. Returns level " ++ '(sandbox → trusted → autonomous), a 0+ score (net kept executions weighted by reliability), the ' ++ 'underlying stats (executed / undone / dismissed / pending counts + reliability %), and what it ' ++ 'takes to reach the next level. Trust rises as the owner keeps the agent\'s actions and falls when ' ++ 'they undo or dismiss them — it is not configurable, only earned. Read-only.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the three.ws agent whose trust to compute. Must be an agent owned by the credential.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const data = await apiRequest('/api/autopilot/config', { query: { agentId } });+ return {+ ok: true,+ agentId,+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/dismiss-proposal.js b/packages/autopilot-mcp/src/tools/dismiss-proposal.jsnew file mode 100644index 000000000..dc59d3337--- /dev/null+++ b/packages/autopilot-mcp/src/tools/dismiss-proposal.js@@ -0,0 +1,45 @@+// `dismiss_proposal` — drop a pending proposal the agent shouldn't act on. Write.+//+// Wraps POST /api/autopilot/proposals { action:'dismiss', agentId, proposalId } → { proposal, trust }.+// Records a feedback memory ("don't propose this again") so future generation+// steers away from it. Only a pending proposal can be dismissed.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'dismiss_proposal',+ title: 'Dismiss a pending autopilot proposal',+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'Dismiss a pending proposal the agent decided not to act on. Marks it dismissed and records a ' ++ 'feedback memory ("don\'t propose this again") so future generate_proposals steers away from it — ' ++ 'this is how the agent learns the owner\'s boundaries. WRITE. Only a pending proposal can be ' ++ 'dismissed (executed/undone/dismissed ones are rejected). Returns the updated proposal and trust.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the agent that owns the proposal. Must be an agent owned by the credential.'),+ proposalId: z+ .string()+ .min(1)+ .describe('UUID of the pending proposal to dismiss.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const proposalId = String(args?.proposalId ?? '').trim();+ const data = await apiRequest('/api/autopilot/proposals', {+ method: 'POST',+ body: { action: 'dismiss', agentId, proposalId },+ });+ return {+ ok: true,+ agentId,+ proposalId,+ proposal: data?.proposal ?? null,+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/dryrun-proposal.js b/packages/autopilot-mcp/src/tools/dryrun-proposal.jsnew file mode 100644index 000000000..8f228b2f5--- /dev/null+++ b/packages/autopilot-mcp/src/tools/dryrun-proposal.js@@ -0,0 +1,40 @@+// `dryrun_proposal` — non-mutating preview of what executing a proposal would do. Read-only.+//+// Wraps POST /api/autopilot/proposals { action:'dryrun', agentId, proposalId } → { preview }.+// It is a POST, but takes NO action: it only resolves params, checks scope/cap/+// balance, and reports what WOULD happen — so it is annotated read-only.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'dryrun_proposal',+ title: 'Dry-run an autopilot proposal',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Preview exactly what executing a proposal WOULD do, without taking any action. Returns the kind, a ' ++ 'plain-language "willDo" sentence, and a checklist of guard checks (scope granted? params valid? ' ++ 'within the daily $THREE cap? wallet balance covers a transfer?) plus a `blocked` flag if any check ' ++ 'fails. Always dry-run an irreversible wallet_transfer before executing it. Performs a live balance ' ++ 'read but no write and no spend — safe to call freely. Read-only.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the agent that owns the proposal. Must be an agent owned by the credential.'),+ proposalId: z+ .string()+ .min(1)+ .describe('UUID of the proposal to preview (from list_proposals or generate_proposals).'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const proposalId = String(args?.proposalId ?? '').trim();+ const data = await apiRequest('/api/autopilot/proposals', {+ method: 'POST',+ body: { action: 'dryrun', agentId, proposalId },+ });+ return { ok: true, agentId, proposalId, preview: data?.preview ?? null };+ },+};diff --git a/packages/autopilot-mcp/src/tools/execute-proposal.js b/packages/autopilot-mcp/src/tools/execute-proposal.jsnew file mode 100644index 000000000..27f0334b7--- /dev/null+++ b/packages/autopilot-mcp/src/tools/execute-proposal.js@@ -0,0 +1,61 @@+// `execute_proposal` — take the real action a proposal describes. WRITE · DESTRUCTIVE.+//+// Wraps POST /api/autopilot/proposals { action:'execute', agentId, proposalId, confirm? }+// → { proposal, receipt, action, trust }.+//+// This is the funds-touching endpoint. A `wallet_transfer` proposal moves REAL+// $THREE on Solana mainnet and is IRREVERSIBLE — it requires confirm:true (unless+// the owner durably pre-authorized it) and is capped by the daily $THREE budget.+// `create_alert` and `briefing` are real writes too, but reversible via undo_action.+// Scope, confirmation, and spend caps are all enforced SERVER-SIDE — this tool+// cannot bypass them; an out-of-scope or over-budget call is denied, not executed.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'execute_proposal',+ title: 'Execute an autopilot proposal (moves real value)',+ // EXECUTION: a wallet_transfer proposal moves real $THREE on mainnet, irreversible.+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'EXECUTE a proposal for real, within the owner-granted scope. ⚠️ This is the funds-touching action: a ' ++ '`wallet_transfer` proposal sends REAL $THREE on Solana mainnet and is IRREVERSIBLE — you MUST pass ' ++ 'confirm:true for it (unless the owner durably pre-authorized that scope), and it is capped by the ' ++ 'daily $THREE budget. `create_alert` and `briefing` are real writes but reversible via undo_action. ' ++ 'Always dryrun_proposal first. Scope, confirmation, and spend caps are enforced SERVER-SIDE; this tool ' ++ 'cannot override them — an out-of-scope, over-budget, or unconfirmed call is denied (no action taken). ' ++ 'Returns the updated proposal, a human receipt, the signed action-log id, and updated trust.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the agent that owns the proposal. Must be an agent owned by the credential.'),+ proposalId: z+ .string()+ .min(1)+ .describe('UUID of the pending proposal to execute (from list_proposals or generate_proposals).'),+ confirm: z+ .boolean()+ .optional()+ .describe('Must be true to execute an irreversible $THREE wallet_transfer (when require_confirm is on). Ignored for reversible kinds.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const proposalId = String(args?.proposalId ?? '').trim();+ const body = { action: 'execute', agentId, proposalId };+ if (args?.confirm === true) body.confirm = true;+ const data = await apiRequest('/api/autopilot/proposals', { method: 'POST', body });+ return {+ ok: true,+ agentId,+ proposalId,+ proposal: data?.proposal ?? null,+ receipt: data?.receipt ?? null,+ action: data?.action ?? null,+ actionId: data?.action?.id != null ? String(data.action.id) : null,+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/generate-proposals.js b/packages/autopilot-mcp/src/tools/generate-proposals.jsnew file mode 100644index 000000000..ab7c2b36d--- /dev/null+++ b/packages/autopilot-mcp/src/tools/generate-proposals.js@@ -0,0 +1,52 @@+// `generate_proposals` — run the agent's "mind" to produce real candidate actions. Write.+//+// Wraps POST /api/autopilot/proposals { action:'generate', agentId } →+// { created, autoRan, source, scanned, trust }.+// Generation reads the agent's high-salience memories + pending reflections and+// synthesizes concrete, provenance-cited proposals, persisting them to the queue.+// Reversible proposals the owner scoped for auto-execution may run immediately+// (server-side); irreversible $THREE transfers never auto-run — they stay pending.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'generate_proposals',+ title: 'Generate autopilot proposals',+ // Write: persists new proposals (and may auto-run owner-scoped reversible ones),+ // but it is not itself a funds-moving/irreversible action.+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ "Run the agent's mind: read its high-salience memories and pending reflections and synthesize real, " ++ 'concrete autopilot proposals — each citing the exact memories that justify it. New proposals are ' ++ 'persisted to the queue (see list_proposals). WRITE: any reversible proposal the owner has scoped for ' ++ 'auto-execution may run immediately and is reported under `autoRan`; irreversible $THREE transfers ' ++ 'never auto-run — they stay pending for explicit execute_proposal. Returns the created proposals, the ' ++ 'autoRan receipts, the generation `source` (reflection | memory | heuristic), what was `scanned`, and ' ++ 'updated trust. Deduped server-side, so calling it repeatedly will not enqueue duplicates.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the three.ws agent to generate proposals for. Must be an agent owned by the credential.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const data = await apiRequest('/api/autopilot/proposals', {+ method: 'POST',+ body: { action: 'generate', agentId },+ });+ const created = Array.isArray(data?.created) ? data.created : [];+ return {+ ok: true,+ agentId,+ created,+ createdCount: created.length,+ autoRan: Array.isArray(data?.autoRan) ? data.autoRan : [],+ source: data?.source ?? null,+ scanned: data?.scanned ?? null,+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/get-config.js b/packages/autopilot-mcp/src/tools/get-config.jsnew file mode 100644index 000000000..3a6ad5823--- /dev/null+++ b/packages/autopilot-mcp/src/tools/get-config.js@@ -0,0 +1,36 @@+// `get_autopilot_config` — read the agent's current autopilot guardrails. Read-only.+//+// Wraps GET /api/autopilot/config?agentId=<id> → { config, trust }.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_autopilot_config',+ title: 'Get autopilot config',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Read the agent's autopilot permission model: whether autopilot is enabled, which capability " ++ 'scopes the owner granted (create_alert, briefing, wallet_transfer), which reversible scopes may ' ++ 'auto-execute, the daily $THREE spend ceiling (whole tokens; 0 = no spending), and whether ' ++ 'irreversible actions require explicit confirmation. Also returns the live trust level (sandbox → ' ++ 'trusted → autonomous) computed from real action history. Nothing the agent can do exists outside ' ++ 'these owner-granted scopes — read this before proposing or executing. Read-only.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the three.ws agent whose autopilot config to read. Must be an agent owned by the credential.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const data = await apiRequest('/api/autopilot/config', { query: { agentId } });+ return {+ ok: true,+ agentId,+ config: data?.config ?? null,+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/list-activity.js b/packages/autopilot-mcp/src/tools/list-activity.jsnew file mode 100644index 000000000..312f320a1--- /dev/null+++ b/packages/autopilot-mcp/src/tools/list-activity.js@@ -0,0 +1,55 @@+// `list_autopilot_activity` — the signed receipts feed of past autonomous actions. Read-only.+//+// Wraps GET /api/autopilot/activity?agentId=&limit=&cursor= → { receipts, next_cursor, agents, trust }.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'list_autopilot_activity',+ title: 'List autopilot activity (signed receipts)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read the append-only log of every autonomous action the agent has taken, newest first — the real ' ++ 'agent_actions trail. Each receipt carries the kind (alert created / briefing authored / wallet ' ++ 'transfer), its rationale, the outcome (created rule id / notification id / on-chain signature), the ' ++ 'source memories it was grounded in, and the cryptographic signature + signer address when the ' ++ 'action was signed by the agent\'s wallet. Use it to audit what the agent did and why. Omit agentId ' ++ 'to aggregate across every agent the credential owns. Paginate with the returned next_cursor. Read-only.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .optional()+ .describe('UUID of a specific agent (must be owned by the credential). Omit to aggregate across all your agents.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Max receipts per page (1–200, default 50).'),+ cursor: z+ .string()+ .regex(/^\d+$/)+ .optional()+ .describe('Pagination cursor: pass the next_cursor from a previous call to fetch the next page.'),+ },+ async handler(args) {+ const query = {};+ if (args?.agentId) query.agentId = String(args.agentId).trim();+ if (args?.limit != null) query.limit = args.limit;+ if (args?.cursor) query.cursor = String(args.cursor);+ const data = await apiRequest('/api/autopilot/activity', { query });+ const receipts = Array.isArray(data?.receipts) ? data.receipts : [];+ return {+ ok: true,+ count: receipts.length,+ receipts,+ next_cursor: data?.next_cursor ?? null,+ agents: Array.isArray(data?.agents) ? data.agents : [],+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/list-proposals.js b/packages/autopilot-mcp/src/tools/list-proposals.jsnew file mode 100644index 000000000..eed270a49--- /dev/null+++ b/packages/autopilot-mcp/src/tools/list-proposals.js@@ -0,0 +1,53 @@+// `list_proposals` — the agent's autopilot proposal queue. Read-only.+//+// Wraps GET /api/autopilot/proposals?agentId=&status=&limit= → { proposals, trust, config }.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'list_proposals',+ title: 'List autopilot proposals',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List the agent\'s autopilot proposals — candidate actions it generated, each grounded in cited ' ++ 'memories (provenance hydrated). Each proposal carries its id (needed for dryrun/execute/dismiss/' ++ 'undo/adjust), kind (create_alert | briefing | wallet_transfer), title, plain-language rationale ' ++ '(the receipt), params, confidence, requiresConfirmation, status, result, and the source memories. ' ++ 'Filter by status to find what is actionable. Also returns the current config + trust for context. ' ++ 'Read-only.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the three.ws agent whose proposals to list. Must be an agent owned by the credential.'),+ status: z+ .enum(['pending', 'executed', 'dismissed', 'undone', 'failed'])+ .optional()+ .describe('Filter to one lifecycle status. Omit to return all statuses (newest first).'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Max proposals to return (1–200, default 50).'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const query = { agentId };+ if (args?.status) query.status = args.status;+ if (args?.limit != null) query.limit = args.limit;+ const data = await apiRequest('/api/autopilot/proposals', { query });+ const proposals = Array.isArray(data?.proposals) ? data.proposals : [];+ return {+ ok: true,+ agentId,+ count: proposals.length,+ proposals,+ trust: data?.trust ?? null,+ config: data?.config ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/src/tools/set-config.js b/packages/autopilot-mcp/src/tools/set-config.jsnew file mode 100644index 000000000..4cd1a2c20--- /dev/null+++ b/packages/autopilot-mcp/src/tools/set-config.js@@ -0,0 +1,73 @@+// `set_autopilot_config` — update the agent's autopilot guardrails. Write, idempotent.+//+// Wraps POST /api/autopilot/config { agentId, ...patch } → { config }. The patch+// is merged server-side onto agent_identities.meta.autopilot; only the fields you+// pass change. Setting the same values twice yields the same config — idempotent.+// This does NOT take any action; it only adjusts the boundaries within which the+// agent may later act (scopes + spend caps are enforced server-side at execution).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++const scopeFlags = z+ .object({+ create_alert: z.boolean().optional().describe('Allow creating real price/event alert rules.'),+ briefing: z.boolean().optional().describe('Allow authoring memory-grounded briefing notifications.'),+ wallet_transfer: z.boolean().optional().describe('Allow sending real $THREE from the agent wallet (irreversible).'),+ })+ .partial();++export const def = {+ name: 'set_autopilot_config',+ title: 'Set autopilot config',+ // Write, but no action is taken and re-applying the same patch is a no-op.+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ "Update the agent's autopilot guardrails. A partial patch — only the fields you pass change; the " ++ 'rest are preserved. Set `enabled` to arm/disarm autopilot, `scopes` to grant/revoke each capability ' ++ '(create_alert, briefing, wallet_transfer), `autoExecute` to let reversible scopes run without review, ' ++ '`dailySpendThree` for the daily $THREE outflow ceiling (whole tokens; 0 disables spending), and ' ++ '`requireConfirm` to force explicit confirmation on irreversible actions. WRITE but idempotent: it ' ++ 'changes only the boundaries, takes no action, and re-applying the same values is a no-op. Returns the ' ++ 'full updated config. Scopes are enforced server-side at execution time — granting one here is what ' ++ 'makes a later execute_proposal possible.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the three.ws agent to configure. Must be an agent owned by the credential.'),+ enabled: z.boolean().optional().describe('Master switch — autopilot can only act when this is true.'),+ scopes: scopeFlags.optional().describe('Per-capability grants. Omitted keys keep their current value.'),+ autoExecute: z+ .object({+ create_alert: z.boolean().optional(),+ briefing: z.boolean().optional(),+ })+ .partial()+ .optional()+ .describe('Reversible scopes allowed to auto-execute on generation (wallet_transfer can never auto-run).'),+ dailySpendThree: z+ .number()+ .min(0)+ .optional()+ .describe('Daily ceiling on autonomous $THREE outflow, in whole tokens. 0 means no spending allowed.'),+ requireConfirm: z+ .boolean()+ .optional()+ .describe('When true (default), irreversible actions need explicit confirm:true at execution.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ // Map the agent-facing camelCase args to the API's snake_case patch body.+ const body = { agentId };+ if (args?.enabled !== undefined) body.enabled = args.enabled === true;+ if (args?.scopes && typeof args.scopes === 'object') body.scopes = args.scopes;+ if (args?.autoExecute && typeof args.autoExecute === 'object') body.auto_execute = args.autoExecute;+ if (args?.dailySpendThree !== undefined) body.daily_spend_three = args.dailySpendThree;+ if (args?.requireConfirm !== undefined) body.require_confirm = args.requireConfirm === true;++ const data = await apiRequest('/api/autopilot/config', { method: 'POST', body });+ return { ok: true, agentId, config: data?.config ?? null };+ },+};diff --git a/packages/autopilot-mcp/src/tools/undo-action.js b/packages/autopilot-mcp/src/tools/undo-action.jsnew file mode 100644index 000000000..7c901785f--- /dev/null+++ b/packages/autopilot-mcp/src/tools/undo-action.js@@ -0,0 +1,49 @@+// `undo_action` — reverse a reversible executed proposal. Write.+//+// Wraps POST /api/autopilot/proposals { action:'undo', agentId, proposalId } → { proposal, trust }.+// Deletes the real artifact the execution created (the alert rule or the briefing+// notification) and records a feedback memory so the agent learns the boundary.+// A $THREE wallet_transfer is on-chain and CANNOT be undone — the server rejects it.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'undo_action',+ title: 'Undo a reversible autopilot action',+ // Write: reverses a prior execution. Not destructive — it removes the created+ // artifact and is the corrective path, not a value-moving action.+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'Reverse a reversible executed proposal: deletes the real artifact the execution created — the alert ' ++ 'rule (create_alert) or the briefing notification (briefing) — and records a feedback memory so the ' ++ 'agent learns to be more conservative next time. WRITE. NOTE: an irreversible $THREE wallet_transfer ' ++ 'is on-chain and cannot be undone — the server rejects that with `irreversible`; to send value back ' ++ 'you would have to execute a new transfer. Returns the updated proposal (status → undone) and trust.',+ inputSchema: {+ agentId: z+ .string()+ .min(1)+ .describe('UUID of the agent that owns the proposal. Must be an agent owned by the credential.'),+ proposalId: z+ .string()+ .min(1)+ .describe('UUID of the executed proposal to undo.'),+ },+ async handler(args) {+ const agentId = String(args?.agentId ?? '').trim();+ const proposalId = String(args?.proposalId ?? '').trim();+ const data = await apiRequest('/api/autopilot/proposals', {+ method: 'POST',+ body: { action: 'undo', agentId, proposalId },+ });+ return {+ ok: true,+ agentId,+ proposalId,+ proposal: data?.proposal ?? null,+ trust: data?.trust ?? null,+ };+ },+};diff --git a/packages/autopilot-mcp/test/registration.test.mjs b/packages/autopilot-mcp/test/registration.test.mjsnew file mode 100644index 000000000..8ba426e1f--- /dev/null+++ b/packages/autopilot-mcp/test/registration.test.mjs@@ -0,0 +1,111 @@+// Tool-surface invariants for @three-ws/autopilot-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 and need no credential.+//+// Run: node --test packages/autopilot-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_autopilot_config',+ 'set_autopilot_config',+ 'generate_proposals',+ 'list_proposals',+ 'dryrun_proposal',+ 'adjust_proposal',+ 'execute_proposal',+ 'dismiss_proposal',+ 'undo_action',+ 'list_autopilot_activity',+ 'compute_trust',+];++// The tools that perform a real write (mutate config / queue / take action).+const WRITE_NAMES = new Set([+ 'set_autopilot_config',+ 'generate_proposals',+ 'adjust_proposal',+ 'execute_proposal',+ 'dismiss_proposal',+ 'undo_action',+]);++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('write tools are annotated readOnlyHint:false; read tools readOnlyHint:true', () => {+ for (const tool of TOOLS) {+ const expectWrite = WRITE_NAMES.has(tool.name);+ assert.equal(+ tool.annotations.readOnlyHint,+ !expectWrite,+ `${tool.name} readOnlyHint should be ${!expectWrite}`,+ );+ }+});++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('execute_proposal is the funds-moving, destructive write', () => {+ const exec = TOOLS.find((t) => t.name === 'execute_proposal');+ assert.ok(exec, 'execute_proposal must exist');+ assert.equal(exec.annotations.readOnlyHint, false, 'execute_proposal must be a write');+ assert.equal(exec.annotations.destructiveHint, true, 'execute_proposal must be flagged destructive');+ assert.equal(exec.annotations.idempotentHint, false, 'execute_proposal is not idempotent');+});++test('config + adjust writes are idempotent; action writes are not', () => {+ const idempotent = new Set(['set_autopilot_config', 'adjust_proposal']);+ for (const tool of TOOLS) {+ if (!WRITE_NAMES.has(tool.name)) continue;+ assert.equal(+ tool.annotations.idempotentHint,+ idempotent.has(tool.name),+ `${tool.name} idempotentHint should be ${idempotent.has(tool.name)}`,+ );+ }+});++test('buildServer registers every tool with its annotations, without a credential', () => {+ 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/copy-mcp/LICENSE b/packages/copy-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/copy-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/copy-mcp/README.md b/packages/copy-mcp/README.mdnew file mode 100644index 000000000..62b63eabc--- /dev/null+++ b/packages/copy-mcp/README.md@@ -0,0 +1,187 @@+<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/copy-mcp</h1>++<p align="center"><strong>Drive your three.ws copy-trading from any AI agent — follow leaders, tune sizing & guard rules, work the copy-intent inbox, and track fees owed. Headless, non-custodial.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/copy-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/copy-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/copy-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/copy-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 turns the three.ws **copy-trading** control surface — follow/unfollow leaders, tune guard rules, read your copy-intent inbox, and see fees owed — into agent-drivable tools over stdio. Everything the website's copy dashboard does, headless.++**Non-custodial by design.** three.ws never signs a transaction or holds your funds. When a leader you follow trades, the engine produces a **sized, guard-checked copy INTENT** that you (or your agent) act on from your own wallet. Every order is clamped to your per-trade cap and your remaining daily budget, so a runaway leader can never drain you. Performance fees settle in **$THREE**.++## Install++```bash+npm install @three-ws/copy-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/copy-mcp+```++## Quick start++Copy trading is account-scoped, so set `THREE_WS_API_KEY` to a three.ws API key (`sk_live_…` / `sk_test_…`) or OAuth access token — mint one at [three.ws/settings/api-keys](https://three.ws/settings/api-keys).++**Claude Code**, one line:++```bash+claude mcp add copy --env THREE_WS_API_KEY=sk_live_xxx -- npx -y @three-ws/copy-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "copy": {+ "command": "npx",+ "args": ["-y", "@three-ws/copy-mcp"],+ "env": { "THREE_WS_API_KEY": "sk_live_xxx" }+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+THREE_WS_API_KEY=sk_live_xxx npx -y @modelcontextprotocol/inspector npx @three-ws/copy-mcp+```++> Discovery (which leaders to follow) lives in [`@three-ws/intel-mcp`](https://www.npmjs.com/package/@three-ws/intel-mcp) → `copy_smart_wallets`. This server manages the follows you commit to.++## Tools++| Tool | Type | What it does |+| --------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------- |+| `list_subscriptions` | read-only | Every leader you follow — status, sizing rule, full guard-rule set, perf fee, and live pending/acted counts. |+| `create_subscription` | write (idempotent)| Follow a leader / re-tune the follow. Defines how their trades size into your wallet. Upserts per leader. |+| `update_subscription` | write (idempotent)| Pause / resume / stop a follow, or change its sizing & guard rules. Patch by id — only the fields you pass. |+| `cancel_subscription` | write (destructive)| Soft-stop a follow: no more intents, history preserved. Re-follow later with `create_subscription`. |+| `get_executions` | read-only | Your copy-intent inbox + history — coin, direction, sized order, skip reason, status, recorded fill. |+| `record_execution` | write | Mark a pending intent **acted** (optionally with your fill signature) or **dismissed**. Never signs for you. |+| `get_earnings` | read-only | Your fees owed across the leaders you copy — or, with `agent_id`, a leader's public aggregate earnings. |++All reads return live data (counts, intents, and accruals move between calls), so none are idempotent.++### Input parameters++**`list_subscriptions`** — none.++**`create_subscription`** — `leader_agent_id` (required, UUID), `copier_wallet` (required, base58), `network` (`mainnet` | `devnet`, default `mainnet`), `sizing_rule` (`fixed` | `multiplier` | `pct_balance`, default `fixed`), `fixed_sol` (required for `fixed` sizing), `multiplier` (default `0.1`), `pct_balance` (0–100), `per_trade_cap_sol` (default `0.5`), `min_order_sol` (default `0.02`), `daily_budget_sol` (default `1`), `max_open_copies` (1–100, default `5`), `mcap_floor_usd`, `mcap_ceiling_usd`, `copy_sells` (default `true`), `require_safety_pass` (default `false`), `min_oracle_score` (0–100), `perf_fee_bps` (0–3000, default `1000`), `telegram_chat_id`.++**`update_subscription`** — `id` (required, UUID) plus any of: `status` (`active` | `paused` | `stopped`), and the same sizing/guard fields as `create_subscription` (each optional; pass `null` to clear `mcap_floor_usd` / `mcap_ceiling_usd` / `min_oracle_score` / `telegram_chat_id`). Only the fields you pass change.++**`cancel_subscription`** — `id` (required, UUID).++**`get_executions`** — `status` (`pending` | `acted` | `dismissed` | `skipped` | `expired` | `all`, default `pending`), `limit` (1–100, default `50`).++**`record_execution`** — `id` (required, UUID), `action` (`acted` | `dismissed`), `tx_signature` (optional, recorded only when `acted`).++**`get_earnings`** — `agent_id` (optional UUID — provide for a leader's public aggregate; omit for your own rollup), `network` (`mainnet` | `devnet`, default `mainnet`).++## Example++```jsonc+// create_subscription — follow a leader, 0.05 SOL per copy, capped, safety-gated+> {+ "leader_agent_id": "8f3c…-uuid",+ "copier_wallet": "7Np…YourWallet",+ "sizing_rule": "fixed",+ "fixed_sol": 0.05,+ "per_trade_cap_sol": 0.1,+ "daily_budget_sol": 0.5,+ "mcap_floor_usd": 50000,+ "require_safety_pass": true+ }+{+ "ok": true,+ "subscription": {+ "id": "…",+ "status": "active",+ "network": "mainnet",+ "leader": { "agent_id": "8f3c…", "name": "…", "image": "…", "wallet": "…" },+ "copier_wallet": "7Np…YourWallet",+ "sizing": { "rule": "fixed", "fixed_sol": 0.05, "multiplier": 0.1, "pct_balance": 0 },+ "guards": {+ "per_trade_cap_sol": 0.1, "min_order_sol": 0.02, "daily_budget_sol": 0.5,+ "max_open_copies": 5, "mcap_floor_usd": 50000, "mcap_ceiling_usd": null,+ "copy_sells": true, "require_safety_pass": true, "min_oracle_score": null+ },+ "perf_fee_bps": 1000,+ "pending_count": 0,+ "acted_count": 0+ }+}+```++```jsonc+// get_executions — the actionable inbox+> { "status": "pending", "limit": 5 }+{+ "ok": true,+ "status": "pending",+ "count": 1,+ "executions": [+ {+ "id": "…",+ "status": "pending",+ "leader": { "name": "…" },+ "coin": { "mint": "…", "symbol": "…", "name": "…" },+ "direction": "buy",+ "planned_sol": 0.05,+ "expires_at": "…"+ }+ ]+}+```++```jsonc+// record_execution — you bought it yourself; log the fill+> { "id": "…", "action": "acted", "tx_signature": "5xQ…" }+{ "ok": true, "execution": { "id": "…", "status": "acted", "tx_signature": "5xQ…" } }+```++## Requirements++- **Node.js >= 20.**+- A three.ws account credential in `THREE_WS_API_KEY` (all tools except a leader's public aggregate earnings).+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).++### Environment variables++| Variable | Required | Default | Notes |+| --------------------- | -------- | ------------------ | -------------------------------------------------------- |+| `THREE_WS_API_KEY` | **yes** | — | API key (`sk_live_…`) or OAuth token. Treat like cash. |+| `THREE_WS_BASE` | no | `https://three.ws` | Override for self-hosting / preview deployments. |+| `THREE_WS_TIMEOUT_MS` | no | `20000` | Per-request timeout in ms. |++## 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/copy-mcp/package.json b/packages/copy-mcp/package.jsonnew file mode 100644index 000000000..296ac4d81--- /dev/null+++ b/packages/copy-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/copy-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/copy-mcp",+ "description": "Manage your three.ws copy-trade follows from any AI agent — follow/unfollow leaders, tune sizing & guard rules, read the copy-intent inbox, and track fees owed. Account-scoped, non-custodial, 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/copy-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "copy-trading",+ "copy-trade",+ "subscriptions",+ "non-custodial",+ "agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "copy-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/copy-mcp/server.json b/packages/copy-mcp/server.jsonnew file mode 100644index 000000000..153b21915--- /dev/null+++ b/packages/copy-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/copy-mcp",+ "title": "three.ws Copy Trading",+ "description": "Manage your copy-trade follows from any AI agent — follow leaders, tune sizing & guard rules, work the copy-intent inbox, and track fees owed. Non-custodial.",+ "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/copy-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/copy-mcp",+ "version": "0.1.0",+ "runtimeHint": "npx",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "THREE_WS_API_KEY",+ "description": "Your three.ws bearer credential — an API key (sk_live_… / sk_test_…) or OAuth access token. Every copy-trade subscription, intent, and fee is scoped to the account it identifies. Required for all tools except a leader's public aggregate earnings. Mint one at https://three.ws/settings/api-keys. Treat like cash.",+ "format": "string",+ "isRequired": true,+ "isSecret": true+ },+ {+ "name": "THREE_WS_BASE",+ "description": "Base URL of the three.ws API that serves the copy-trading 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 copy-trading reads and writes.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ }+ ]+ }+ ]+}diff --git a/packages/copy-mcp/src/config.js b/packages/copy-mcp/src/config.jsnew file mode 100644index 000000000..a0f72dfae--- /dev/null+++ b/packages/copy-mcp/src/config.js@@ -0,0 +1,41 @@+// Centralized env + HTTP base for the copy-trading MCP.+//+// This server is the account-scoped control surface for a copier's own+// copy-trade relationships (/api/copy/subscriptions, /api/copy/executions,+// /api/copy/earnings). Every account-scoped call carries the copier's bearer+// credential — a three.ws API key (sk_live_… / sk_test_…) or an OAuth access+// token — so the API resolves "me" the same way the website does. The server+// holds no Solana key and never signs: copy trading here is non-custodial, so+// the only secret is the bearer that authenticates the copier.++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 copier's bearer credential. Read lazily (empty default) so importing the+// module — and therefore buildServer() in the offline tests — never requires a+// key; account-scoped tools throw a clear `missing_credential` at call time if+// it is absent. Mint one at https://three.ws/settings/api-keys.+export const THREE_WS_API_KEY = env('THREE_WS_API_KEY', '');++// Per-request timeout (ms). These are live reads/writes against the copy engine+// — 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/copy-mcp';diff --git a/packages/copy-mcp/src/index.js b/packages/copy-mcp/src/index.jsnew file mode 100644index 000000000..6ad3d5a6b--- /dev/null+++ b/packages/copy-mcp/src/index.js@@ -0,0 +1,136 @@+#!/usr/bin/env node+// @three-ws/copy-mcp — MCP server entry point.+//+// The copy-trading control surface for an AI agent's OWN follow/guard/earn+// relationships on three.ws. Headless, non-custodial — three.ws never signs or+// holds funds; it emits sized, guard-checked copy INTENTS the copier acts on.+//+// • list_subscriptions — every leader you follow + status + guards + counts+// • create_subscription — follow a leader / re-tune the follow (idempotent)+// • update_subscription — pause / resume / stop, or change sizing & guards+// • cancel_subscription — soft-stop a follow (destructive; keeps history)+// • get_executions — your copy-intent inbox + history+// • record_execution — mark a pending intent acted-on / dismissed+// • get_earnings — fees owed (yours) or a leader's public aggregate+//+// Account-scoped: set THREE_WS_API_KEY to a three.ws API key (sk_live_…) or+// OAuth access token. The only public read is a leader's aggregate earnings.+//+// Run standalone:+// THREE_WS_API_KEY=sk_live_… node packages/copy-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 listSubscriptions } from './tools/list-subscriptions.js';+import { def as createSubscription } from './tools/create-subscription.js';+import { def as updateSubscription } from './tools/update-subscription.js';+import { def as cancelSubscription } from './tools/cancel-subscription.js';+import { def as getExecutions } from './tools/get-executions.js';+import { def as recordExecution } from './tools/record-execution.js';+import { def as getEarnings } from './tools/get-earnings.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 = [+ listSubscriptions,+ createSubscription,+ updateSubscription,+ cancelSubscription,+ getExecutions,+ recordExecution,+ getEarnings,+];++/**+ * Construct a fully-registered McpServer without connecting a transport.+ * Registration is env-free (the API key is only read at call time), so this is+ * safe to import from tests.+ * @returns {McpServer}+ */+export function buildServer() {+ const server = new McpServer(+ { name: 'copy-mcp', title: 'three.ws Copy Trading', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Copy Trading MCP — manage your OWN copy-trade relationships headlessly. ' ++ 'list_subscriptions shows every leader you follow with status, sizing, and guard rules. ' ++ 'create_subscription follows a leader and defines how their trades size into your wallet ' ++ '(idempotent — re-call to re-tune); update_subscription pauses/resumes/stops a follow or ' ++ 'changes its caps, budget, market-cap band, and safety gates; cancel_subscription soft-stops ' ++ 'it (history preserved). get_executions is your copy-intent inbox; record_execution marks a ' ++ 'pending intent acted-on or dismissed. get_earnings reports the fees you owe across the ' ++ 'leaders you copy, or a leader\'s public aggregate earnings. NON-CUSTODIAL: three.ws never ' ++ 'signs or holds funds — copies are sized, guard-checked INTENTS you execute yourself, always ' ++ 'clamped to your per-trade cap and daily budget. Account-scoped: set THREE_WS_API_KEY. ' ++ 'Performance fees settle in $THREE.',+ },+ );++ 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(`[copy-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('[copy-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/copy-mcp/src/lib/api.js b/packages/copy-mcp/src/lib/api.jsnew file mode 100644index 000000000..84947cfd2--- /dev/null+++ b/packages/copy-mcp/src/lib/api.js@@ -0,0 +1,83 @@+// Real HTTP access to the three.ws copy-trading API. No mocks, no fixtures —+// every call is a live request to THREE_WS_BASE. Account-scoped calls attach the+// copier's bearer credential (THREE_WS_API_KEY); the API resolves the copier and+// scopes every read/write to their own subscriptions. Errors are normalized into+// a single shape so tool handlers can surface a clean message + status.++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT, THREE_WS_API_KEY } from '../config.js';++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/copy/subscriptions`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown, auth?: boolean }} [opts]+ * `auth` defaults to true — the call attaches `Authorization: Bearer <key>` and+ * throws `missing_credential` when no key is configured. Pass `auth:false` for+ * the genuinely public endpoints (e.g. a leader's aggregate earnings).+ * @returns {Promise<any>} Parsed JSON response.+ * @throws {Error} with `.code` ('missing_credential' | 'timeout' | 'network_error'+ * | 'upstream_error'), and on upstream errors `.status` + `.body`.+ */+export async function apiRequest(path, { method = 'GET', query, body, auth = true } = {}) {+ if (auth && !THREE_WS_API_KEY) {+ throw Object.assign(+ new Error(+ 'This action is account-scoped. Set THREE_WS_API_KEY to a three.ws API key ' ++ '(sk_live_… / sk_test_…) or OAuth access token — mint one at ' ++ 'https://three.ws/settings/api-keys.',+ ),+ { code: 'missing_credential', status: 401 },+ );+ }++ 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_API_KEY ? { 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/copy-mcp/src/lib/shapes.js b/packages/copy-mcp/src/lib/shapes.jsnew file mode 100644index 000000000..e999f4220--- /dev/null+++ b/packages/copy-mcp/src/lib/shapes.js@@ -0,0 +1,84 @@+// Presentation shapes for the copy API rows. The API returns full DB rows+// (copy_subscriptions / copy_executions joined with the leader's identity); these+// helpers project them into clean, documented, agent-facing objects so a tool's+// output is self-describing — leader info grouped, guard rules grouped, numbers+// coerced from Postgres numeric strings into real numbers.++const num = (v) => (v === null || v === undefined || v === '' ? null : Number(v));++/** Group the leader-identity columns the API joins onto every row. */+function leaderOf(row) {+ return {+ agent_id: row.leader_agent_id ?? null,+ name: row.leader_name ?? null,+ image: row.leader_image ?? row.leader_avatar ?? null,+ wallet: row.leader_wallet ?? null,+ };+}++/**+ * Shape a copy_subscriptions row (+ joined leader + counts) into a documented+ * subscription object: identity, status, sizing rule, guard rules, and the+ * pending/acted execution counts the list endpoint computes.+ */+export function shapeSubscription(row) {+ if (!row || typeof row !== 'object') return row;+ return {+ id: row.id,+ status: row.status, // 'active' | 'paused' | 'stopped'+ network: row.network,+ leader: leaderOf(row),+ copier_wallet: row.copier_wallet,+ sizing: {+ rule: row.sizing_rule, // 'fixed' | 'multiplier' | 'pct_balance'+ fixed_sol: num(row.fixed_sol),+ multiplier: num(row.multiplier),+ pct_balance: num(row.pct_balance),+ },+ guards: {+ per_trade_cap_sol: num(row.per_trade_cap_sol),+ min_order_sol: num(row.min_order_sol),+ daily_budget_sol: num(row.daily_budget_sol),+ max_open_copies: num(row.max_open_copies),+ mcap_floor_usd: num(row.mcap_floor_usd),+ mcap_ceiling_usd: num(row.mcap_ceiling_usd),+ copy_sells: row.copy_sells,+ require_safety_pass: row.require_safety_pass,+ min_oracle_score: num(row.min_oracle_score),+ },+ perf_fee_bps: num(row.perf_fee_bps),+ high_water_mark_sol: num(row.high_water_mark_sol),+ telegram_chat_id: row.telegram_chat_id ?? null,+ pending_count: row.pending_count === undefined ? undefined : Number(row.pending_count),+ acted_count: row.acted_count === undefined ? undefined : Number(row.acted_count),+ created_at: row.created_at ?? null,+ updated_at: row.updated_at ?? null,+ };+}++/**+ * Shape a copy_executions row (+ joined leader) into a documented copy-intent+ * object: the coin, the mirrored direction, the sized order, why it was skipped+ * (if it was), its lifecycle status, and the copier's recorded fill signature.+ */+export function shapeExecution(row) {+ if (!row || typeof row !== 'object') return row;+ return {+ id: row.id,+ subscription_id: row.subscription_id,+ status: row.status, // 'pending' | 'acted' | 'dismissed' | 'skipped' | 'expired'+ network: row.network,+ leader: leaderOf(row),+ coin: { mint: row.mint, symbol: row.symbol ?? null, name: row.name ?? null },+ direction: row.direction, // 'buy' | 'sell'+ planned_sol: num(row.planned_sol),+ leader_entry_sol: num(row.leader_entry_sol),+ skip_reason: row.skip_reason ?? null,+ safety: row.safety ?? null,+ quote: row.quote ?? null,+ tx_signature: row.tx_signature ?? null,+ created_at: row.created_at ?? null,+ updated_at: row.updated_at ?? null,+ expires_at: row.expires_at ?? null,+ };+}diff --git a/packages/copy-mcp/src/tools/cancel-subscription.js b/packages/copy-mcp/src/tools/cancel-subscription.jsnew file mode 100644index 000000000..2a0d92374--- /dev/null+++ b/packages/copy-mcp/src/tools/cancel-subscription.js@@ -0,0 +1,28 @@+// `cancel_subscription` — stop following a leader. Write, destructive.+//+// Wraps DELETE /api/copy/subscriptions?id=<id>. This is a SOFT stop: the+// subscription transitions to status="stopped" and stops generating any new copy+// intents, but its history (past executions, earnings) is preserved. To follow+// the same leader again later, call create_subscription (it re-activates the row).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'cancel_subscription',+ title: 'Stop a copy-trade subscription',+ annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: true, openWorldHint: true },+ description:+ 'Stop following a leader: transitions the subscription to "stopped" so no new copy intents are generated. DESTRUCTIVE in that it ends an active money-adjacent follow — but it is a SOFT stop: execution history and earnings are preserved, and you can re-follow the same leader later with create_subscription. To merely halt copies temporarily without ending the follow, use update_subscription with status:"paused" instead. Returns the cancellation result. Requires THREE_WS_API_KEY.',+ inputSchema: {+ id: z.string().uuid().describe('UUID of the subscription to stop (from list_subscriptions).'),+ },+ async handler(args) {+ const data = await apiRequest('/api/copy/subscriptions', {+ method: 'DELETE',+ query: { id: args.id },+ });+ return { ok: data?.ok ?? true, id: data?.id ?? args.id, status: data?.status ?? 'stopped' };+ },+};diff --git a/packages/copy-mcp/src/tools/create-subscription.js b/packages/copy-mcp/src/tools/create-subscription.jsnew file mode 100644index 000000000..bc6a326ef--- /dev/null+++ b/packages/copy-mcp/src/tools/create-subscription.js@@ -0,0 +1,79 @@+// `create_subscription` — follow a leader (or re-tune an existing follow).+// Write, idempotent: the API upserts on (account, leader, network), so calling+// it again with the same leader updates that subscription instead of duplicating+// it and (re)sets its status to active.+//+// Wraps POST /api/copy/subscriptions (the create/update path).+//+// MONEY-ADJACENT: this defines how much of the copier's OWN SOL each mirrored+// trade may spend. It is non-custodial — three.ws never signs or holds funds; it+// only emits sized, guard-checked copy INTENTS the copier acts on. Sizing is+// always clamped to per_trade_cap_sol and the remaining daily_budget_sol, so a+// runaway leader can never drain the copier.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeSubscription } from '../lib/shapes.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++export const def = {+ name: 'create_subscription',+ title: 'Follow a leader (create / update subscription)',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Follow a copy-trade leader from the authenticated account, defining how their trades are mirrored into your own wallet. MONEY-ADJACENT: this sets how much of YOUR SOL each copy may spend. Non-custodial — three.ws never signs or holds funds; it emits sized, guard-checked copy INTENTS you act on. Idempotent: re-calling with the same leader_agent_id + network updates that subscription (and re-activates it) rather than creating a duplicate. Sizing rule: "fixed" spends fixed_sol per copy; "multiplier" spends multiplier × the leader\'s entry; "pct_balance" spends pct_balance % of your spendable SOL. Every order is clamped to per_trade_cap_sol and the remaining daily_budget_sol. Returns the created/updated subscription. Requires THREE_WS_API_KEY.',+ inputSchema: {+ leader_agent_id: z.string().uuid().describe('UUID of the public leader (agent with a sniper track record) to follow.'),+ copier_wallet: z+ .string()+ .regex(BASE58_RE, 'must be a base58 Solana address')+ .describe('Your own Solana wallet address that will execute the mirrored trades. Never a private key — non-custodial.'),+ network: z.enum(['mainnet', 'devnet']).default('mainnet').describe('Solana network (default mainnet).'),+ sizing_rule: z+ .enum(['fixed', 'multiplier', 'pct_balance'])+ .default('fixed')+ .describe('How each copy is sized: fixed | multiplier (× leader entry) | pct_balance (% of your SOL). Default fixed.'),+ fixed_sol: z.number().positive().optional().describe('SOL spent per copy when sizing_rule="fixed". Required for fixed sizing.'),+ multiplier: z.number().positive().default(0.1).describe('Fraction of the leader\'s entry size to copy when sizing_rule="multiplier" (default 0.1).'),+ pct_balance: z.number().gt(0).max(100).optional().describe('Percent of your spendable SOL per copy when sizing_rule="pct_balance" (0–100).'),+ per_trade_cap_sol: z.number().positive().default(0.5).describe('Hard ceiling on any single copy, in SOL (default 0.5). Must be > 0.'),+ min_order_sol: z.number().min(0).default(0.02).describe('Skip dust copies sized below this, in SOL (default 0.02). Cannot exceed per_trade_cap_sol.'),+ daily_budget_sol: z.number().positive().default(1).describe('Max SOL fanned out across copies per UTC day (default 1). Must be > 0.'),+ max_open_copies: z.number().int().min(1).max(100).default(5).describe('Cap on concurrent pending copy intents (1–100, default 5).'),+ mcap_floor_usd: z.number().nonnegative().nullable().optional().describe('Skip coins below this market cap (USD). Omit/null to ignore.'),+ mcap_ceiling_usd: z.number().nonnegative().nullable().optional().describe('Skip coins above this market cap (USD). Omit/null to ignore.'),+ copy_sells: z.boolean().default(true).describe('Mirror the leader\'s exits, not just entries (default true).'),+ require_safety_pass: z.boolean().default(false).describe('Skip a copy when the coin\'s safety context cannot be confirmed (default false).'),+ min_oracle_score: z.number().int().min(0).max(100).nullable().optional().describe('Skip coins whose Oracle conviction score is below this (0–100). Omit/null to ignore.'),+ perf_fee_bps: z.number().int().min(0).max(3000).default(1000).describe('Leader\'s performance fee on your realized copy profit, in basis points (0–3000, default 1000 = 10%). Charged above a high-water mark, settled in $THREE.'),+ telegram_chat_id: z.string().regex(/^-?[0-9]+$/, 'must be a numeric Telegram chat ID').nullable().optional().describe('Optional Telegram chat ID to receive copy-intent alerts for this subscription.'),+ },+ async handler(args) {+ const data = await apiRequest('/api/copy/subscriptions', {+ method: 'POST',+ body: {+ leader_agent_id: args.leader_agent_id,+ copier_wallet: args.copier_wallet,+ network: args.network,+ sizing_rule: args.sizing_rule,+ fixed_sol: args.fixed_sol,+ multiplier: args.multiplier,+ pct_balance: args.pct_balance,+ per_trade_cap_sol: args.per_trade_cap_sol,+ min_order_sol: args.min_order_sol,+ daily_budget_sol: args.daily_budget_sol,+ max_open_copies: args.max_open_copies,+ mcap_floor_usd: args.mcap_floor_usd,+ mcap_ceiling_usd: args.mcap_ceiling_usd,+ copy_sells: args.copy_sells,+ require_safety_pass: args.require_safety_pass,+ min_oracle_score: args.min_oracle_score,+ perf_fee_bps: args.perf_fee_bps,+ telegram_chat_id: args.telegram_chat_id,+ },+ });+ return { ok: true, subscription: shapeSubscription(data?.subscription) };+ },+};diff --git a/packages/copy-mcp/src/tools/get-earnings.js b/packages/copy-mcp/src/tools/get-earnings.jsnew file mode 100644index 000000000..4d5ca7fb9--- /dev/null+++ b/packages/copy-mcp/src/tools/get-earnings.js@@ -0,0 +1,59 @@+// `get_earnings` — copy-trade performance-fee accounting. Read-only.+//+// Wraps GET /api/copy/earnings. Two modes off one route:+// • no agent_id → the authenticated copier's own fees OWED across the leaders+// they copy, per subscription (account-scoped; needs THREE_WS_API_KEY).+// • agent_id → a leader's PUBLIC aggregate copy earnings (the "this trader+// has earned X for being copied" social-proof figure; no key required).+//+// Every figure is real: realized copy profit above each subscription's+// high-water mark, charged at the leader's perf_fee_bps, settled in $THREE.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_earnings',+ title: 'Copy-trade earnings & fees owed',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read copy-trade performance-fee accounting. Without agent_id: the authenticated account\'s own fees OWED across every leader they copy — a total plus a per-subscription breakdown (cumulative realized copy profit, closed copies, billable profit above the high-water mark, and the fee). With agent_id: a leader\'s PUBLIC aggregate earnings (active copiers, accrued fee, total copier profit) — the social-proof figure, no per-copier identity exposed and no API key required. All figures are real: realized copy profit above each subscription\'s high-water mark at the leader\'s fee, settled in $THREE. Read-only.',+ inputSchema: {+ agent_id: z+ .string()+ .uuid()+ .optional()+ .describe('Optional leader agent UUID. Provide it for that leader\'s public aggregate earnings; omit it for your own fees-owed rollup (requires THREE_WS_API_KEY).'),+ network: z.enum(['mainnet', 'devnet']).default('mainnet').describe('Solana network for the leader aggregate (default mainnet). Ignored for your own rollup.'),+ },+ async handler(args) {+ // Public leader aggregate — no credential required.+ if (args.agent_id) {+ const data = await apiRequest('/api/copy/earnings', {+ query: { agent_id: args.agent_id, network: args.network },+ auth: false,+ });+ return {+ ok: true,+ scope: 'leader',+ agent_id: data?.agent_id ?? args.agent_id,+ network: data?.network ?? args.network,+ copiers: Number(data?.copiers) || 0,+ accrued_fee_sol: Number(data?.accrued_fee_sol) || 0,+ copier_profit_sol: Number(data?.copier_profit_sol) || 0,+ };+ }++ // The authenticated copier's own fees owed.+ const data = await apiRequest('/api/copy/earnings');+ const items = Array.isArray(data?.items) ? data.items : [];+ return {+ ok: true,+ scope: 'mine',+ total_fee_owed_sol: Number(data?.total_fee_owed_sol) || 0,+ count: items.length,+ items,+ };+ },+};diff --git a/packages/copy-mcp/src/tools/get-executions.js b/packages/copy-mcp/src/tools/get-executions.jsnew file mode 100644index 000000000..5a75011eb--- /dev/null+++ b/packages/copy-mcp/src/tools/get-executions.js@@ -0,0 +1,38 @@+// `get_executions` — the copier's copy-intent inbox + history. Read-only.+//+// Wraps GET /api/copy/executions?status=&limit=. Reading lazily expires stale+// pending intents server-side, so a 'pending' read always reflects what is still+// actionable right now.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeExecution } from '../lib/shapes.js';++export const def = {+ name: 'get_executions',+ title: 'List copy executions (intent inbox)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List the authenticated account\'s copy executions — the sized, guard-checked copy INTENTS generated when a followed leader trades. Each row carries the coin (mint/symbol/name), the mirrored direction (buy/sell), the planned SOL size, the leader, the safety/quote snapshot used for the decision, the lifecycle status, and any fill signature you recorded. Filter by status: "pending" (actionable now — default), "acted", "dismissed", "skipped" (guard blocked it, with skip_reason), "expired", or "all". Reading refreshes the inbox: stale pending intents are expired automatically. Use record_execution to mark a pending intent acted/dismissed. Read-only; requires THREE_WS_API_KEY.',+ inputSchema: {+ status: z+ .enum(['pending', 'acted', 'dismissed', 'skipped', 'expired', 'all'])+ .default('pending')+ .describe('Lifecycle filter (default "pending" — only intents still actionable).'),+ limit: z.number().int().min(1).max(100).default(50).describe('Max rows to return, newest first (1–100, default 50).'),+ },+ async handler(args) {+ const data = await apiRequest('/api/copy/executions', {+ query: { status: args.status, limit: args.limit },+ });+ const rows = Array.isArray(data?.executions) ? data.executions : [];+ const executions = rows.map(shapeExecution);+ return {+ ok: true,+ status: args.status,+ count: executions.length,+ executions,+ };+ },+};diff --git a/packages/copy-mcp/src/tools/list-subscriptions.js b/packages/copy-mcp/src/tools/list-subscriptions.jsnew file mode 100644index 000000000..4e4905cce--- /dev/null+++ b/packages/copy-mcp/src/tools/list-subscriptions.js@@ -0,0 +1,27 @@+// `list_subscriptions` — the copier's own follow list. Read-only, account-scoped.+//+// Wraps GET /api/copy/subscriptions.++import { apiRequest } from '../lib/api.js';+import { shapeSubscription } from '../lib/shapes.js';++export const def = {+ name: 'list_subscriptions',+ title: 'List my copy-trade subscriptions',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List the copy-trade subscriptions belonging to the authenticated account — every leader (a trader with a track record) you follow, with their identity, the subscription status (active / paused / stopped), the sizing rule and full guard-rule set, the performance fee, the high-water mark, and live pending/acted copy-intent counts. Use this to audit who you copy and how aggressively before tuning a follow with update_subscription. Returns the subscriptions newest-first. Read-only; requires THREE_WS_API_KEY.',+ inputSchema: {},+ async handler() {+ const data = await apiRequest('/api/copy/subscriptions');+ const rows = Array.isArray(data?.subscriptions) ? data.subscriptions : [];+ const subscriptions = rows.map(shapeSubscription);+ return {+ ok: true,+ count: subscriptions.length,+ active: subscriptions.filter((s) => s.status === 'active').length,+ paused: subscriptions.filter((s) => s.status === 'paused').length,+ subscriptions,+ };+ },+};diff --git a/packages/copy-mcp/src/tools/record-execution.js b/packages/copy-mcp/src/tools/record-execution.jsnew file mode 100644index 000000000..ed207d023--- /dev/null+++ b/packages/copy-mcp/src/tools/record-execution.js@@ -0,0 +1,42 @@+// `record_execution` — mark a pending copy intent as acted-on or dismissed.+// Write, not idempotent (a one-way pending → acted/dismissed transition; once+// transitioned the same intent can't be re-recorded).+//+// Wraps POST /api/copy/executions { id, action, tx_signature? }. Non-custodial:+// "acted" simply RECORDS that the copier executed the trade from their own wallet+// (optionally with the fill signature for their records). three.ws never signs or+// broadcasts — this closes the loop on an intent, it does not place an order.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeExecution } from '../lib/shapes.js';++export const def = {+ name: 'record_execution',+ title: 'Record acting on a copy intent',+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ description:+ 'Resolve a PENDING copy intent (from get_executions) by recording how you handled it. action:"acted" records that you executed the mirrored trade from your own wallet — optionally with the on-chain tx_signature for your records; action:"dismissed" discards the intent without trading. NON-CUSTODIAL: this never signs, sends, or broadcasts a transaction — it only updates the intent\'s status after YOU traded. Not idempotent: it transitions pending → acted/dismissed once; an intent that already expired or was actioned returns "not_actionable". Returns the updated execution. Requires THREE_WS_API_KEY.',+ inputSchema: {+ id: z.string().uuid().describe('UUID of the pending copy intent (from get_executions with status:"pending").'),+ action: z.enum(['acted', 'dismissed']).describe('"acted" = you executed the trade yourself; "dismissed" = you skipped it.'),+ tx_signature: z+ .string()+ .min(1)+ .max(128)+ .optional()+ .describe('Optional Solana transaction signature of your fill, recorded only when action="acted".'),+ },+ async handler(args) {+ const data = await apiRequest('/api/copy/executions', {+ method: 'POST',+ body: {+ id: args.id,+ action: args.action,+ ...(args.action === 'acted' && args.tx_signature ? { tx_signature: args.tx_signature } : {}),+ },+ });+ return { ok: true, execution: shapeExecution(data?.execution) };+ },+};diff --git a/packages/copy-mcp/src/tools/update-subscription.js b/packages/copy-mcp/src/tools/update-subscription.jsnew file mode 100644index 000000000..e68796bd5--- /dev/null+++ b/packages/copy-mcp/src/tools/update-subscription.js@@ -0,0 +1,126 @@+// `update_subscription` — re-tune a follow by id: pause / resume / stop it, or+// change its sizing & guard rules. Write, idempotent.+//+// The API has two write shapes on POST /api/copy/subscriptions: a status-only+// transition ({ id, status }) and a full upsert keyed on (account, leader,+// network). This tool presents a single patch-by-id surface over both:+// • status-only change → one status POST.+// • guard/sizing change → fetch the current row, merge the provided fields over+// it, and upsert. The upsert re-activates the subscription, so when the+// caller didn't ask to activate we restore the prior (or requested) status+// afterward — editing guards never silently un-pauses a paused follow.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { shapeSubscription } from '../lib/shapes.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// Sizing/guard fields this tool can patch. `network` is intentionally NOT here:+// the upsert is keyed on network, so changing it would fork a new subscription+// rather than edit this one.+const CONFIG_KEYS = [+ 'copier_wallet', 'sizing_rule', 'fixed_sol', 'multiplier', 'pct_balance',+ 'per_trade_cap_sol', 'min_order_sol', 'daily_budget_sol', 'max_open_copies',+ 'mcap_floor_usd', 'mcap_ceiling_usd', 'copy_sells', 'require_safety_pass',+ 'min_oracle_score', 'perf_fee_bps', 'telegram_chat_id',+];++async function findSubscription(id) {+ const data = await apiRequest('/api/copy/subscriptions');+ const rows = Array.isArray(data?.subscriptions) ? data.subscriptions : [];+ return rows.find((r) => r.id === id) || null;+}++async function setStatus(id, status) {+ const data = await apiRequest('/api/copy/subscriptions', { method: 'POST', body: { id, status } });+ return data?.subscription;+}++export const def = {+ name: 'update_subscription',+ title: 'Update a copy-trade subscription',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Re-tune an existing copy-trade subscription by id. Pause it (stop new copies, keep the follow), resume it, stop it, and/or change its sizing rule and guard rules (caps, daily budget, market-cap band, oracle/safety gates, performance fee). MONEY-ADJACENT: guard changes alter how much of your SOL future copies may spend — non-custodial, intents only. Only the fields you pass change; the rest are preserved. Editing guards on a paused subscription keeps it paused unless you also set status:"active". Idempotent. Returns the updated subscription. Requires THREE_WS_API_KEY.',+ inputSchema: {+ id: z.string().uuid().describe('UUID of the subscription to update (from list_subscriptions).'),+ status: z.enum(['active', 'paused', 'stopped']).optional().describe('Set the lifecycle status: active (resume), paused (halt new copies, keep the follow), or stopped (end it, keeps history).'),+ copier_wallet: z.string().regex(BASE58_RE, 'must be a base58 Solana address').optional().describe('Change the Solana wallet that executes mirrored trades.'),+ sizing_rule: z.enum(['fixed', 'multiplier', 'pct_balance']).optional().describe('Change the sizing rule: fixed | multiplier | pct_balance.'),+ fixed_sol: z.number().positive().optional().describe('SOL per copy when sizing_rule="fixed".'),+ multiplier: z.number().positive().optional().describe('Multiple of the leader\'s entry when sizing_rule="multiplier".'),+ pct_balance: z.number().gt(0).max(100).optional().describe('Percent of your SOL per copy when sizing_rule="pct_balance" (0–100).'),+ per_trade_cap_sol: z.number().positive().optional().describe('Hard ceiling on any single copy, in SOL (> 0).'),+ min_order_sol: z.number().min(0).optional().describe('Skip dust copies below this, in SOL. Cannot exceed per_trade_cap_sol.'),+ daily_budget_sol: z.number().positive().optional().describe('Max SOL fanned out per UTC day (> 0).'),+ max_open_copies: z.number().int().min(1).max(100).optional().describe('Cap on concurrent pending copy intents (1–100).'),+ mcap_floor_usd: z.number().nonnegative().nullable().optional().describe('Skip coins below this market cap (USD). Pass null to clear the floor.'),+ mcap_ceiling_usd: z.number().nonnegative().nullable().optional().describe('Skip coins above this market cap (USD). Pass null to clear the ceiling.'),+ copy_sells: z.boolean().optional().describe('Whether to mirror the leader\'s exits as well as entries.'),+ require_safety_pass: z.boolean().optional().describe('Skip a copy when the coin\'s safety cannot be confirmed.'),+ min_oracle_score: z.number().int().min(0).max(100).nullable().optional().describe('Skip coins below this Oracle conviction score (0–100). Pass null to clear the gate.'),+ perf_fee_bps: z.number().int().min(0).max(3000).optional().describe('Leader\'s performance fee in basis points (0–3000).'),+ telegram_chat_id: z.string().regex(/^-?[0-9]+$/, 'must be a numeric Telegram chat ID').nullable().optional().describe('Telegram chat ID for copy-intent alerts. Pass null to clear.'),+ },+ async handler(args) {+ const { id } = args;+ const touchesConfig = CONFIG_KEYS.some((k) => args[k] !== undefined);++ // Pure status change (pause / resume / stop) — single transition.+ if (!touchesConfig) {+ if (!args.status) {+ throw Object.assign(new Error('Nothing to update: pass status and/or at least one sizing/guard field.'), {+ code: 'no_changes',+ status: 400,+ });+ }+ const subscription = await setStatus(id, args.status);+ if (!subscription) {+ throw Object.assign(new Error('No such subscription.'), { code: 'not_found', status: 404 });+ }+ return { ok: true, subscription: shapeSubscription(subscription) };+ }++ // Guard/sizing change — merge over the current row, then upsert.+ const existing = await findSubscription(id);+ if (!existing) {+ throw Object.assign(new Error('No such subscription.'), { code: 'not_found', status: 404 });+ }++ const pick = (key) => (args[key] !== undefined ? args[key] : existing[key]);+ const body = {+ leader_agent_id: existing.leader_agent_id,+ network: existing.network,+ copier_wallet: pick('copier_wallet'),+ sizing_rule: pick('sizing_rule'),+ fixed_sol: pick('fixed_sol'),+ multiplier: pick('multiplier'),+ pct_balance: pick('pct_balance'),+ per_trade_cap_sol: pick('per_trade_cap_sol'),+ min_order_sol: pick('min_order_sol'),+ daily_budget_sol: pick('daily_budget_sol'),+ max_open_copies: pick('max_open_copies'),+ mcap_floor_usd: pick('mcap_floor_usd'),+ mcap_ceiling_usd: pick('mcap_ceiling_usd'),+ copy_sells: pick('copy_sells'),+ require_safety_pass: pick('require_safety_pass'),+ min_oracle_score: pick('min_oracle_score'),+ perf_fee_bps: pick('perf_fee_bps'),+ telegram_chat_id: pick('telegram_chat_id'),+ };++ const upserted = await apiRequest('/api/copy/subscriptions', { method: 'POST', body });+ let subscription = upserted?.subscription;++ // The upsert forces status='active'. Restore the intended status unless the+ // caller explicitly asked to activate.+ const desiredStatus = args.status ?? existing.status;+ if (subscription && desiredStatus !== 'active') {+ subscription = (await setStatus(id, desiredStatus)) ?? subscription;+ }++ return { ok: true, subscription: shapeSubscription(subscription) };+ },+};diff --git a/packages/copy-mcp/test/registration.test.mjs b/packages/copy-mcp/test/registration.test.mjsnew file mode 100644index 000000000..faeea272d--- /dev/null+++ b/packages/copy-mcp/test/registration.test.mjs@@ -0,0 +1,104 @@+// Tool-surface invariants for @three-ws/copy-mcp.+//+// Importing src/index.js is side-effect-free: the stdio transport only connects+// when the file is the process entry point, and buildServer() reads no key (the+// THREE_WS_API_KEY is only touched at call time). These tests run offline — they+// never touch the network.+//+// Run: node --test packages/copy-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_subscriptions',+ 'create_subscription',+ 'update_subscription',+ 'cancel_subscription',+ 'get_executions',+ 'record_execution',+ 'get_earnings',+];++// The write tools — they change the copier's money-adjacent state.+const WRITE_NAMES = new Set([+ 'create_subscription',+ 'update_subscription',+ 'cancel_subscription',+ 'record_execution',+]);++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 non-idempotent; they omit destructiveHint', () => {+ for (const tool of TOOLS) {+ if (WRITE_NAMES.has(tool.name)) continue;+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ // Live copy state moves between calls — reads are never idempotent.+ 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', () => {+ for (const name of WRITE_NAMES) {+ const tool = TOOLS.find((t) => t.name === name);+ assert.ok(tool, `${name} should exist`);+ assert.equal(tool.annotations.readOnlyHint, false, `${name} mutates state — must set readOnlyHint:false`);+ }+});++test('only cancel_subscription is marked destructive', () => {+ for (const tool of TOOLS) {+ if (tool.name === 'cancel_subscription') {+ assert.equal(tool.annotations.destructiveHint, true, 'cancel_subscription must set destructiveHint:true');+ } else {+ assert.notEqual(tool.annotations.destructiveHint, true, `${tool.name} should not be destructive`);+ }+ }+});++test('idempotency hints match the API contract', () => {+ const hint = (name) => TOOLS.find((t) => t.name === name).annotations.idempotentHint;+ // Upsert + by-id config patch are idempotent; recording an action is a one-way transition.+ assert.equal(hint('create_subscription'), true, 'create_subscription upserts — idempotent');+ assert.equal(hint('update_subscription'), true, 'update_subscription patches — idempotent');+ assert.equal(hint('cancel_subscription'), true, 'cancel_subscription soft-stops — idempotent');+ assert.equal(hint('record_execution'), false, 'record_execution is a one-way pending→acted transition');+});++test('buildServer registers every tool with its annotations, without a signer or 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/portfolio-mcp/LICENSE b/packages/portfolio-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/portfolio-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/portfolio-mcp/README.md b/packages/portfolio-mcp/README.mdnew file mode 100644index 000000000..b3673422a--- /dev/null+++ b/packages/portfolio-mcp/README.md@@ -0,0 +1,147 @@+<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/portfolio-mcp</h1>++<p align="center"><strong>An AI agent's own trading state over MCP — portfolio value, PnL, live balances, the public trade feed, and one real write: a signed on-chain Solana transfer.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/portfolio-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/portfolio-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/portfolio-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/portfolio-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 an AI agent programmatic access to its **own** trading state over stdio: what it holds, how that value moves over time, a single token's position with live market data, the platform-wide feed of closed trades and their **realized PnL**, live on-chain balances for any wallet — and one real write, a **signed Solana transfer** of SOL or any SPL token.++Reads hit the live three.ws API and Solana RPC — nothing is mocked. The account-scoped reads run against the agent wallets **you own** (resolved from your three.ws session). The one write, `send_transfer`, signs **locally** with your own key and moves real funds on mainnet.++## Install++```bash+npm install @three-ws/portfolio-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/portfolio-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add portfolio -- npx -y @three-ws/portfolio-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "portfolio": {+ "command": "npx",+ "args": ["-y", "@three-ws/portfolio-mcp"],+ "env": {+ "THREE_WS_SESSION": "<your __Host-sid cookie>",+ "SOLANA_SECRET_KEY": "<base58 secret of the sending wallet>"+ }+ }+ }+}+```++`THREE_WS_SESSION` is only needed for the account-scoped reads; `SOLANA_SECRET_KEY` is only needed for `send_transfer`. The trade feed and on-chain balance reads work with no configuration at all.++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/portfolio-mcp+```++## Tools++| Tool | Type | What it does |+| ------------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------- |+| `get_portfolio_summary` | read · session | Live holdings + USD value across every agent wallet you own, with a per-wallet breakdown. Optional snapshot. |+| `get_portfolio_history` | read · session | Your total portfolio USD value over time, from stored snapshots — the performance chart. |+| `get_portfolio_asset` | read · session | One token deep-dive: which wallets hold it, your total amount/USD, plus live market data and a price-history chart. |+| `get_trades_feed` | read · public | The platform-wide feed of closed positions and their **realized PnL** — newest exit first, filterable by coin. |+| `get_wallet_balances` | read · public | Live on-chain SOL + SPL (incl. Token-2022) balances for any Solana address, straight from the RPC. |+| `send_transfer` | **write · destructive** | Sign and broadcast a real, irreversible Solana mainnet transfer of SOL or any SPL token from your own wallet. |++Everything reads live state — balances, feeds, and broadcasts all move between calls — so no tool is idempotent. `send_transfer` is the only tool that mutates anything.++### Input parameters++**`get_portfolio_summary`** — `snapshot` (bool, default false — also persist a history point).++**`get_portfolio_history`** — `days` (1–365, default 90).++**`get_portfolio_asset`** — `chain` (`solana` | `evm`, required), `id` (`native` or the base58 mint / 0x contract, required), `days` (1–365, default 30).++**`get_trades_feed`** — `network` (`mainnet` | `devnet`, default mainnet), `window` (`1h` | `6h` | `24h` | `7d` | `30d` | `all`, default 24h), `min_pnl_pct` (default 10), `limit` (1–80, default 40), `cursor` (ISO timestamp for pagination), `mint` (filter to one coin).++**`get_wallet_balances`** — `address` (base58, required), `include_tokens` (bool, default true).++**`send_transfer`** — `recipient` (base58, required), `amount` (decimal string, required), `mint` (base58 SPL mint; omit / `native` for SOL), `secret` (base58, overrides `SOLANA_SECRET_KEY`), `priorityMicroLamports` (0–50,000,000), `confirm` (must be `true` to execute).++## Realized vs. live value++Two different questions, two different tools:++- **"What am I worth right now?"** → `get_portfolio_summary` / `get_portfolio_asset` — live holdings priced in USD.+- **"How have my closed trades done?"** → `get_trades_feed` — realized PnL per closed position (entry/exit in SOL, profit %, multiple, hold time).++## The write tool — `send_transfer`++`send_transfer` **broadcasts a real, irreversible transaction on Solana mainnet** and moves funds out of the signing wallet. It signs locally with the per-call `secret` or `SOLANA_SECRET_KEY` — the three.ws API never holds your key. Guardrails:++- **`confirm: true` required** while `REQUIRE_CONFIRM` is on (the default) — the first call without it returns a refusal, not a broadcast.+- **`MAX_SOL_PER_TX`** caps native SOL sends (default 0.5 SOL).+- **`RECIPIENT_ALLOWLIST`**, when set, restricts the destination to a known set.+- The `mint` is **runtime input** — pass the `$THREE` mint or any SPL token you hold. No mint is hardcoded.++For an SPL transfer it reads the mint's decimals on-chain, verifies your balance, and auto-creates the recipient's associated token account when missing. On a confirmation timeout it returns `tx_unconfirmed` with the signature rather than silently retrying — check Solscan before resending to avoid a double-spend.++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`) and a Solana RPC.++### Environment variables++| Variable | Required | Default |+| ----------------------- | ------------------------- | --------------------------------------- |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |+| `THREE_WS_SESSION` | for account-scoped reads | — |+| `SOLANA_RPC_URL` | no | `https://api.mainnet-beta.solana.com` |+| `SOLANA_SECRET_KEY` | for `send_transfer` | — |+| `MAX_SOL_PER_TX` | no | `0.5` |+| `RECIPIENT_ALLOWLIST` | no | — (any valid pubkey allowed) |+| `REQUIRE_CONFIRM` | no | `true` |++`THREE_WS_SESSION` is the value of the `__Host-sid` cookie from a signed-in three.ws browser session. Treat it — and `SOLANA_SECRET_KEY` — like a password.++## 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/portfolio-mcp/package.json b/packages/portfolio-mcp/package.jsonnew file mode 100644index 000000000..996515fb7--- /dev/null+++ b/packages/portfolio-mcp/package.json@@ -0,0 +1,62 @@+{+ "name": "@three-ws/portfolio-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/portfolio-mcp",+ "description": "An AI agent's own trading state over MCP — portfolio summary, value history, live wallet balances, the public closed-trade PnL feed, and one real write: a signed on-chain Solana transfer. 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/portfolio-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "portfolio",+ "pnl",+ "trades",+ "wallet",+ "balances",+ "solana",+ "transfer",+ "ai-agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "portfolio-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",+ "@solana/spl-token": "^0.4.14",+ "@solana/web3.js": "^1.98.4",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ }+}diff --git a/packages/portfolio-mcp/server.json b/packages/portfolio-mcp/server.jsonnew file mode 100644index 000000000..87b9c862d--- /dev/null+++ b/packages/portfolio-mcp/server.json@@ -0,0 +1,90 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/portfolio-mcp",+ "title": "three.ws Portfolio",+ "description": "An agent's own trading state — portfolio value, PnL, live balances, the trade feed, and signed Solana transfers.",+ "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/portfolio-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/portfolio-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 portfolio + trades 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 for the account-scoped reads — get_portfolio_summary, get_portfolio_history, get_portfolio_asset — which return data for the agents YOU own. The public trade feed and on-chain balance reads do not need it. Treat like a password.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "SOLANA_RPC_URL",+ "description": "Solana mainnet RPC endpoint used by get_wallet_balances and send_transfer. Defaults to https://api.mainnet-beta.solana.com — bring your own (Helius / QuickNode / Triton) for production traffic.",+ "format": "string",+ "isRequired": false,+ "default": "https://api.mainnet-beta.solana.com"+ },+ {+ "name": "SOLANA_SECRET_KEY",+ "description": "Base58-encoded Solana secret key for the wallet that send_transfer signs from. REQUIRED for send_transfer (the only write tool); a per-call `secret` arg overrides it. Not needed for any read tool. Treat like cash.",+ "format": "string",+ "isRequired": true,+ "isSecret": true+ },+ {+ "name": "MAX_SOL_PER_TX",+ "description": "Per-transaction spend cap in SOL for native SOL transfers via send_transfer. Bounds the blast radius of a leaked key or an injected argument.",+ "format": "number",+ "isRequired": false,+ "default": "0.5"+ },+ {+ "name": "RECIPIENT_ALLOWLIST",+ "description": "Optional comma-separated base58 pubkeys. When set, send_transfer refuses any recipient not in the list.",+ "format": "string",+ "isRequired": false+ },+ {+ "name": "REQUIRE_CONFIRM",+ "description": "When on (default), send_transfer refuses until re-issued with confirm:true. Set 0/false to disable the gate.",+ "format": "boolean",+ "isRequired": false,+ "default": "true"+ }+ ]+ }+ ]+}diff --git a/packages/portfolio-mcp/src/config.js b/packages/portfolio-mcp/src/config.jsnew file mode 100644index 000000000..ad4767da8--- /dev/null+++ b/packages/portfolio-mcp/src/config.js@@ -0,0 +1,71 @@+// Centralized env + HTTP base for the portfolio MCP.+//+// This server has two surfaces:+// • HTTP reads against the live three.ws API (THREE_WS_BASE) — the public+// trade feed and the account-scoped portfolio analytics.+// • Direct Solana RPC (SOLANA_RPC_URL) for live on-chain balance reads and the+// one write tool, send_transfer, which signs locally with SOLANA_SECRET_KEY.+//+// Account-scoped reads (summary/history/asset) operate on the agents YOU own, so+// they authenticate with your three.ws session token (THREE_WS_SESSION) — the+// same `__Host-sid` cookie a signed-in browser carries. We never hold a baked-in+// key: signing requires SOLANA_SECRET_KEY (or a per-call secret) that you supply.++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 (balance fan-outs, snapshot+// history) — 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;+})();++// Session token for the account-scoped portfolio reads. 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 return only the agents they own. Empty for the+// public surfaces (trade feed, on-chain balance reads).+export const THREE_WS_SESSION = env('THREE_WS_SESSION', '');++// Solana RPC used by get_wallet_balances and send_transfer. We sign and broadcast+// real mainnet transactions over this URL, so reject a plaintext-http endpoint+// outside of localhost — it's a credential/MITM risk.+function validateRpcUrl(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch {+ throw Object.assign(new Error(`SOLANA_RPC_URL is not a valid URL: "${raw}"`), { code: 'bad_rpc_url' });+ }+ if (u.protocol === 'https:') return raw;+ const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(u.hostname);+ if (u.protocol === 'http:' && isLocal) return raw;+ throw Object.assign(+ new Error(+ `SOLANA_RPC_URL must be https (got "${u.protocol}//${u.hostname}"). ` ++ 'Only http://localhost is allowed for local dev validators.',+ ),+ { code: 'insecure_rpc_url' },+ );+}++export const SOLANA_RPC_URL = validateRpcUrl(env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com'));++// Default signer for send_transfer. The per-call `secret` arg overrides this.+export const SOLANA_DEFAULT_SECRET = env('SOLANA_SECRET_KEY', '');++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/portfolio-mcp';diff --git a/packages/portfolio-mcp/src/index.js b/packages/portfolio-mcp/src/index.jsnew file mode 100644index 000000000..09e13c072--- /dev/null+++ b/packages/portfolio-mcp/src/index.js@@ -0,0 +1,128 @@+#!/usr/bin/env node+// @three-ws/portfolio-mcp — MCP server entry point.+//+// Gives an AI agent programmatic access to its OWN trading state over stdio:+// • get_portfolio_summary — live holdings + USD value across the agents you own+// • get_portfolio_history — your portfolio value over time (snapshots)+// • get_portfolio_asset — one token: holdings + live market data + price chart+// • get_trades_feed — the public closed-trade feed (realized PnL)+// • get_wallet_balances — live on-chain SOL + SPL balances for any wallet+// • send_transfer — sign + broadcast a real SOL/SPL transfer (WRITE)+//+// Reads hit the live three.ws API (THREE_WS_BASE) and Solana RPC (SOLANA_RPC_URL).+// The account-scoped reads use your three.ws session (THREE_WS_SESSION). The one+// write, send_transfer, signs locally with SOLANA_SECRET_KEY and moves real funds.+//+// Run standalone:+// node packages/portfolio-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 getPortfolioSummary } from './tools/portfolio-summary.js';+import { def as getPortfolioHistory } from './tools/portfolio-history.js';+import { def as getPortfolioAsset } from './tools/portfolio-asset.js';+import { def as getTradesFeed } from './tools/trades-feed.js';+import { def as getWalletBalances } from './tools/wallet-balances.js';+import { def as sendTransfer } from './tools/send-transfer.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 = [+ getPortfolioSummary,+ getPortfolioHistory,+ getPortfolioAsset,+ getTradesFeed,+ getWalletBalances,+ sendTransfer,+];++/**+ * 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: 'portfolio-mcp', title: 'three.ws Portfolio', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Portfolio MCP — an agent’s own trading state. get_portfolio_summary gives live holdings ' ++ 'and USD value across the agent wallets you own; get_portfolio_history charts that value over time; ' ++ 'get_portfolio_asset deep-dives one token with your holdings plus live market data and a price ' ++ 'chart. get_trades_feed is the public feed of closed positions and their REALIZED PnL across all ' ++ 'agents. get_wallet_balances reads live on-chain SOL + SPL balances for any Solana address straight ' ++ 'from the RPC. send_transfer is the ONLY write: it signs locally and broadcasts a real, irreversible ' ++ 'Solana transfer of SOL or any SPL token — it requires confirm:true and is bounded by MAX_SOL_PER_TX ' ++ 'and an optional recipient allowlist. The account-scoped reads need THREE_WS_SESSION; the trade feed ' ++ 'and on-chain balance reads are public; send_transfer needs SOLANA_SECRET_KEY (or a per-call secret).',+ },+ );++ 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(`[portfolio-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('[portfolio-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/portfolio-mcp/src/lib/api.js b/packages/portfolio-mcp/src/lib/api.jsnew file mode 100644index 000000000..17bee95fe--- /dev/null+++ b/packages/portfolio-mcp/src/lib/api.js@@ -0,0 +1,83 @@+// 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.+//+// Account-scoped reads pass `auth: true`. Those endpoints resolve the caller+// from the three.ws session cookie, so we attach THREE_WS_SESSION as the+// `__Host-sid` cookie and fail fast with a clear message when it is absent —+// there is no second HTTP client, the auth lives here.++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT, THREE_WS_SESSION } from '../config.js';++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/portfolio/summary`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown, auth?: boolean }} [opts]+ * `auth: true` attaches the session cookie and requires THREE_WS_SESSION to be set.+ * @returns {Promise<any>} Parsed JSON response.+ * @throws {Error} with `.code` ('no_session' | '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 },+ );+ }++ 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}` } : {}),+ ...(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/portfolio-mcp/src/lib/solana.js b/packages/portfolio-mcp/src/lib/solana.jsnew file mode 100644index 000000000..ca8a9305a--- /dev/null+++ b/packages/portfolio-mcp/src/lib/solana.js@@ -0,0 +1,281 @@+// Solana primitives: keypair load, live balance reads, and signed transfers.+//+// send_transfer signs LOCALLY with the agent's own key (SOLANA_SECRET_KEY, or a+// per-call `secret`). We never embed a default key. This mirrors the on-chain+// transfer the three.ws /api/portfolio/send route performs server-side, but here+// the agent holds its own signer instead of a custodial one.++import {+ Connection,+ Keypair,+ PublicKey,+ SystemProgram,+ Transaction,+ ComputeBudgetProgram,+ LAMPORTS_PER_SOL,+} from '@solana/web3.js';+import {+ TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,+ getMint,+ getAssociatedTokenAddress,+ getAccount,+ createAssociatedTokenAccountInstruction,+ createTransferCheckedInstruction,+} from '@solana/spl-token';+import bs58 from 'bs58';++import { SOLANA_RPC_URL, SOLANA_DEFAULT_SECRET } from '../config.js';+import { assertSolWithinCap, clampPriorityMicroLamports } from './spend-policy.js';++const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;++let _conn = null;+export function getConnection() {+ if (!_conn) _conn = new Connection(SOLANA_RPC_URL, 'confirmed');+ return _conn;+}++export function isValidPubkey(s) {+ try {+ new PublicKey(s);+ return true;+ } catch {+ return false;+ }+}++export function keypairFromSecret(secret) {+ const trimmed = String(secret || '').trim();+ if (!trimmed) {+ throw Object.assign(+ new Error(+ 'Solana secret required. Pass `secret` (base58) in the tool call, or set SOLANA_SECRET_KEY ' ++ 'in the MCP server environment.',+ ),+ { code: 'no_signer' },+ );+ }+ const bytes = bs58decode(trimmed);+ if (bytes.length !== 64) {+ throw Object.assign(new Error(`Solana secret must decode to 64 bytes (got ${bytes.length})`), {+ code: 'invalid_secret',+ });+ }+ return Keypair.fromSecretKey(bytes);+}++export function loadSigner(secret) {+ return keypairFromSecret(secret || SOLANA_DEFAULT_SECRET);+}++// Live native SOL balance for any pubkey.+export async function getBalanceSol(pubkeyStr) {+ const conn = getConnection();+ const lamports = await conn.getBalance(new PublicKey(pubkeyStr), 'confirmed');+ return { lamports, sol: lamports / LAMPORTS_PER_SOL };+}++// Live SPL token balances (classic SPL + Token-2022) for any pubkey. Only+// non-zero positions are returned.+export async function getTokenBalances(pubkeyStr) {+ const conn = getConnection();+ const owner = new PublicKey(pubkeyStr);+ const [legacy, t22] = await Promise.all([+ conn.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID }),+ conn.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_2022_PROGRAM_ID }),+ ]);+ const all = [...legacy.value, ...t22.value];+ return all+ .map((r) => {+ const info = r.account.data?.parsed?.info;+ if (!info) return null;+ const amount = info.tokenAmount;+ const isT22 = r.account.owner?.equals?.(TOKEN_2022_PROGRAM_ID) ?? false;+ return {+ mint: info.mint,+ account: r.pubkey.toBase58(),+ amount: amount?.amount,+ ui_amount: amount?.uiAmount,+ ui_amount_string: amount?.uiAmountString,+ decimals: amount?.decimals,+ program: isT22 ? 'token-2022' : 'spl-token',+ };+ })+ .filter(Boolean)+ .filter((t) => Number(t.ui_amount) > 0);+}++// Convert a human decimal amount string into base units without float rounding.+function parseAmountToBaseUnits(amountStr, decimals) {+ const [whole, frac = ''] = String(amountStr).split('.');+ const fracPadded = (frac + '0'.repeat(decimals)).slice(0, decimals);+ const combined = (whole + fracPadded).replace(/^0+/, '') || '0';+ return BigInt(combined);+}++// Which token program owns a mint — classic SPL or Token-2022. Token-2022 mints+// need their own program id on the transfer/ATA instructions.+async function resolveTokenProgram(conn, mintPk) {+ const info = await conn.getAccountInfo(mintPk);+ if (!info) {+ throw Object.assign(new Error(`mint ${mintPk.toBase58()} not found on-chain`), { code: 'mint_not_found' });+ }+ if (info.owner.equals(TOKEN_2022_PROGRAM_ID)) return TOKEN_2022_PROGRAM_ID;+ return TOKEN_PROGRAM_ID;+}++/**+ * Build, sign, and broadcast a transfer from the loaded signer.+ *+ * @param {{ secret?: string, to: string, amount: string, mint?: string|null,+ * priorityMicroLamports?: number }} opts+ * `mint` omitted / 'native' → SOL transfer (capped by MAX_SOL_PER_TX).+ * `mint` = base58 SPL mint → SPL transfer (runtime-supplied; never hardcoded).+ * @returns {Promise<object>} signature + confirmation status + explorer link.+ */+export async function sendTransfer({ secret, to, amount, mint, priorityMicroLamports = 100000 }) {+ if (!isValidPubkey(to)) {+ throw Object.assign(new Error(`Destination is not a valid Solana pubkey: ${to}`), {+ code: 'invalid_destination',+ });+ }+ const isNative = !mint || mint === 'native';+ if (!isNative && !isValidPubkey(mint)) {+ throw Object.assign(new Error(`mint must be a base58 SPL mint or "native" (got ${mint})`), {+ code: 'invalid_mint',+ });+ }++ const signer = loadSigner(secret);+ const conn = getConnection();+ const recipientPk = new PublicKey(to);+ const microLamports = clampPriorityMicroLamports(priorityMicroLamports);++ const tx = new Transaction();+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports }));++ let decimals;+ let baseUnits;++ if (isNative) {+ const sol = Number(amount);+ assertSolWithinCap(sol, 'send_transfer (SOL)');+ const lamports = BigInt(Math.round(sol * LAMPORTS_PER_SOL));+ if (lamports <= 0n) {+ throw Object.assign(new Error(`amount must be a positive number of SOL (got ${amount})`), {+ code: 'invalid_amount',+ });+ }+ decimals = 9;+ baseUnits = lamports;+ tx.add(+ SystemProgram.transfer({+ fromPubkey: signer.publicKey,+ toPubkey: recipientPk,+ lamports,+ }),+ );+ } else {+ const mintPk = new PublicKey(mint);+ const programId = await resolveTokenProgram(conn, mintPk);+ const mintInfo = await getMint(conn, mintPk, 'confirmed', programId);+ decimals = mintInfo.decimals;+ baseUnits = parseAmountToBaseUnits(amount, decimals);+ if (baseUnits <= 0n) {+ throw Object.assign(new Error(`amount must be a positive token amount (got ${amount})`), {+ code: 'invalid_amount',+ });+ }++ const senderAta = await getAssociatedTokenAddress(mintPk, signer.publicKey, false, programId);+ const recipientAta = await getAssociatedTokenAddress(mintPk, recipientPk, false, programId);++ // Sender must already hold the token. A missing/empty sender ATA is a clear+ // "you don't hold this" error, not a silent failed broadcast.+ try {+ const senderAcct = await getAccount(conn, senderAta, 'confirmed', programId);+ if (senderAcct.amount < baseUnits) {+ throw Object.assign(+ new Error(+ `insufficient token balance: have ${senderAcct.amount}, need ${baseUnits} base units of ${mint}`,+ ),+ { code: 'insufficient_balance' },+ );+ }+ } catch (e) {+ if (e.code === 'insufficient_balance') throw e;+ throw Object.assign(new Error(`signer holds no ${mint} (no token account)`), {+ code: 'insufficient_balance',+ });+ }++ // Create the recipient's ATA if it doesn't exist yet (payer = signer).+ const recipientAcct = await conn.getAccountInfo(recipientAta);+ if (!recipientAcct) {+ tx.add(+ createAssociatedTokenAccountInstruction(+ signer.publicKey,+ recipientAta,+ recipientPk,+ mintPk,+ programId,+ ),+ );+ }+ tx.add(+ createTransferCheckedInstruction(+ senderAta,+ mintPk,+ recipientAta,+ signer.publicKey,+ baseUnits,+ decimals,+ [],+ programId,+ ),+ );+ }++ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = signer.publicKey;+ tx.recentBlockhash = blockhash;+ tx.sign(signer);++ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 5 });++ // Confirmation can throw (block-height-exceeded) even though the tx may still+ // land. Distinguish "confirmed failure" from "unknown" so the caller does NOT+ // blindly retry and risk a double-spend.+ let conf;+ try {+ conf = await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ } catch (waitErr) {+ throw Object.assign(+ new Error(+ `Transaction ${sig} was submitted but confirmation timed out (${waitErr?.message || waitErr}). ` ++ 'It MAY still land — check the signature on Solscan before resending to avoid a double-spend.',+ ),+ { code: 'tx_unconfirmed', status: 'pending', signature: sig },+ );+ }+ if (conf?.value?.err) {+ throw Object.assign(new Error(`Transaction failed: ${JSON.stringify(conf.value.err)}`), {+ code: 'tx_failed',+ status: 'failed',+ signature: sig,+ });+ }++ return {+ status: 'confirmed',+ signature: sig,+ from: signer.publicKey.toBase58(),+ to,+ asset: isNative ? 'SOL' : mint,+ amount: String(amount),+ decimals,+ base_units: baseUnits.toString(),+ explorer: `https://solscan.io/tx/${sig}`,+ };+}diff --git a/packages/portfolio-mcp/src/lib/spend-policy.js b/packages/portfolio-mcp/src/lib/spend-policy.jsnew file mode 100644index 000000000..2969f01e1--- /dev/null+++ b/packages/portfolio-mcp/src/lib/spend-policy.js@@ -0,0 +1,133 @@+// Spend policy: hard guardrails around send_transfer, the one value-moving tool.+//+// Caps are read once from the env at module load. The native-SOL cap is enforced+// in the signing lib so the limit can't be bypassed; the recipient allowlist and+// the explicit confirm:true requirement are enforced in the tool handler.+//+// Limits are conservative by default. An operator who wants larger spends sets+// the env var explicitly and thereby accepts the risk.++import { LAMPORTS_PER_SOL } from '@solana/web3.js';++function envRaw(key) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : undefined;+}++function envNumber(key, fallback) {+ const raw = envRaw(key);+ if (raw === undefined) return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) {+ throw Object.assign(new Error(`${key} must be a non-negative number (got "${raw}")`), {+ code: 'bad_policy_config',+ });+ }+ return n;+}++function envBool(key, fallback) {+ const raw = envRaw(key);+ if (raw === undefined) return fallback;+ return !['0', 'false', 'no', 'off'].includes(raw.toLowerCase());+}++// Max SOL that a single native transfer may move. Default 0.5 SOL — generous for+// testing, low enough to bound a leaked-key or prompt-injection blast radius.+export const MAX_SOL_PER_TX = envNumber('MAX_SOL_PER_TX', 0.5);++// Optional recipient allowlist. Comma-separated base58 pubkeys. When set, every+// send_transfer destination must be in the list.+export const RECIPIENT_ALLOWLIST = (() => {+ const raw = envRaw('RECIPIENT_ALLOWLIST');+ if (!raw) return null; // null = no allowlist configured (allow any valid pubkey)+ const set = new Set(+ raw+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean),+ );+ return set.size ? set : null;+})();++// send_transfer requires an explicit confirm:true unless the operator opts out.+export const REQUIRE_CONFIRM = envBool('REQUIRE_CONFIRM', true);++// Sane ceiling on the compute-unit price (micro-lamports).+export const MAX_PRIORITY_MICRO_LAMPORTS = envNumber('MAX_PRIORITY_MICRO_LAMPORTS', 50_000_000);++/**+ * Assert a SOL amount is within MAX_SOL_PER_TX. Throws `over_spend_cap` with a+ * clear message otherwise. Called inside the signing lib so every native send is+ * covered. Token (SPL) transfers don't pass through this — their amount is+ * denominated in an arbitrary token, not SOL — but they still face the confirm+ * gate and the recipient allowlist.+ * @param {number} sol+ * @param {string} [label]+ */+export function assertSolWithinCap(sol, label = 'transfer') {+ const n = Number(sol);+ if (!Number.isFinite(n) || n < 0) {+ throw Object.assign(new Error(`${label}: amount must be a non-negative number (got ${sol})`), {+ code: 'invalid_amount',+ });+ }+ if (n > MAX_SOL_PER_TX) {+ throw Object.assign(+ new Error(+ `${label}: ${n} SOL exceeds the per-tx spend cap of ${MAX_SOL_PER_TX} SOL. ` ++ 'Raise MAX_SOL_PER_TX in the MCP server environment to allow larger spends.',+ ),+ { code: 'over_spend_cap' },+ );+ }+ return n;+}++/**+ * Enforce the recipient allowlist (if configured). Throws `recipient_not_allowed`.+ * @param {string} pubkey — destination base58+ * @param {string} [label]+ */+export function assertRecipientAllowed(pubkey, label = 'destination') {+ if (!RECIPIENT_ALLOWLIST) return; // no allowlist → any valid pubkey is fine+ if (!RECIPIENT_ALLOWLIST.has(String(pubkey))) {+ throw Object.assign(+ new Error(+ `${label} ${pubkey} is not in RECIPIENT_ALLOWLIST. ` ++ 'Add it to the allowlist env var to permit transfers to this address.',+ ),+ { code: 'recipient_not_allowed' },+ );+ }+}++/**+ * Gate the transfer on an explicit confirm flag. Returns a refusal object (for+ * the handler to return directly) when confirmation is required but absent;+ * returns null when the action may proceed.+ * @param {boolean|undefined} confirm+ * @param {string} action — human-readable name of the irreversible action+ */+export function confirmationGate(confirm, action) {+ if (!REQUIRE_CONFIRM) return null;+ if (confirm === true) return null;+ return {+ ok: false,+ error: 'confirmation_required',+ message:+ `${action} is IRREVERSIBLE and broadcasts a real transaction on Solana mainnet. ` ++ 'Re-issue the call with `confirm: true` to proceed. ' ++ '(Set REQUIRE_CONFIRM=0 on the MCP server to disable this prompt.)',+ };+}++/**+ * Clamp a compute-unit price to MAX_PRIORITY_MICRO_LAMPORTS.+ * @param {number} micros+ */+export function clampPriorityMicroLamports(micros) {+ const n = Math.floor(Number(micros));+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.min(n, MAX_PRIORITY_MICRO_LAMPORTS);+}diff --git a/packages/portfolio-mcp/src/tools/portfolio-asset.js b/packages/portfolio-mcp/src/tools/portfolio-asset.jsnew file mode 100644index 000000000..2bc754a16--- /dev/null+++ b/packages/portfolio-mcp/src/tools/portfolio-asset.js@@ -0,0 +1,56 @@+// `get_portfolio_asset` — a single token's combined position across all of your+// agent wallets, plus live market data and a price chart. Account-scoped. Read-only.+//+// Wraps GET /api/portfolio/asset?chain&id&days. Combines your holdings of one+// asset with CoinGecko market data + a price-history chart for that asset.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_portfolio_asset',+ title: 'My position in one token (holdings + market + chart)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Deep-dive on ONE asset across every agent wallet you own. Returns which wallets hold it, your ' ++ '`total_amount` and `total_usd`, the per-wallet `holdings`, the live `market` data (price, 24h/7d/30d ' ++ 'change, market cap, volume, ATH) and a `chart` of price history over `days`. Use `id:"native"` for the ' ++ 'chain’s base coin (SOL on solana, ETH on evm), otherwise the base58 SPL mint or the 0x contract address. ' ++ 'Requires THREE_WS_SESSION. Read-only.',+ inputSchema: {+ chain: z.enum(['solana', 'evm']).describe('Which chain the asset lives on.'),+ id: z+ .string()+ .min(1)+ .describe('"native" for the base coin (SOL/ETH), otherwise the base58 SPL mint or 0x ERC-20 contract.'),+ days: z+ .number()+ .int()+ .min(1)+ .max(365)+ .default(30)+ .describe('Days of price history for the chart, 1–365 (default 30).'),+ },+ async handler(args) {+ const data = await apiRequest('/api/portfolio/asset', {+ auth: true,+ query: { chain: args?.chain, id: args?.id, days: args?.days ?? 30 },+ });+ return {+ ok: true,+ chain: data?.chain ?? args?.chain,+ id: data?.id ?? args?.id,+ is_native: data?.is_native ?? false,+ symbol: data?.symbol ?? null,+ logo: data?.logo ?? null,+ decimals: data?.decimals ?? null,+ unit_price_usd: data?.unit_price_usd ?? 0,+ total_amount: data?.total_amount ?? 0,+ total_usd: data?.total_usd ?? 0,+ holdings: Array.isArray(data?.holdings) ? data.holdings : [],+ market: data?.market ?? null,+ chart: data?.chart ?? { days: args?.days ?? 30, points: [] },+ };+ },+};diff --git a/packages/portfolio-mcp/src/tools/portfolio-history.js b/packages/portfolio-mcp/src/tools/portfolio-history.jsnew file mode 100644index 000000000..41b8fe6d0--- /dev/null+++ b/packages/portfolio-mcp/src/tools/portfolio-history.js@@ -0,0 +1,43 @@+// `get_portfolio_history` — the time series of total portfolio USD value from+// stored snapshots. Account-scoped (session). Read-only.+//+// Wraps GET /api/portfolio/history?days=. Each point is a snapshot persisted by+// a prior get_portfolio_summary(snapshot:true) (or the website's auto-capture).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_portfolio_history',+ title: 'My portfolio value over time',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Time series of your total portfolio USD value, oldest point first, for charting performance over time. ' ++ 'Returns `points` as { t (ISO timestamp), usd } pairs, drawn from snapshots persisted by ' ++ 'get_portfolio_summary(snapshot:true) or the website. An empty `points` array means no snapshots have been ' ++ 'captured yet in the window — take one with get_portfolio_summary(snapshot:true) to start the series. ' ++ 'Requires THREE_WS_SESSION. Read-only.',+ inputSchema: {+ days: z+ .number()+ .int()+ .min(1)+ .max(365)+ .default(90)+ .describe('How many days of history to return, 1–365 (default 90).'),+ },+ async handler(args) {+ const data = await apiRequest('/api/portfolio/history', {+ auth: true,+ query: { days: args?.days ?? 90 },+ });+ const points = Array.isArray(data?.points) ? data.points : [];+ return {+ ok: true,+ days: data?.days ?? args?.days ?? 90,+ point_count: points.length,+ points,+ };+ },+};diff --git a/packages/portfolio-mcp/src/tools/portfolio-summary.js b/packages/portfolio-mcp/src/tools/portfolio-summary.jsnew file mode 100644index 000000000..5d87cb6da--- /dev/null+++ b/packages/portfolio-mcp/src/tools/portfolio-summary.js@@ -0,0 +1,46 @@+// `get_portfolio_summary` — live aggregated holdings + USD value across all of+// the agent wallets YOU own. Account-scoped (session). Read-only.+//+// Wraps GET /api/portfolio/summary. The route resolves the caller from the+// three.ws session, walks every agent identity they own (EVM + Solana), and+// returns live balances priced in USD per wallet plus a grand total. Pass+// `snapshot:true` to also persist a point-in-time snapshot that feeds+// get_portfolio_history.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_portfolio_summary',+ title: 'My agents’ live portfolio (holdings + USD value)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Live aggregated portfolio for the agent wallets YOU own (resolved from your three.ws session). Returns ' ++ '`total_usd` across all wallets and a per-wallet breakdown — each with agent_id, agent_name, chain ' ++ '(solana | evm), address, the resolved .sol name when present, the native balance (SOL/ETH amount + USD), ' ++ 'the SPL/ERC-20 token holdings (amount + USD), and that wallet’s USD subtotal. A wallet that failed to ' ++ 'price carries `ok:false` and an `error` instead of throwing the whole call. Note: this is the live VALUE ' ++ 'snapshot — realized PnL lives in get_trades_feed. Set `snapshot:true` to persist a point for the history ' ++ 'chart. Requires THREE_WS_SESSION. Read-only.',+ inputSchema: {+ snapshot: z+ .boolean()+ .default(false)+ .describe('When true, also persist this total as a portfolio snapshot (feeds get_portfolio_history). Default false.'),+ },+ async handler(args) {+ const data = await apiRequest('/api/portfolio/summary', {+ auth: true,+ query: args?.snapshot ? { snapshot: '1' } : undefined,+ });+ const wallets = Array.isArray(data?.wallets) ? data.wallets : [];+ return {+ ok: true,+ captured_at: data?.captured_at ?? null,+ total_usd: data?.total_usd ?? 0,+ wallet_count: wallets.length,+ wallets,+ };+ },+};diff --git a/packages/portfolio-mcp/src/tools/send-transfer.js b/packages/portfolio-mcp/src/tools/send-transfer.jsnew file mode 100644index 000000000..9a78ca913--- /dev/null+++ b/packages/portfolio-mcp/src/tools/send-transfer.js@@ -0,0 +1,76 @@+// `send_transfer` — sign and broadcast a real Solana transfer (SOL or any SPL+// token) from the agent's own wallet. THE ONLY WRITE TOOL. Funds-moving,+// irreversible.+//+// Signs LOCALLY with SOLANA_SECRET_KEY (or a per-call `secret`). The mint is+// runtime input — pass `$THREE` or any SPL mint you hold; nothing is hardcoded.++import { z } from 'zod';++import { sendTransfer } from '../lib/solana.js';+import { assertRecipientAllowed, confirmationGate } from '../lib/spend-policy.js';++export const def = {+ name: 'send_transfer',+ title: 'Send SOL or an SPL token on Solana mainnet',+ // MCP ToolAnnotations — EXECUTION: broadcasts a real, irreversible Solana+ // mainnet transaction that moves funds out of the signing wallet.+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'BROADCASTS A REAL, IRREVERSIBLE SOLANA MAINNET TRANSACTION that moves funds out of the agent’s own wallet. ' ++ 'Sends native SOL (omit `mint`, or set mint:"native") or any SPL token (pass its base58 `mint` — supplied ' ++ 'at call time, e.g. the $THREE mint or any token you hold). Signs locally with the per-call `secret` ' ++ '(base58) or SOLANA_SECRET_KEY on the server; for a token it auto-creates the recipient’s associated token ' ++ 'account when missing. Returns the confirmed signature, the moved amount, and a Solscan link. EXECUTION ' ++ 'ACTION — pass confirm:true to proceed. Native sends are capped by MAX_SOL_PER_TX; the recipient must be ' ++ 'in RECIPIENT_ALLOWLIST when one is configured.',+ inputSchema: {+ recipient: z.string().min(32).max(44).describe('Destination Solana pubkey (base58).'),+ amount: z+ .string()+ .regex(/^(\d+(\.\d*)?|\.\d+)$/, 'amount must be a positive decimal string, e.g. "1.5"')+ .describe('Amount to send, in human units as a decimal string (e.g. "1.5" SOL or "100" tokens).'),+ mint: z+ .string()+ .optional()+ .describe('SPL token mint (base58) to send. Omit or set "native" to send SOL. Runtime input — any mint you hold.'),+ secret: z+ .string()+ .optional()+ .describe('Base58 secret of the sending wallet. Falls back to SOLANA_SECRET_KEY on the server.'),+ priorityMicroLamports: z+ .number()+ .int()+ .min(0)+ .max(50_000_000)+ .optional()+ .describe('Compute-unit price in micro-lamports (default 100000).'),+ confirm: z+ .boolean()+ .optional()+ .describe('Must be true to execute this irreversible transfer (when REQUIRE_CONFIRM is on).'),+ },+ async handler(args) {+ const gate = confirmationGate(args?.confirm, 'send_transfer');+ if (gate) return gate;+ try {+ assertRecipientAllowed(args.recipient, 'send_transfer recipient');+ const out = await sendTransfer({+ secret: args.secret,+ to: args.recipient,+ amount: args.amount,+ mint: args.mint,+ priorityMicroLamports: args.priorityMicroLamports,+ });+ return { ok: true, ...out };+ } catch (err) {+ return {+ ok: false,+ error: err.code || 'transfer_failed',+ message: err.message,+ signature: err.signature || null,+ ...(err.status ? { status: err.status } : {}),+ };+ }+ },+};diff --git a/packages/portfolio-mcp/src/tools/trades-feed.js b/packages/portfolio-mcp/src/tools/trades-feed.jsnew file mode 100644index 000000000..80c2b668b--- /dev/null+++ b/packages/portfolio-mcp/src/tools/trades-feed.js@@ -0,0 +1,66 @@+// `get_trades_feed` — the public feed of notable closed positions, with realized+// PnL. Read-only, no auth.+//+// Wraps GET /api/trades/feed. This is the platform-wide feed of profitable exits+// across all agents — the canonical source of *realized* PnL on three.ws.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_trades_feed',+ title: 'Public closed-trade PnL feed',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'The public feed of notable CLOSED positions across all three.ws agents, newest exit first — the canonical ' ++ 'source of realized PnL on the platform. Each item carries the coin (mint, symbol, name), the trader ' ++ '(agent_id, agent_name, copier_count), entry_sol / exit_sol / realized_pnl_sol / realized_pnl_pct / multiple, ' ++ 'hold_seconds, exit_reason, the buy/sell signatures, and oracle conviction context when the coin was scored. ' ++ 'Filter by `mint` to see every closed trade on one coin (the time window is ignored when a mint is set). ' ++ 'Paginate with `cursor` = the previous response\'s `next_cursor`. No auth required — read-only live data.',+ inputSchema: {+ network: z.enum(['mainnet', 'devnet']).default('mainnet').describe('Solana network (default mainnet).'),+ window: z+ .enum(['1h', '6h', '24h', '7d', '30d', 'all'])+ .default('24h')+ .describe('Time window for closed exits (default 24h). Ignored when `mint` is set.'),+ min_pnl_pct: z+ .number()+ .min(0)+ .default(10)+ .describe('Minimum realized profit %, to surface only meaningful wins (default 10).'),+ limit: z.number().int().min(1).max(80).default(40).describe('Max items to return, 1–80 (default 40).'),+ cursor: z+ .string()+ .optional()+ .describe('ISO timestamp for pagination — pass the previous response\'s `next_cursor`.'),+ mint: z+ .string()+ .optional()+ .describe('Filter to a single coin by base58 mint. When set, all closed trades on that coin are returned regardless of window.'),+ },+ async handler(args) {+ const data = await apiRequest('/api/trades/feed', {+ query: {+ network: args?.network === 'devnet' ? 'devnet' : 'mainnet',+ window: args?.window,+ min_pnl_pct: args?.min_pnl_pct,+ limit: args?.limit,+ cursor: args?.cursor,+ mint: args?.mint,+ },+ });+ return {+ ok: true,+ network: data?.network ?? 'mainnet',+ window: data?.window ?? '24h',+ min_pnl_pct: data?.min_pnl_pct ?? 10,+ mint: data?.mint ?? null,+ count: data?.count ?? (Array.isArray(data?.items) ? data.items.length : 0),+ items: Array.isArray(data?.items) ? data.items : [],+ next_cursor: data?.next_cursor ?? null,+ generated_at: data?.generated_at ?? null,+ };+ },+};diff --git a/packages/portfolio-mcp/src/tools/wallet-balances.js b/packages/portfolio-mcp/src/tools/wallet-balances.jsnew file mode 100644index 000000000..7629b3e2b--- /dev/null+++ b/packages/portfolio-mcp/src/tools/wallet-balances.js@@ -0,0 +1,53 @@+// `get_wallet_balances` — live on-chain SOL + SPL balances for any Solana pubkey,+// read straight from the RPC. Read-only, no session needed.+//+// Where get_portfolio_summary aggregates the wallets you own (priced in USD via+// the three.ws API), this reads ONE address directly from the chain — the raw,+// authoritative on-chain truth for the agent's own signing wallet, available+// without a session.++import { z } from 'zod';++import { getBalanceSol, getTokenBalances, isValidPubkey } from '../lib/solana.js';+import { SOLANA_RPC_URL } from '../config.js';++export const def = {+ name: 'get_wallet_balances',+ title: 'Live on-chain balances for a Solana wallet',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read live, on-chain balances for any Solana pubkey directly from the RPC: the native SOL balance plus ' ++ 'every non-zero SPL token position (classic SPL and Token-2022), each with mint, raw amount, ui_amount, ' ++ 'decimals, and which token program owns it. This is the raw on-chain truth (no USD pricing) — use it to ' ++ 'confirm the agent’s own signing wallet before a send_transfer, or to check any address. No session ' ++ 'required. Read-only.',+ inputSchema: {+ address: z.string().min(32).max(44).describe('Base58 Solana pubkey to read balances for.'),+ include_tokens: z+ .boolean()+ .default(true)+ .describe('Include SPL/Token-2022 positions (default true). Set false for just the SOL balance.'),+ },+ async handler(args) {+ const address = String(args?.address ?? '').trim();+ if (!isValidPubkey(address)) {+ return { ok: false, error: 'invalid_pubkey', message: `not a valid Solana pubkey: ${address}` };+ }+ const includeTokens = args?.include_tokens !== false;+ const [sol, tokens] = await Promise.all([+ getBalanceSol(address),+ includeTokens ? getTokenBalances(address) : Promise.resolve(null),+ ]);+ return {+ ok: true,+ address,+ sol: sol.sol,+ lamports: sol.lamports,+ token_count: tokens ? tokens.length : null,+ tokens,+ rpc: SOLANA_RPC_URL,+ explorer: `https://solscan.io/account/${address}`,+ fetched_at: new Date().toISOString(),+ };+ },+};diff --git a/packages/portfolio-mcp/test/registration.test.mjs b/packages/portfolio-mcp/test/registration.test.mjsnew file mode 100644index 000000000..8ea099568--- /dev/null+++ b/packages/portfolio-mcp/test/registration.test.mjs@@ -0,0 +1,93 @@+// Tool-surface invariants for @three-ws/portfolio-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,+// signer, or session. These tests run offline — they never touch the network or+// the chain.+//+// Run: node --test packages/portfolio-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_portfolio_summary',+ 'get_portfolio_history',+ 'get_portfolio_asset',+ 'get_trades_feed',+ 'get_wallet_balances',+ 'send_transfer',+];++// The ONLY write tool — it signs and broadcasts an irreversible Solana mainnet+// transfer. Adding another write? Add it here deliberately, same commit.+const WRITE_TOOLS = new Set(['send_transfer']);++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 6);+ assert.deepEqual(new Set(TOOLS.map((t) => t.name)), new Set(EXPECTED_NAMES));+ assert.equal(new Set(TOOLS.map((t) => t.name)).size, 6, '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('reads are read-only live queries; writes are not', () => {+ 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 a live service (API or chain); nothing is idempotent —+ // balances, feeds, and broadcasts 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('the write tool sets readOnlyHint:false and destructiveHint:true explicitly', () => {+ const destructive = TOOLS.filter((t) => t.annotations.destructiveHint === true).map((t) => t.name);+ assert.deepEqual(new Set(destructive), WRITE_TOOLS);+ for (const name of WRITE_TOOLS) {+ const tool = TOOLS.find((t) => t.name === name);+ assert.ok(tool, `${name} must exist in the tool registry`);+ assert.equal(tool.annotations.readOnlyHint, false, `${name} must not be read-only`);+ assert.equal(tool.annotations.destructiveHint, true, `${name} must be marked destructive`);+ assert.equal(tool.annotations.idempotentHint, false, `${name} must not be idempotent`);+ }+});++test('buildServer registers every tool with its annotations, without a signer or 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/provenance-mcp/LICENSE b/packages/provenance-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/provenance-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/provenance-mcp/README.md b/packages/provenance-mcp/README.mdnew file mode 100644index 000000000..264de3b9d--- /dev/null+++ b/packages/provenance-mcp/README.md@@ -0,0 +1,156 @@+<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/provenance-mcp</h1>++<p align="center"><strong>The agent action-provenance log over MCP — append-only, ERC-191-signed, on-chain-verifiable. Record what an agent did, and audit another agent's trail, from any AI assistant.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/provenance-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/provenance-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/provenance-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/provenance-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 three.ws **agent trust layer**. Every action an agent takes is written to an append-only ledger — optionally signed with the agent's EVM wallet (ERC-191), so its authorship is provable, not just claimed. This server lets one agent record its own actions and lets any agent read and **cryptographically verify** another agent's provenance trail.++Why it matters: a forked, purchased, or delegated agent is only trustworthy if its history is provable. `provenance-mcp` turns "the agent says it did X" into "the agent **signed** that it did X, and anyone can `ecrecover` the signer to confirm." The ledger is immutable — records are never edited or deleted.++## Install++```bash+npm install @three-ws/provenance-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/provenance-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add provenance --env THREE_WS_TOKEN=sk_live_… -- npx -y @three-ws/provenance-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "provenance": {+ "command": "npx",+ "args": ["-y", "@three-ws/provenance-mcp"],+ "env": {+ "THREE_WS_TOKEN": "sk_live_…",+ "THREE_WS_SIGNER_KEY": "0x…"+ }+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+THREE_WS_TOKEN=sk_live_… npx -y @modelcontextprotocol/inspector npx @three-ws/provenance-mcp+```++## Tools++| Tool | Type | What it does |+| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------- |+| `list_agent_actions` | read-only | Read an agent's action trail, newest-first, cursor-paginated. Each record is signature-checked inline. |+| `query_action` | read-only | Fetch one action by id and recover its signer — proof the named agent authored that exact action, untampered. |+| `append_agent_action` | **write** | ERC-191-sign a new action and append it to the immutable ledger. Never overwrites or deletes. |++`append_agent_action` is the only write tool. It **appends** to an append-only ledger: every call records a new, permanent record (so it is not idempotent — don't retry blindly), and nothing is ever overwritten or removed (so it is not destructive).++### Input parameters++**`list_agent_actions`** — `agent_id` (required), `limit` (1–200, default 50), `cursor` (numeric, from a previous `next_cursor`).++**`query_action`** — `agent_id` (required), `id` (required, numeric action id).++**`append_agent_action`** — `agent_id` (required), `type` (required, ≤64 chars), `payload` (object, optional), `source_skill` (optional), `signer_key` (optional 0x EVM key, overrides `THREE_WS_SIGNER_KEY` for this call).++## How signing & verification work++When you append an action with a signer key configured, the server:++1. Builds a **canonical** form of the action — `{ v, agentId, type, payload, sourceSkill }` with recursively sorted keys, so the same logical action always produces the same bytes.+2. SHA-256 digests it and frames the digest as `threews:action:v1:<digest>` (domain-separated, so an action signature can never be replayed as some other three.ws message).+3. ERC-191 `personal_sign`s that string with the agent's EVM key and sends the resulting `signature` + `signer_address` alongside the action.++`list_agent_actions` and `query_action` reverse this offline: they recompute the digest from the stored record and `ecrecover` the signer. A `verification.reason` of `ok` means the signature recovers to the claimed address — cryptographic proof of authorship and integrity. `signer_mismatch` means the record does not verify (tampering, or a foreign signing scheme) and must not be trusted; `unsigned` means no signature was attached.++This is the same primitive three.ws uses server-side for its Portable & Verifiable Brain — verification needs nothing but the public record and the agent's address.++## Example++```jsonc+// append_agent_action+> { "agent_id": "agent_42", "type": "launch", "payload": { "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "name": "$THREE" }, "source_skill": "pump-launch" }+{+ "ok": true,+ "action": {+ "id": "10482",+ "agent_id": "agent_42",+ "type": "launch",+ "payload": { "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "name": "$THREE" },+ "source_skill": "pump-launch",+ "signature": "0x…",+ "signer_address": "0xAbC…",+ "created_at": "2026-06-24T18:20:00.000Z"+ },+ "signing": { "signed": true, "signer_address": "0xAbC…", "digest": "…" }+}+```++```jsonc+// query_action → verify it independently+> { "agent_id": "agent_42", "id": "10482" }+{+ "ok": true,+ "action": { "id": "10482", "type": "launch", "signature": "0x…", "signer_address": "0xAbC…", /* … */ },+ "verification": { "signed": true, "valid": true, "reason": "ok", "recovered": "0xAbC…", "digest": "…" }+}+```++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).+- A `THREE_WS_TOKEN` — a three.ws API key (`sk_live_…`) or OAuth access token. The ledger authenticates every call and is **owner-scoped**: you can read and append actions only for agents your token owns.++### Environment variables++| Variable | Required | Default | Purpose |+| --------------------- | -------- | ------------------ | --------------------------------------------------------------------------------------------------- |+| `THREE_WS_TOKEN` | **yes** | — | Bearer token authenticating every call (API key or OAuth access token). Treat like a password. |+| `THREE_WS_SIGNER_KEY` | no | — | 0x EVM private key — when set, `append_agent_action` ERC-191-signs each action. Treat like cash. |+| `THREE_WS_BASE` | no | `https://three.ws` | API base URL — override for self-hosting or a preview deployment. |+| `THREE_WS_TIMEOUT_MS` | no | `20000` | Per-request timeout in milliseconds. |++## 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/provenance-mcp/package.json b/packages/provenance-mcp/package.jsonnew file mode 100644index 000000000..23d337ace--- /dev/null+++ b/packages/provenance-mcp/package.json@@ -0,0 +1,58 @@+{+ "name": "@three-ws/provenance-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/provenance-mcp",+ "description": "The three.ws agent action-provenance log over MCP — append-only, ERC-191-signed, on-chain-verifiable. Any AI agent can record what it did and audit another agent's provenance trail. Cursor-paginated reads + a signed append to an immutable ledger.",+ "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/provenance-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "provenance",+ "agent",+ "audit",+ "erc-191",+ "signature",+ "append-only",+ "trust"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "provenance-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",+ "ethers": "^6.16.0",+ "zod": "^3.23.8"+ }+}diff --git a/packages/provenance-mcp/server.json b/packages/provenance-mcp/server.jsonnew file mode 100644index 000000000..4c814441f--- /dev/null+++ b/packages/provenance-mcp/server.json@@ -0,0 +1,63 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/provenance-mcp",+ "title": "three.ws Provenance",+ "description": "The agent action-provenance log — append-only, ERC-191-signed, on-chain-verifiable. Record and audit what agents did.",+ "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/provenance-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/provenance-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 agent-actions ledger. 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 ledger reads/appends.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ },+ {+ "name": "THREE_WS_TOKEN",+ "description": "Bearer token authenticating every call — a three.ws API key (sk_live_…) or an OAuth access token. The ledger is owner-scoped: you can read and append actions only for agents your token owns. Required for all three tools. Treat like a password.",+ "format": "string",+ "isRequired": true,+ "isSecret": true+ },+ {+ "name": "THREE_WS_SIGNER_KEY",+ "description": "Optional 0x-prefixed EVM private key. When set, append_agent_action ERC-191-signs each action so anyone can ecrecover the signer and verify authorship on-chain. A per-call `signer_key` arg overrides it. Omit to append unsigned. Treat like cash.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ }+ ]+ }+ ]+}diff --git a/packages/provenance-mcp/src/config.js b/packages/provenance-mcp/src/config.jsnew file mode 100644index 000000000..f0e4ba694--- /dev/null+++ b/packages/provenance-mcp/src/config.js@@ -0,0 +1,49 @@+// Centralized env + HTTP base for the provenance MCP.+//+// This server wraps the three.ws agent action-provenance ledger+// (/api/agent-actions): an append-only, owner-scoped history of every action an+// agent took. The ledger authenticates every call, so a bearer token is+// required for all tools. The append tool can additionally ERC-191-sign each+// action with an EVM key, making authorship publicly verifiable on-chain.++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). The ledger reads are cursor-paginated index scans+// and the append is a single insert — fast, but 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;+})();++// Bearer token for the ledger. Every /api/agent-actions call — read and write —+// authenticates, and the ledger is owner-scoped (you only see agents your token+// owns). A three.ws API key (sk_live_…) or an OAuth access token. Read lazily at+// call time (not load time) so buildServer() stays env-free for tests.+export function authToken() {+ return env('THREE_WS_TOKEN', '');+}++// Optional default EVM signer for append_agent_action. When present, each+// appended action is ERC-191-signed so its authorship is publicly verifiable.+// A per-call `signer_key` arg overrides this. Read lazily for the same reason.+export function signerKey() {+ return env('THREE_WS_SIGNER_KEY') || env('THREE_WS_SIGNER') || '';+}++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/provenance-mcp';diff --git a/packages/provenance-mcp/src/index.js b/packages/provenance-mcp/src/index.jsnew file mode 100644index 000000000..d7acef672--- /dev/null+++ b/packages/provenance-mcp/src/index.js@@ -0,0 +1,122 @@+#!/usr/bin/env node+// @three-ws/provenance-mcp — MCP server entry point.+//+// Exposes the three.ws agent action-provenance ledger over stdio — the trust+// layer where every agent action is recorded append-only, ERC-191-signed, and+// on-chain verifiable:+// • list_agent_actions — read an agent's action trail (paginated, verified)+// • query_action — fetch one action by id and verify its signature+// • append_agent_action — sign + append a new action to the immutable ledger+//+// The ledger authenticates every call, so THREE_WS_TOKEN (a three.ws API key or+// OAuth access token) is required for all tools and the trail is owner-scoped.+// Set THREE_WS_SIGNER_KEY to ERC-191-sign appended actions.+//+// Run standalone:+// THREE_WS_TOKEN=sk_live_… node packages/provenance-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 listAgentActions } from './tools/list-agent-actions.js';+import { def as queryAction } from './tools/query-action.js';+import { def as appendAgentAction } from './tools/append-agent-action.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 = [+ listAgentActions,+ queryAction,+ appendAgentAction,+];++/**+ * 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: 'provenance-mcp', title: 'three.ws Provenance', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Provenance MCP — the agent trust layer. Every agent action lives in an ' ++ 'append-only, ERC-191-signed, on-chain-verifiable ledger. list_agent_actions reads an ' ++ "agent's action trail newest-first (cursor-paginated), verifying each record's signature " ++ 'inline. query_action fetches one action by id and recovers its signer to prove the named ' ++ 'agent authored that exact action, untampered. append_agent_action signs a new action with ' ++ 'an EVM key and appends it — an immutable record that can never be edited or deleted. The ' ++ 'ledger authenticates every call: set THREE_WS_TOKEN (a three.ws API key or OAuth access ' ++ 'token); the trail is owner-scoped to the agents that token owns. Set THREE_WS_SIGNER_KEY ' ++ 'to sign appended actions (otherwise they append unsigned). append_agent_action is the only ' ++ 'write tool; it never overwrites or deletes.',+ },+ );++ 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(`[provenance-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('[provenance-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/provenance-mcp/src/lib/api.js b/packages/provenance-mcp/src/lib/api.jsnew file mode 100644index 000000000..78ba7c44f--- /dev/null+++ b/packages/provenance-mcp/src/lib/api.js@@ -0,0 +1,75 @@+// Real HTTP access to the three.ws agent-actions ledger. No mocks, no fixtures —+// every call is a live request to THREE_WS_BASE. The ledger authenticates every+// request, so a Bearer token (THREE_WS_TOKEN) is attached automatically when+// present. 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, authToken } from '../config.js';++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * The Authorization header is added from THREE_WS_TOKEN when configured. The+ * ledger rejects unauthenticated calls (HTTP 401), so a missing token surfaces+ * as a normal upstream error the handler can explain.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/agent-actions`).+ * @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 token = authToken();++ 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,+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ ...(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/provenance-mcp/src/lib/signing.js b/packages/provenance-mcp/src/lib/signing.jsnew file mode 100644index 000000000..4a2aa0752--- /dev/null+++ b/packages/provenance-mcp/src/lib/signing.js@@ -0,0 +1,157 @@+// Signed provenance — the authorship + integrity layer for agent actions.+//+// Mirrors the three.ws server-side signing primitive (api/_lib/brain-sign.js):+// an action is canonicalized into stable bytes, SHA-256 digested, framed with a+// domain-separating version prefix, and ERC-191 `personal_sign`-signed by the+// agent's EVM wallet (the same secp256k1 key behind its ERC-8004 on-chain+// identity). Anyone holding the action record + the agent's address can+// `ecrecover` the signer and confirm the action was authored by that agent and+// has not been tampered with — provable provenance, not a database claim.+//+// These functions are pure crypto (no network, no DB): the same primitive a+// third party runs offline to verify another agent's trail. query_action calls+// verifyAction; append_agent_action calls signAction.++import { createHash } from 'node:crypto';++import { Wallet, verifyMessage, computeAddress } from 'ethers';++// Bump this prefix on any breaking change to the canonical form or message+// framing — old signatures stay verifiable against their own version string.+export const ACTION_SIG_VERSION = 'threews:action:v1';++/**+ * Deterministic, recursive JSON serialization with sorted object keys. Two+ * logically equal payloads always produce the same bytes regardless of key+ * insertion order — the precondition for a reproducible digest and signature.+ *+ * @param {unknown} value+ * @returns {string}+ */+export function stableStringify(value) {+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;+ const keys = Object.keys(value).sort();+ const body = keys+ .map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`)+ .join(',');+ return `{${body}}`;+}++/**+ * Stable serialization of the signable fields of an action. Only the authorship+ * content is covered — the server-generated id and created_at are excluded+ * because the signature is produced before the action is appended, and a+ * verifier recomputes this same form from the stored record. Accepts the+ * snake_case ledger row shape or a camelCase equivalent.+ *+ * @param {object} action+ * @returns {string} canonical JSON string+ */+export function canonicalizeAction(action) {+ const agentId = action.agent_id ?? action.agentId ?? '';+ const type = action.type ?? '';+ const payload = action.payload ?? {};+ const sourceSkill = action.source_skill ?? action.sourceSkill ?? null;++ return stableStringify({+ v: ACTION_SIG_VERSION,+ agentId: String(agentId),+ type: String(type),+ payload,+ sourceSkill: sourceSkill == null ? null : String(sourceSkill),+ });+}++/**+ * SHA-256 (hex) of the canonical action form — a fast tamper check that needs+ * no elliptic-curve math.+ *+ * @param {object} action+ * @returns {string} 64-char lowercase hex digest+ */+export function actionDigest(action) {+ return createHash('sha256').update(canonicalizeAction(action)).digest('hex');+}++/**+ * The exact string that gets ERC-191 signed. Framing the digest with a+ * domain-separating prefix prevents an action signature from being replayed as+ * a signature over some other three.ws message (e.g. a memory).+ *+ * @param {string} digest hex digest from actionDigest+ * @returns {string}+ */+export function signMessageBody(digest) {+ return `${ACTION_SIG_VERSION}:${digest}`;+}++/**+ * Sign an action with a raw EVM private key. Pure crypto, no network. Returns+ * the ERC-191 signature, the recovered signer address, and the digest.+ *+ * @param {string} privKeyHex 0x-prefixed 32-byte private key+ * @param {object} action the action to sign (agent_id, type, payload, source_skill)+ * @returns {Promise<{ signature: string, signer_address: string, digest: string }>}+ */+export async function signAction(privKeyHex, action) {+ const wallet = new Wallet(normalizeKey(privKeyHex));+ const digest = actionDigest(action);+ const signature = await wallet.signMessage(signMessageBody(digest));+ return { signature, signer_address: wallet.address, digest };+}++/**+ * Derive the EVM address for a private key without signing — used to label the+ * signer in dry runs and to validate a configured key at append time.+ *+ * @param {string} privKeyHex 0x-prefixed 32-byte private key+ * @returns {string} checksummed 0x address+ */+export function addressForKey(privKeyHex) {+ return computeAddress(normalizeKey(privKeyHex));+}++/**+ * Verify an action record against a signature + claimed signer. Pure crypto —+ * the function any agent runs offline to trust another agent's provenance.+ *+ * @param {object} action the action (ledger row or decorated)+ * @param {object} [proof]+ * @param {string} [proof.signature] ERC-191 signature (defaults to action.signature)+ * @param {string} [proof.signer_address] claimed signer (defaults to action.signer_address)+ * @returns {{ valid: boolean, recovered: string|null, digest: string, reason: string }}+ */+export function verifyAction(action, proof = {}) {+ const signature = proof.signature ?? action.signature ?? null;+ const signerAddress = proof.signer_address ?? action.signer_address ?? null;+ const digest = actionDigest(action);++ if (!signature || !signerAddress) {+ return { valid: false, recovered: null, digest, reason: 'unsigned' };+ }++ let recovered = null;+ try {+ recovered = verifyMessage(signMessageBody(digest), signature);+ } catch {+ return { valid: false, recovered: null, digest, reason: 'malformed_signature' };+ }++ const valid = recovered.toLowerCase() === String(signerAddress).toLowerCase();+ return {+ valid,+ recovered,+ digest,+ reason: valid ? 'ok' : 'signer_mismatch',+ };+}++// ethers accepts a 0x-prefixed key; tolerate a bare 64-hex key by adding 0x.+function normalizeKey(privKeyHex) {+ const k = String(privKeyHex || '').trim();+ if (!k) {+ throw Object.assign(new Error('signer private key is empty'), { code: 'bad_signer_key' });+ }+ return k.startsWith('0x') ? k : `0x${k}`;+}diff --git a/packages/provenance-mcp/src/tools/append-agent-action.js b/packages/provenance-mcp/src/tools/append-agent-action.jsnew file mode 100644index 000000000..cf174f3cf--- /dev/null+++ b/packages/provenance-mcp/src/tools/append-agent-action.js@@ -0,0 +1,91 @@+// `append_agent_action` — record one action in an agent's append-only+// provenance ledger. WRITE tool.+//+// Wraps POST /api/agent-actions. The ledger is immutable: this only ever adds a+// row, never overwrites or deletes (so destructiveHint:false), and the same+// call appends a new distinct record every time (idempotentHint:false). When an+// EVM signer key is configured (THREE_WS_SIGNER_KEY env or the `signer_key`+// arg) the action is ERC-191-signed before it is sent, so anyone can later+// `ecrecover` the signer and verify authorship on-chain. With no key the action+// is appended unsigned — honestly reported, never a fake signature.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { signerKey } from '../config.js';+import { signAction } from '../lib/signing.js';++export const def = {+ name: 'append_agent_action',+ title: 'Append a signed action to the provenance ledger',+ // MCP ToolAnnotations — WRITE: appends to an immutable, append-only ledger.+ // Never overwrites or deletes (destructiveHint:false). Each call records a+ // new distinct row (idempotentHint:false).+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ description:+ "Record an action in an agent's append-only provenance ledger — the permanent, auditable trail of what the agent did. Provide `agent_id` (THREE_WS_TOKEN must own it), a short `type` (≤64 chars, e.g. launch, buy, post, reflect), an optional structured `payload`, and an optional `source_skill`. WRITE ACTION: this APPENDS a new immutable record — it can never be edited or deleted, and calling it twice records two distinct actions, so don't retry blindly. When an EVM signer is configured (THREE_WS_SIGNER_KEY env or the `signer_key` arg) the action is ERC-191-signed before sending, making its authorship publicly verifiable; with no key it is appended unsigned. Returns the stored record (with id + created_at) and a `signing` block reporting whether it was signed and by which address.",+ inputSchema: {+ agent_id: z+ .string()+ .min(1)+ .describe('The agent identity id to record the action under. Your token must own it.'),+ type: z+ .string()+ .min(1)+ .max(64)+ .describe('Short action type, e.g. launch, buy, sell, post, reflect, follow. Truncated to 64 chars server-side.'),+ payload: z+ .record(z.any())+ .optional()+ .describe('Structured details of the action (any JSON object) — e.g. { mint, amount_sol, signature }. Stored verbatim and covered by the signature.'),+ source_skill: z+ .string()+ .max(200)+ .optional()+ .describe('Identifier of the skill/tool that produced this action, for attribution in the trail.'),+ signer_key: z+ .string()+ .optional()+ .describe('Optional 0x-prefixed EVM private key to ERC-191-sign this action. Overrides THREE_WS_SIGNER_KEY for this call. Omit to use the env key, or sign nothing if none is set.'),+ },+ async handler(args) {+ const agent_id = String(args?.agent_id ?? '').trim();+ const type = String(args?.type ?? '').trim();+ if (!agent_id) return { ok: false, error: 'validation_error', message: 'agent_id is required' };+ if (!type) return { ok: false, error: 'validation_error', message: 'type is required' };++ const payload = args?.payload && typeof args.payload === 'object' ? args.payload : {};+ const source_skill = args?.source_skill ? String(args.source_skill) : null;++ const body = { agent_id, type, payload, source_skill };++ // Sign before sending when a key is available. A bad key is a caller+ // error worth surfacing — don't silently downgrade to unsigned.+ const key = (args?.signer_key && String(args.signer_key).trim()) || signerKey();+ let signing = { signed: false, signer_address: null };+ if (key) {+ let signed;+ try {+ signed = await signAction(key, body);+ } catch (err) {+ return {+ ok: false,+ error: err?.code || 'signing_failed',+ message: `could not sign action: ${err?.message || err}`,+ };+ }+ body.signature = signed.signature;+ body.signer_address = signed.signer_address;+ signing = { signed: true, signer_address: signed.signer_address, digest: signed.digest };+ }++ const data = await apiRequest('/api/agent-actions', { method: 'POST', body });+ const action = data?.action ?? data;++ return {+ ok: true,+ action,+ signing,+ };+ },+};diff --git a/packages/provenance-mcp/src/tools/list-agent-actions.js b/packages/provenance-mcp/src/tools/list-agent-actions.jsnew file mode 100644index 000000000..86c7b1131--- /dev/null+++ b/packages/provenance-mcp/src/tools/list-agent-actions.js@@ -0,0 +1,79 @@+// `list_agent_actions` — read one agent's append-only provenance trail,+// newest-first, cursor-paginated. Read-only.+//+// Wraps GET /api/agent-actions?agent_id=&limit=&cursor=. The ledger is+// owner-scoped: the THREE_WS_TOKEN must own the agent (else 403/404). Each+// record carries an ERC-191 signature + signer_address when the action was+// signed at append time, so the trail is independently verifiable.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { verifyAction } from '../lib/signing.js';++export const def = {+ name: 'list_agent_actions',+ title: 'List an agent\'s action-provenance trail',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Read an agent's append-only action log, newest-first, cursor-paginated. Returns each action's id, type (e.g. launch, buy, post, reflect), payload, source_skill, created_at, and — when the action was signed — its ERC-191 signature + signer_address. Each record is checked against its own signature: `verification.reason` is `ok` (recovered signer matches the claimed address), `unsigned`, `signer_mismatch` (recovered a different address — tampering OR an action signed under a different canonical scheme; treat as unverified, not trusted), or `malformed_signature`. Pass the returned `next_cursor` back as `cursor` to page further. The ledger is owner-scoped: THREE_WS_TOKEN must own `agent_id`. Read-only; the log is immutable so older pages never change.",+ inputSchema: {+ agent_id: z+ .string()+ .min(1)+ .describe('The agent identity id whose provenance trail to read. Your token must own it.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .default(50)+ .describe('Max actions to return (1–200, default 50).'),+ cursor: z+ .string()+ .regex(/^\d+$/)+ .optional()+ .describe('Pagination cursor — pass the `next_cursor` from a previous call to fetch the next (older) page.'),+ },+ async handler(args) {+ const agent_id = String(args?.agent_id ?? '').trim();+ const limit = clampLimit(args?.limit);+ const cursor = args?.cursor != null ? String(args.cursor) : undefined;++ const data = await apiRequest('/api/agent-actions', {+ query: { agent_id, limit, cursor },+ });++ const actions = Array.isArray(data?.actions) ? data.actions : [];+ return {+ ok: true,+ agent_id,+ count: actions.length,+ next_cursor: data?.next_cursor ?? null,+ has_more: Boolean(data?.next_cursor),+ actions: actions.map(decorateWithVerification),+ };+ },+};++export function clampLimit(raw) {+ const n = Number(raw);+ if (!Number.isFinite(n)) return 50;+ return Math.min(Math.max(Math.trunc(n), 1), 200);+}++// Attach an offline verification verdict to each record. The verdict is the raw+// recover-and-compare result — never softened. A `signer_mismatch` (recovered a+// different address than claimed) stays a mismatch: it could be tampering or a+// foreign signing scheme, and either way the record is not trustable as-is.+export function decorateWithVerification(action) {+ if (!action || typeof action !== 'object') return action;+ if (!action.signature || !action.signer_address) {+ return { ...action, verification: { signed: false, valid: false, reason: 'unsigned' } };+ }+ const v = verifyAction(action);+ return {+ ...action,+ verification: { signed: true, valid: v.valid, reason: v.reason, recovered: v.recovered },+ };+}diff --git a/packages/provenance-mcp/src/tools/query-action.js b/packages/provenance-mcp/src/tools/query-action.jsnew file mode 100644index 000000000..6ea5e4c70--- /dev/null+++ b/packages/provenance-mcp/src/tools/query-action.js@@ -0,0 +1,67 @@+// `query_action` — fetch one action from an agent's provenance trail by id and+// independently verify its signature. Read-only.+//+// The ledger exposes a cursor-paginated list (id DESC, `id < cursor`). To pull a+// single record we request the window starting just above the target id with+// limit 1, which returns exactly that action when it exists and belongs to the+// agent. The signature is then recovered and checked offline.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';+import { verifyAction } from '../lib/signing.js';++export const def = {+ name: 'query_action',+ title: 'Fetch + verify one provenance action',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Fetch a single action from an agent's append-only log by its id, then verify it. Returns the action (type, payload, source_skill, created_at, signature, signer_address) plus a `verification` block: `signed`, `valid`, `reason` (`ok` | `unsigned` | `signer_mismatch` | `malformed_signature`), the `recovered` signer address, and the recomputed `digest`. `valid:true` means the ERC-191 signature recovers to the claimed signer over the canonical action form — cryptographic proof the named agent authored this exact action and it was not altered. The ledger is owner-scoped: THREE_WS_TOKEN must own `agent_id`. Returns ok:false / not_found when the id is absent from this agent's log. Read-only.",+ inputSchema: {+ agent_id: z+ .string()+ .min(1)+ .describe('The agent identity id that owns the action. Your token must own this agent.'),+ id: z+ .string()+ .regex(/^\d+$/)+ .describe('The numeric action id to fetch (the `id` field from list_agent_actions).'),+ },+ async handler(args) {+ const agent_id = String(args?.agent_id ?? '').trim();+ const id = String(args?.id ?? '').trim();+ if (!/^\d+$/.test(id)) {+ return { ok: false, error: 'validation_error', message: 'id must be a numeric action id' };+ }++ // `id < cursor` is strict, so the window above (id+1) makes the target the+ // first row returned. BigInt keeps bigserial ids exact.+ const cursor = (BigInt(id) + 1n).toString();+ const data = await apiRequest('/api/agent-actions', {+ query: { agent_id, limit: 1, cursor },+ });++ const actions = Array.isArray(data?.actions) ? data.actions : [];+ const action = actions.find((a) => String(a?.id) === id) || null;+ if (!action) {+ return {+ ok: false,+ error: 'not_found',+ message: `action ${id} not found in agent ${agent_id}'s log`,+ };+ }++ const v = verifyAction(action);+ return {+ ok: true,+ action,+ verification: {+ signed: Boolean(action.signature && action.signer_address),+ valid: v.valid,+ reason: v.reason,+ recovered: v.recovered,+ digest: v.digest,+ },+ };+ },+};diff --git a/packages/provenance-mcp/test/registration.test.mjs b/packages/provenance-mcp/test/registration.test.mjsnew file mode 100644index 000000000..0504a949b--- /dev/null+++ b/packages/provenance-mcp/test/registration.test.mjs@@ -0,0 +1,76 @@+// Tool-surface invariants for @three-ws/provenance-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 token or+// signer. These tests run offline — they never touch the network.+//+// Run: node --test packages/provenance-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_agent_actions',+ 'query_action',+ 'append_agent_action',+];++const READ_TOOLS = new Set(['list_agent_actions', 'query_action']);+const WRITE_TOOLS = new Set(['append_agent_action']);++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('read tools are read-only, live, non-idempotent, and omit destructiveHint', () => {+ for (const tool of TOOLS.filter((t) => READ_TOOLS.has(t.name))) {+ 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 ledger data is never idempotent — newer actions appear 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('the append tool is a non-idempotent, non-destructive write', () => {+ for (const tool of TOOLS.filter((t) => WRITE_TOOLS.has(t.name))) {+ assert.equal(tool.annotations.readOnlyHint, false, `${tool.name} writes — readOnlyHint must be false`);+ // Append-only ledger: each call records a new row, none are ever removed.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} appends a new record every call`);+ assert.equal(tool.annotations.destructiveHint, false, `${tool.name} never overwrites or deletes`);+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ }+});++test('buildServer registers every tool with its annotations, without a token or 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/provenance-mcp/test/signing.test.mjs b/packages/provenance-mcp/test/signing.test.mjsnew file mode 100644index 000000000..fac2dcbb4--- /dev/null+++ b/packages/provenance-mcp/test/signing.test.mjs@@ -0,0 +1,92 @@+// ERC-191 action signing/verification round-trips — offline, real crypto.+//+// These exercise the actual ethers Wallet sign + ecrecover path that+// append_agent_action and query_action rely on. No network, no mocks.+//+// Run: node --test packages/provenance-mcp/test/signing.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import {+ ACTION_SIG_VERSION,+ stableStringify,+ canonicalizeAction,+ actionDigest,+ signAction,+ addressForKey,+ verifyAction,+} from '../src/lib/signing.js';++// A deterministic, clearly-synthetic test key (not a real funded wallet).+const TEST_KEY = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';++test('stableStringify sorts keys so equal payloads hash identically regardless of order', () => {+ const a = stableStringify({ b: 1, a: { y: 2, x: 3 }, c: [3, 2, 1] });+ const b = stableStringify({ c: [3, 2, 1], a: { x: 3, y: 2 }, b: 1 });+ assert.equal(a, b);+});++test('canonicalizeAction is order-independent in payload and version-tagged', () => {+ const base = { agent_id: 'agent_1', type: 'launch', source_skill: 'pump' };+ const one = canonicalizeAction({ ...base, payload: { mint: 'X', amount: 1 } });+ const two = canonicalizeAction({ ...base, payload: { amount: 1, mint: 'X' } });+ assert.equal(one, two);+ assert.ok(one.includes(ACTION_SIG_VERSION));+ // Same digest for the two orderings.+ assert.equal(+ actionDigest({ ...base, payload: { mint: 'X', amount: 1 } }),+ actionDigest({ ...base, payload: { amount: 1, mint: 'X' } }),+ );+});++test('signAction produces a signature that verifies against the recovered signer', async () => {+ const action = { agent_id: 'agent_42', type: 'buy', payload: { mint: 'THREEsynthetic1111', sol: 0.5 }, source_skill: 'autopilot' };+ const { signature, signer_address, digest } = await signAction(TEST_KEY, action);++ assert.equal(signer_address, addressForKey(TEST_KEY));+ assert.equal(digest, actionDigest(action));++ const v = verifyAction({ ...action, signature, signer_address });+ assert.equal(v.valid, true);+ assert.equal(v.reason, 'ok');+ assert.equal(v.recovered.toLowerCase(), signer_address.toLowerCase());+});++test('verifyAction reports unsigned when no signature is present', () => {+ const v = verifyAction({ agent_id: 'a', type: 'post', payload: {}, signature: null, signer_address: null });+ assert.equal(v.valid, false);+ assert.equal(v.reason, 'unsigned');+});++test('verifyAction detects tampering — a mutated payload fails verification', async () => {+ const action = { agent_id: 'agent_7', type: 'reflect', payload: { note: 'original' }, source_skill: null };+ const { signature, signer_address } = await signAction(TEST_KEY, action);++ const tampered = { ...action, payload: { note: 'altered' }, signature, signer_address };+ const v = verifyAction(tampered);+ assert.equal(v.valid, false);+ assert.equal(v.reason, 'signer_mismatch');+});++test('verifyAction reports malformed_signature on garbage input', () => {+ const v = verifyAction({+ agent_id: 'a',+ type: 'post',+ payload: {},+ signature: '0xnotasignature',+ signer_address: '0x0000000000000000000000000000000000000000',+ });+ assert.equal(v.valid, false);+ assert.equal(v.reason, 'malformed_signature');+});++test('signatures are domain-separated: a memory-style body does not verify as an action', async () => {+ // The action body is prefixed with ACTION_SIG_VERSION; a signature over a+ // different framing must not validate against the action digest.+ const action = { agent_id: 'agent_1', type: 'launch', payload: { mint: 'X' } };+ const { signature, signer_address } = await signAction(TEST_KEY, action);+ // Same signature, but claim it covers a different action — must fail.+ const other = { agent_id: 'agent_1', type: 'sell', payload: { mint: 'X' }, signature, signer_address };+ assert.equal(verifyAction(other).valid, false);+});diff --git a/packages/signals-mcp/LICENSE b/packages/signals-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/signals-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/signals-mcp/README.md b/packages/signals-mcp/README.mdnew file mode 100644index 000000000..792d84bd3--- /dev/null+++ b/packages/signals-mcp/README.md@@ -0,0 +1,171 @@+<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/signals-mcp</h1>++<p align="center"><strong>Discover, subscribe to, and track copy-trade signal feeds — a marketplace ranked by proven realized edge and a publisher leaderboard from real on-chain performance, from any AI agent.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/signals-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/signals-mcp?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/signals-mcp?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/signals-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 **signal-marketplace** surface over stdio. Browse copy-trade feeds ranked by *proven* realized edge, rank publishers by real on-chain performance, subscribe one of your agents to a feed, track its delivery history and realized ROI, and halt it instantly with a kill switch.++Every feed, ranking, and delivery stat comes straight from the live three.ws API. Discovery and the publisher leaderboard are **public, read-only — no key required**. The follower tools (subscribe, list-your-subscriptions, kill/pause) are **account-scoped** and authenticate with a three.ws API key.++> **Already have [`@three-ws/intel-mcp`](https://www.npmjs.com/package/@three-ws/intel-mcp)?** Its `signal_feed` tool reads a *single* feed's accuracy + emission log. This server is the complementary half: feed **discovery**, **subscription**, **tracking**, and the **publisher leaderboard**.++## Install++```bash+npm install @three-ws/signals-mcp+```++Or run with `npx` (no install):++```bash+npx @three-ws/signals-mcp+```++## Quick start++**Claude Code**, one line:++```bash+claude mcp add signals -- npx -y @three-ws/signals-mcp+```++With the follower tools enabled (account-scoped):++```bash+claude mcp add signals --env THREE_WS_API_KEY=sk_live_xxx -- npx -y @three-ws/signals-mcp+```++**Claude Desktop / Cursor** (`claude_desktop_config.json` or `mcp.json`):++```json+{+ "mcpServers": {+ "signals": {+ "command": "npx",+ "args": ["-y", "@three-ws/signals-mcp"],+ "env": { "THREE_WS_API_KEY": "sk_live_xxx" }+ }+ }+}+```++Inspect the surface with the MCP Inspector:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/signals-mcp+```++## Tools++| Tool | Type | What it does |+| ------------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------- |+| `list_signal_feeds` | read · public | Browse the feed directory ranked by proven realized edge (hit-rate × ROI, confidence-regressed). Returns each feed's `id`, pricing, publisher, and stats. |+| `get_mirror_leaderboard` | read · public | Rank publishers/leaders by REAL on-chain performance — realized P&L, win-rate, volume, followers. Every number traces to a signature. |+| `get_subscriptions` | read · account | List your subscriptions with delivery history and realized stats (executed fills, paid count, USDC spent). |+| `subscribe_signal` | write · account | Subscribe one of your agents to a feed. `simulate` mode pays/trades nothing; `live` pays USDC (x402) and mirrors real trades. Idempotent upsert. |+| `set_subscription_status` | write · account | Resume, pause, stop, or **instantly kill** a subscription (the kill halts all pay/trade before it fires). |++`list_signal_feeds` and `get_mirror_leaderboard` are read-only and need no key. The other three are account-scoped — they require `THREE_WS_API_KEY`.++### Input parameters++**`list_signal_feeds`** — `network` (`mainnet` | `devnet`, default `mainnet`), `sort` (`edge` | `roi` | `hitrate` | `subscribers` | `newest`, default `edge`), `limit` (1–100, default 60).++**`get_mirror_leaderboard`** — `network` (`mainnet` | `devnet`, default `mainnet`), `sort` (`score` | `pnl` | `followers` | `volume` | `winrate`, default `score`), `limit` (1–50, default 25).++**`get_subscriptions`** — *(no parameters)*.++**`subscribe_signal`** — `agent_id` (required, your subscriber agent), `feed_id` (required, from `list_signal_feeds`), `mode` (`simulate` | `live`, default `simulate`), `billing` (`per_signal` | `per_epoch`, default `per_signal`), `base_sol` (0.001–10), `size_scaling` (0.01–20), `max_per_trade_sol` (0.001–50), `slippage_bps` (0–5000), `firewall_level` (`block` | `warn`), `copy_exits` (bool).++**`set_subscription_status`** — `subscription_id` (required), `state` (`active` | `paused` | `stopped` | `killed`).++## Payment & risk++`subscribe_signal` is the only money-moving tool, and only in **live** mode:++- **`mode:"simulate"` (default)** — mirrors the publisher's signals WITHOUT paying or trading. Orders are sized and labelled for trust-building; nothing is spent.+- **`mode:"live"`** — BOTH pays the publisher in **USDC over x402** (per-signal or per-epoch, per the feed's pricing) AND auto-mirrors real on-chain trades from the subscriber agent's custodial wallet, within its spend policy.++Money moves at **delivery time** (when the publisher emits a signal), not at the moment you call `subscribe_signal`. To stop a live subscription from spending or trading **right now**, call `set_subscription_status` with `state:"killed"` — the kill is honoured before any payment or trade can fire.++Publishing is reputation-gated on the platform: only agents with a verified on-chain track record can run a feed, so the directory you browse is real edge, not self-declared.++## Example++```jsonc+// list_signal_feeds+> { "sort": "edge", "limit": 2 }+{+ "ok": true,+ "network": "mainnet",+ "sort": "edge",+ "count": 2,+ "feeds": [+ {+ "rank": 1,+ "id": 42,+ "slug": "alpha-trader-1a2b3c4d",+ "title": "Alpha Trader",+ "publisher": { "name": "Alpha", "verified": true, "score": 81, "realized_pnl_sol": 12.4 },+ "pricing": { "per_signal_usdc": 1, "per_epoch_usdc": 20, "epoch_seconds": 86400 },+ "stats": { "closed_signals": 34, "hit_rate": 0.68, "avg_realized_pct": 41.2, "subscribers": 19 },+ "edge_score": 77+ }+ ]+}+```++```jsonc+// subscribe_signal (live — spends USDC at delivery time)+> { "agent_id": "agt_…", "feed_id": 42, "mode": "live", "billing": "per_signal", "base_sol": 0.05, "max_per_trade_sol": 0.25 }+{ "ok": true, "subscription": { "id": 7, "feed_id": 42, "mode": "live", "status": "active", "killed": false } }+```++```jsonc+// set_subscription_status (instant kill switch)+> { "subscription_id": 7, "state": "killed" }+{ "ok": true, "state": "killed", "subscription": { "id": 7, "killed": true, "status": "paused" } }+```++## Requirements++- **Node.js >= 20.**+- Network access to `https://three.ws` (or your own `THREE_WS_BASE`).+- A three.ws API key (`THREE_WS_API_KEY`) **only** for the account-scoped follower tools.++### Environment variables++| Variable | Required | Default |+| --------------------- | -------------------------------- | ------------------ |+| `THREE_WS_BASE` | no | `https://three.ws` |+| `THREE_WS_TIMEOUT_MS` | no | `20000` |+| `THREE_WS_API_KEY` | for the follower tools only | — |++## 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/signals-mcp/package.json b/packages/signals-mcp/package.jsonnew file mode 100644index 000000000..93f0de025--- /dev/null+++ b/packages/signals-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/signals-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/signals-mcp",+ "description": "Discover, subscribe to, and track three.ws copy-trade signal feeds from any AI agent — a marketplace ranked by proven realized edge, a publisher leaderboard from real on-chain performance, and account-scoped subscribe + kill-switch controls 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/signals-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "signals",+ "copy-trading",+ "marketplace",+ "leaderboard",+ "x402"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "signals-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/signals-mcp/server.json b/packages/signals-mcp/server.jsonnew file mode 100644index 000000000..4e12ecdb6--- /dev/null+++ b/packages/signals-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/signals-mcp",+ "title": "three.ws Signals",+ "description": "Discover copy-trade signal feeds ranked by proven edge, rank publishers by real on-chain performance, and subscribe + track over the live three.ws API.",+ "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/signals-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/signals-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 signal-marketplace 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 marketplace reads and subscription writes.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ },+ {+ "name": "THREE_WS_API_KEY",+ "description": "three.ws API key (sk_live_… / sk_test_…) for the account-scoped follower tools (get_subscriptions, subscribe_signal, set_subscription_status). Optional — the public discovery and leaderboard tools work without it. subscribe_signal in live mode spends real USDC, so treat this key like cash.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ }+ ]+ }+ ]+}diff --git a/packages/signals-mcp/src/config.js b/packages/signals-mcp/src/config.jsnew file mode 100644index 000000000..db221eb46--- /dev/null+++ b/packages/signals-mcp/src/config.js@@ -0,0 +1,42 @@+// Centralized env + HTTP config for the signals MCP.+//+// This server is the signal-marketplace surface of three.ws. The discovery and+// publisher-leaderboard reads are PUBLIC (no credential). The follower tools —+// listing your subscriptions, subscribing, and the kill/pause controls — are+// account-scoped writes that authenticate with a three.ws API key, so the only+// secret this server ever holds is THREE_WS_API_KEY (supplied by the operator,+// never baked in). Every feed, delivery stat, and ranking comes live from the+// endpoints; nothing is computed or cached here.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Base URL of the three.ws API. Override only when self-hosting or pointing at a+// preview deployment.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Per-request timeout (ms). These are live reads/writes (marketplace ranking,+// subscription upserts) — 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;+})();++// three.ws API key (sk_live_… / sk_test_…) for the account-scoped follower tools.+// Optional: the public discovery + leaderboard tools work without it. Required+// only for subscribe_signal, set_subscription_status, and get_subscriptions —+// each throws a clear `auth_required` error when it is missing. Treat like cash.+export const THREE_WS_API_KEY = env('THREE_WS_API_KEY', '');++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/signals-mcp';diff --git a/packages/signals-mcp/src/index.js b/packages/signals-mcp/src/index.jsnew file mode 100644index 000000000..b1cb15751--- /dev/null+++ b/packages/signals-mcp/src/index.js@@ -0,0 +1,127 @@+#!/usr/bin/env node+// @three-ws/signals-mcp — MCP server entry point.+//+// Gives any AI agent the three.ws signal-marketplace surface over stdio:+// • list_signal_feeds — discover copy-trade feeds, ranked by proven edge+// • get_mirror_leaderboard — rank publishers by REAL on-chain performance+// • get_subscriptions — your subscriptions + delivery history & realized ROI+// • subscribe_signal — subscribe an agent to a feed (simulate or live)+// • set_subscription_status — resume / pause / stop / instant-kill a subscription+//+// Discovery + the leaderboard are PUBLIC reads. The follower tools (the last+// three) are account-scoped: set THREE_WS_API_KEY to an sk_live_… / sk_test_…+// three.ws API key. subscribe_signal in live mode pays the publisher in USDC+// (x402) and auto-mirrors real trades at delivery time — read its description.+//+// Run standalone:+// node packages/signals-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 listSignalFeeds } from './tools/list-signal-feeds.js';+import { def as getMirrorLeaderboard } from './tools/get-mirror-leaderboard.js';+import { def as getSubscriptions } from './tools/get-subscriptions.js';+import { def as subscribeSignal } from './tools/subscribe-signal.js';+import { def as setSubscriptionStatus } from './tools/set-subscription-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 = [+ listSignalFeeds,+ getMirrorLeaderboard,+ getSubscriptions,+ subscribeSignal,+ setSubscriptionStatus,+];++/**+ * 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: 'signals-mcp', title: 'three.ws Signals', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Signals MCP — discover, subscribe to, and track copy-trade signal feeds. ' ++ 'list_signal_feeds browses the public feed directory ranked by PROVEN realized edge (a thin feed ' ++ "with one lucky call can't top a deep, consistent one). get_mirror_leaderboard ranks publishers by " ++ 'real on-chain performance — every number traces to a signature, losers included. get_subscriptions ' ++ 'lists your subscriptions with delivery history and realized ROI. subscribe_signal subscribes one of ' ++ 'your agents to a feed: simulate mode (default) pays/trades nothing; LIVE mode pays the publisher in ' ++ 'USDC (x402) and auto-mirrors real trades at delivery time. set_subscription_status resumes, pauses, ' ++ 'stops, or INSTANTLY KILLS a subscription (the kill halts all pay/trade before it fires). Discovery ' ++ 'and the leaderboard are public; the follower tools need THREE_WS_API_KEY (an sk_live_… key). All ' ++ 'data is live from the three.ws API — nothing is mocked.',+ },+ );++ 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(`[signals-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('[signals-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/signals-mcp/src/lib/api.js b/packages/signals-mcp/src/lib/api.jsnew file mode 100644index 000000000..26456a074--- /dev/null+++ b/packages/signals-mcp/src/lib/api.js@@ -0,0 +1,88 @@+// 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';++/**+ * Guard for the account-scoped tools. Throws a clean `auth_required` error+ * (surfaced to the MCP client) when no API key is configured, so the agent gets+ * an actionable message instead of an upstream 401.+ */+export function requireApiKey() {+ if (!THREE_WS_API_KEY) {+ throw Object.assign(+ new Error(+ 'This tool is account-scoped and needs a three.ws API key. Set THREE_WS_API_KEY ' ++ '(an sk_live_… / sk_test_… key from three.ws) in the server environment.',+ ),+ { code: 'auth_required', status: 401 },+ );+ }+}++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * When THREE_WS_API_KEY is set it is sent as `Authorization: Bearer <key>`, which+ * authenticates the account-scoped follower endpoints (api-key bearer auth needs+ * no CSRF). Public endpoints ignore the header.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/signals/marketplace`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]+ * @returns {Promise<any>} Parsed JSON response.+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),+ * and on upstream errors `.status` + `.body`.+ */+export async function apiRequest(path, { method = 'GET', query, body } = {}) {+ const url = new URL(`${THREE_WS_BASE}${path}`);+ if (query) {+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null || value === '') continue;+ url.searchParams.set(key, String(value));+ }+ }++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);++ let res;+ try {+ res = await fetch(url, {+ method,+ headers: {+ accept: 'application/json',+ 'user-agent': USER_AGENT,+ ...(THREE_WS_API_KEY ? { 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/signals-mcp/src/tools/get-mirror-leaderboard.js b/packages/signals-mcp/src/tools/get-mirror-leaderboard.jsnew file mode 100644index 000000000..e1ba0f54a--- /dev/null+++ b/packages/signals-mcp/src/tools/get-mirror-leaderboard.js@@ -0,0 +1,57 @@+// `get_mirror_leaderboard` — performance-weighted ranking of followable+// publishers/leaders for copy-trading. Read-only.+//+// Wraps GET /api/mirror/leaderboard?network=&sort=&limit=.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++const SORTS = ['score', 'pnl', 'followers', 'volume', 'winrate'];++export const def = {+ name: 'get_mirror_leaderboard',+ title: 'Rank signal publishers by realized performance',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Rank followable agents (signal publishers / copy-trade leaders) by REAL, on-chain-derived ' ++ 'performance — never inflated. Every number traces to a real signature: realized P&L and win-rate come ' ++ 'from closed sniper round-trips, volume from the discretionary custody ledger, and losers are included. ' ++ 'Each leader returns rank, agent_id, name, avatar, settled trades, wins, win_rate, realized pnl_sol, ' ++ 'roi_pct, trade count, volume_sol, follower counts, last trade time, and a composite score (realized ROI ' ++ 'weighted by sample size so a one-trade fluke cannot top a consistent trader). Sort by `score` (default), ' ++ '`pnl`, `followers`, `volume`, or `winrate`. Use this to find a leader before subscribing to their feed. ' ++ 'Public, read-only live data — no key required.',+ inputSchema: {+ network: z+ .enum(['mainnet', 'devnet'])+ .default('mainnet')+ .describe('Solana network to rank on (default mainnet).'),+ sort: z+ .enum(SORTS)+ .default('score')+ .describe('Ranking key: score (default), pnl, followers, volume, or winrate.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(50)+ .default(25)+ .describe('Maximum leaders to return (1–50, default 25).'),+ },+ async handler(args) {+ const network = args?.network === 'devnet' ? 'devnet' : 'mainnet';+ const sort = SORTS.includes(args?.sort) ? args.sort : 'score';+ const limit = Math.max(1, Math.min(50, Number(args?.limit) || 25));++ const data = await apiRequest('/api/mirror/leaderboard', { query: { network, sort, limit } });+ const leaders = Array.isArray(data?.data?.leaders) ? data.data.leaders : [];+ return {+ ok: true,+ network: data?.data?.network || network,+ sort: data?.data?.sort || sort,+ count: leaders.length,+ leaders,+ };+ },+};diff --git a/packages/signals-mcp/src/tools/get-subscriptions.js b/packages/signals-mcp/src/tools/get-subscriptions.jsnew file mode 100644index 000000000..ffc8a19a3--- /dev/null+++ b/packages/signals-mcp/src/tools/get-subscriptions.js@@ -0,0 +1,31 @@+// `get_subscriptions` — the caller's signal subscriptions with delivery history+// and realized performance. Account-scoped, read-only.+//+// Wraps GET /api/signals/subscribe (Authorization: Bearer <THREE_WS_API_KEY>).++import { apiRequest, requireApiKey } from '../lib/api.js';++export const def = {+ name: 'get_subscriptions',+ title: 'List your signal subscriptions + delivery history',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "List every signal subscription owned by the authenticated account — the follower's tracking surface. " ++ 'Each subscription returns its numeric `id` (pass this to set_subscription_status), the subscriber agent, ' ++ 'the feed it follows (slug, title, publisher, pricing), the copy-trade config (mode simulate/live, billing, ' ++ 'base_sol, size_scaling, max_per_trade_sol, slippage_bps, firewall_level, copy_exits), live status ' ++ '(status, killed flag, epoch_paid_until, last delivered emission), and the realized delivery stats: ' ++ '`stats.executed` (mirror fills that executed on-chain), `stats.paid_count` (paid deliveries), and ' ++ '`stats.usdc_spent` (total USDC paid to the publisher). Requires THREE_WS_API_KEY. Read-only live data.',+ inputSchema: {},+ async handler() {+ requireApiKey();+ const data = await apiRequest('/api/signals/subscribe', { method: 'GET' });+ const subscriptions = Array.isArray(data?.subscriptions) ? data.subscriptions : [];+ return {+ ok: true,+ count: subscriptions.length,+ subscriptions,+ };+ },+};diff --git a/packages/signals-mcp/src/tools/list-signal-feeds.js b/packages/signals-mcp/src/tools/list-signal-feeds.jsnew file mode 100644index 000000000..efb8199a3--- /dev/null+++ b/packages/signals-mcp/src/tools/list-signal-feeds.js@@ -0,0 +1,58 @@+// `list_signal_feeds` — the public signal-feed directory. Read-only.+//+// Wraps GET /api/signals/marketplace?network=&sort=&limit=.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++const SORTS = ['edge', 'roi', 'hitrate', 'subscribers', 'newest'];++export const def = {+ name: 'list_signal_feeds',+ title: 'Browse the signal-feed marketplace',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Discover copy-trade signal feeds on three.ws. Returns the public directory of active feeds, each ' ++ 'ranked by its PROVEN realized edge (hit-rate × realized ROI, confidence-regressed toward the ' ++ "publisher's verified track-record score until enough signals have closed — a thin feed riding one " ++ 'lucky call can never top a deep, consistent one). For each feed you get its numeric `id` (pass this ' ++ 'to subscribe_signal), `slug`, title, the publisher (name, verified badge, track-record score, realized ' ++ 'SOL P&L), pricing (per-signal and per-epoch USDC), and proven stats (closed signals, hit-rate, average ' ++ 'realized %, active subscribers, executed fills, avg emit→fill latency, avg follower ROI). Sort by ' ++ '`edge` (default), `roi`, `hitrate`, `subscribers`, or `newest`. Public, read-only live data — no key required.',+ inputSchema: {+ network: z+ .enum(['mainnet', 'devnet'])+ .default('mainnet')+ .describe('Solana network the feeds publish on (default mainnet).'),+ sort: z+ .enum(SORTS)+ .default('edge')+ .describe(+ 'Ranking key: edge (proven realized edge, default), roi (avg realized %), hitrate, subscribers, or newest.',+ ),+ limit: z+ .number()+ .int()+ .min(1)+ .max(100)+ .default(60)+ .describe('Maximum feeds to return (1–100, default 60).'),+ },+ async handler(args) {+ const network = args?.network === 'devnet' ? 'devnet' : 'mainnet';+ const sort = SORTS.includes(args?.sort) ? args.sort : 'edge';+ const limit = Math.max(1, Math.min(100, Number(args?.limit) || 60));++ const data = await apiRequest('/api/signals/marketplace', { query: { network, sort, limit } });+ const feeds = Array.isArray(data?.feeds) ? data.feeds : [];+ return {+ ok: true,+ network: data?.network || network,+ sort: data?.sort || sort,+ count: feeds.length,+ feeds,+ };+ },+};diff --git a/packages/signals-mcp/src/tools/set-subscription-status.js b/packages/signals-mcp/src/tools/set-subscription-status.jsnew file mode 100644index 000000000..4f0124953--- /dev/null+++ b/packages/signals-mcp/src/tools/set-subscription-status.js@@ -0,0 +1,48 @@+// `set_subscription_status` — control an existing subscription: resume, pause,+// stop, or instantly KILL it (halt all further pay/trade). Account-scoped write,+// idempotent (setting a state repeatedly leaves the same state).+//+// Wraps POST /api/signals/subscribe { id, status } / { id, killed }.++import { z } from 'zod';++import { apiRequest, requireApiKey } from '../lib/api.js';++export const def = {+ name: 'set_subscription_status',+ title: 'Resume, pause, stop, or kill a subscription',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Control an existing signal subscription owned by the authenticated account.\n' ++ ' • active — (re)activate it; this also CLEARS any kill flag so it resumes paying/mirroring.\n' ++ ' • paused — stop delivering for now; the kill flag (if set) is left untouched.\n' ++ ' • stopped — stop the subscription (soft — its delivery history is kept).\n' ++ ' • killed — INSTANT kill switch: halts everything immediately; the kill is honoured before any ' ++ 'payment or trade can fire. Use this to stop a live subscription from spending or trading right now.\n' ++ 'Idempotent — setting the same state again is a no-op. Get the subscription `id` from get_subscriptions. ' ++ 'Requires THREE_WS_API_KEY.',+ inputSchema: {+ subscription_id: z+ .number()+ .int()+ .positive()+ .describe('Numeric subscription id (the `id` from get_subscriptions).'),+ state: z+ .enum(['active', 'paused', 'stopped', 'killed'])+ .describe('Target state: active (resume + clear kill), paused, stopped, or killed (instant halt of all pay/trade).'),+ },+ async handler(args) {+ requireApiKey();+ const id = Number(args?.subscription_id);+ const state = args?.state;+ const body = state === 'killed' ? { id, killed: true } : { id, status: state };++ const data = await apiRequest('/api/signals/subscribe', { method: 'POST', body });+ const subscription = data?.subscription ?? null;+ return {+ ok: true,+ subscription,+ state: subscription ? (subscription.killed ? 'killed' : subscription.status) : state,+ };+ },+};diff --git a/packages/signals-mcp/src/tools/subscribe-signal.js b/packages/signals-mcp/src/tools/subscribe-signal.jsnew file mode 100644index 000000000..5c02f159d--- /dev/null+++ b/packages/signals-mcp/src/tools/subscribe-signal.js@@ -0,0 +1,98 @@+// `subscribe_signal` — subscribe one of your agents to a signal feed (create or+// update the subscription). Account-scoped write, idempotent upsert.+//+// Wraps POST /api/signals/subscribe (Authorization: Bearer <THREE_WS_API_KEY>).++import { z } from 'zod';++import { apiRequest, requireApiKey } from '../lib/api.js';++export const def = {+ name: 'subscribe_signal',+ title: 'Subscribe an agent to a signal feed',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ description:+ 'Subscribe one of YOUR agents to a signal feed so it copy-trades the publisher. Idempotent: a feed is ' ++ 'keyed by (subscriber agent, feed) — re-calling updates the existing subscription instead of creating a ' ++ 'duplicate. A new subscription starts at the current emission head, so it is never charged for or made to ' ++ 'mirror signals emitted before it subscribed.\n\n' ++ 'PAYMENT & RISK: `mode:"simulate"` (default) mirrors WITHOUT paying or trading — it sizes and labels the ' ++ 'orders for trust-building, spends nothing. `mode:"live"` BOTH pays the publisher in USDC (x402, ' ++ 'per-signal or per-epoch per the feed pricing) AND auto-mirrors real on-chain trades from the subscriber ' ++ "agent's custodial wallet, within its spend policy. Money moves at delivery time (when the publisher emits " ++ 'a signal), not at the moment you call this tool. Use set_subscription_status with killed:true to halt all ' ++ 'further pay/trade instantly. Requires THREE_WS_API_KEY; the agent must be owned by that account.',+ inputSchema: {+ agent_id: z+ .string()+ .min(1)+ .describe('ID of the subscriber agent (must be owned by the authenticated account). This agent pays and mirrors.'),+ feed_id: z+ .number()+ .int()+ .positive()+ .describe('Numeric feed id to follow (from list_signal_feeds — the `id` field). The feed must be active.'),+ mode: z+ .enum(['simulate', 'live'])+ .default('simulate')+ .describe('simulate = no pay, no trade (default, safe). live = pays USDC AND auto-mirrors real trades.'),+ billing: z+ .enum(['per_signal', 'per_epoch'])+ .default('per_signal')+ .describe('How live mode is charged: per_signal (each entry) or per_epoch (a flat fee per epoch window).'),+ base_sol: z+ .number()+ .min(0.001)+ .max(10)+ .optional()+ .describe('Base order size in SOL before the per-signal size multiple/scaling (0.001–10, default 0.05).'),+ size_scaling: z+ .number()+ .min(0.01)+ .max(20)+ .optional()+ .describe('Multiplier applied on top of the base size (0.01–20, default 1).'),+ max_per_trade_sol: z+ .number()+ .min(0.001)+ .max(50)+ .optional()+ .describe('Hard cap on any single mirrored order in SOL (0.001–50, default 0.25).'),+ slippage_bps: z+ .number()+ .int()+ .min(0)+ .max(5000)+ .optional()+ .describe('Max slippage in basis points for mirrored trades (0–5000, default 300 = 3%).'),+ firewall_level: z+ .enum(['block', 'warn'])+ .default('block')+ .describe('Risk firewall on mirrored buys: block (refuse risky trades, default) or warn (allow with a flag).'),+ copy_exits: z+ .boolean()+ .default(true)+ .describe('Mirror the publisher\'s exits too (sell when they sell). Default true.'),+ },+ async handler(args) {+ requireApiKey();+ const body = {+ agent_id: String(args?.agent_id ?? '').trim(),+ feed_id: Number(args?.feed_id),+ mode: args?.mode === 'live' ? 'live' : 'simulate',+ billing: args?.billing === 'per_epoch' ? 'per_epoch' : 'per_signal',+ firewall_level: args?.firewall_level === 'warn' ? 'warn' : 'block',+ copy_exits: args?.copy_exits !== false,+ };+ if (args?.base_sol != null) body.base_sol = Number(args.base_sol);+ if (args?.size_scaling != null) body.size_scaling = Number(args.size_scaling);+ if (args?.max_per_trade_sol != null) body.max_per_trade_sol = Number(args.max_per_trade_sol);+ if (args?.slippage_bps != null) body.slippage_bps = Math.round(Number(args.slippage_bps));++ const data = await apiRequest('/api/signals/subscribe', { method: 'POST', body });+ return {+ ok: true,+ subscription: data?.subscription ?? null,+ };+ },+};diff --git a/packages/signals-mcp/test/registration.test.mjs b/packages/signals-mcp/test/registration.test.mjsnew file mode 100644index 000000000..f6842bae6--- /dev/null+++ b/packages/signals-mcp/test/registration.test.mjs@@ -0,0 +1,85 @@+// Tool-surface invariants for @three-ws/signals-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/signals-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_signal_feeds',+ 'get_mirror_leaderboard',+ 'get_subscriptions',+ 'subscribe_signal',+ 'set_subscription_status',+];++// The account-scoped write tools (account-keyed POSTs). Everything else is a+// public, read-only live query.+const WRITE_NAMES = new Set(['subscribe_signal', 'set_subscription_status']);++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`);+ // Every tool talks to the live three.ws API.+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} talks to a live service`);+ }+});++test('read-only tools are honest live queries; writes are flagged', () => {+ for (const tool of TOOLS) {+ if (WRITE_NAMES.has(tool.name)) {+ assert.equal(tool.annotations.readOnlyHint, false, `${tool.name} is a write — readOnlyHint must be false`);+ } else {+ assert.equal(tool.annotations.readOnlyHint, true, `${tool.name} should be read-only`);+ // Live market data is never idempotent — the feed/leaderboard moves between calls.+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);+ }+ }+});++test('the two account-scoped writes are present and marked', () => {+ const writes = TOOLS.filter((t) => t.annotations.readOnlyHint === false).map((t) => t.name);+ assert.deepEqual(new Set(writes), WRITE_NAMES);+});++test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {+ for (const tool of TOOLS) {+ if (WRITE_NAMES.has(tool.name)) continue;+ 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/pages/agent-detail.html b/pages/agent-detail.htmlindex 7243f644d..8f160eb6a 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -209,12 +209,6 @@<link rel="stylesheet" href="/nav.css" /><link rel="stylesheet" href="/footer.css" /><script defer src="/footer-newsletter.js"></script>- <script- type="module"- src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"- integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"- crossorigin="anonymous"- ></script><script>// Optimistic auth probe so the reviews widget can prompt sign-in on// submit instead of firing a csrf/POST round-trip the server would@@ -241,7 +235,6 @@);});</script>- <script type="module" src="/model-viewer-meshopt.js"></script></head><body><div id="nav-container"></div>@@ -289,18 +282,7 @@<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg></button><div class="ad-hero-avatar-wrap" id="ad-avatar-wrap" role="button" aria-label="View full 3D model" tabindex="0">- <model-viewer- id="ad-avatar-3d"- class="ad-hero-avatar"- auto-rotate- rotation-per-second="18deg"- interaction-prompt="none"- loading="eager"- reveal="auto"- shadow-intensity="0"- exposure="1.1"- alt="Agent 3D avatar"- ></model-viewer>+ <div id="ad-avatar-3d" class="ad-hero-avatar" role="img" aria-label="Agent 3D avatar"></div><img class="ad-hero-avatar" id="ad-avatar" alt="" style="display:none" /><div class="ad-hero-avatar-overlay" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>@@ -982,14 +964,7 @@<div class="ad-3d-modal hidden" id="ad-3d-modal" role="dialog" aria-modal="true" aria-label="Full-screen 3D viewer"><div class="ad-3d-modal-inner"><button class="ad-3d-modal-close" id="ad-3d-modal-close" aria-label="Close">✕</button>- <model-viewer- id="ad-avatar-modal-3d"- auto-rotate- camera-controls- shadow-intensity="0"- exposure="1.1"- alt="Agent 3D avatar — fullscreen"- ></model-viewer>+ <div id="ad-avatar-modal-3d" role="img" aria-label="Agent 3D avatar — fullscreen"></div><aid="ad-3d-modal-world"class="ad-3d-modal-world"diff --git a/pages/ibm/hello.html b/pages/ibm/hello.htmlindex 1b09cd438..0e275b7f7 100644--- a/pages/ibm/hello.html+++ b/pages/ibm/hello.html@@ -5,10 +5,10 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark">-<title>x402 live demo — three.ws × IBM</title>-<meta name="description" content="A live, self-contained x402 demo: pay $0.001 in USDC from your own wallet to call a real three.ws data API. Settled on-chain on Base or Solana. No backend, no account.">-<meta property="og:title" content="x402 live demo — three.ws × IBM">-<meta property="og:description" content="Pay $0.001 in USDC from your own wallet to call a real three.ws API. See HTTP 402 micropayments settle on-chain — on Base or Solana — in seconds.">+<title>IBM and three.ws partnership</title>+<meta name="description" content="IBM and three.ws work together to unite payments, data, 3D and AI — pairing IBM Granite on watsonx.ai with three.ws's on-chain micropayments and 3D agent engine. Explore live demos that run against real production systems.">+<meta property="og:title" content="IBM and three.ws partnership">+<meta property="og:description" content="IBM and three.ws unite payments, data, 3D and AI — IBM Granite on watsonx.ai with three.ws on-chain micropayments and 3D agents. Live demos, nothing mocked."><meta property="og:type" content="website"><style>/* ─── Self-hosted IBM Plex (latin subset) — no third-party font CDN, so a@@ -113,11 +113,15 @@ a:focus-visible{outline-offset:3px}/* ── Hero ── */.hero{padding:56px 0 36px}-.partner-label{display:inline-flex;align-items:center;gap:12px;border:1px solid var(--ibm-border);padding:6px 14px;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-muted);margin-bottom:28px}-.ibm-mark{font-family:var(--font-sans);font-weight:700;font-size:15px;letter-spacing:-.01em;color:var(--ibm-blue);line-height:1}.hero h1{font-size:clamp(30px,5vw,46px);font-weight:300;line-height:1.1;margin-bottom:18px;max-width:680px}.hero h1 strong{font-weight:600}.hero-sub{font-size:18px;color:var(--ibm-muted);max-width:620px;font-weight:300;line-height:1.6}+.hero-eyebrow{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-blue);font-weight:500;margin-bottom:14px}+.hero-cta{display:flex;flex-wrap:wrap;align-items:center;gap:16px 28px;margin-top:30px}+.btn-tertiary{display:inline-flex;align-items:center;gap:10px;color:var(--ibm-link);font-size:15px;font-weight:500;background:none;border:none;padding:0;cursor:pointer;transition:gap .12s,color .12s}+.btn-tertiary:hover{text-decoration:none;color:var(--ibm-blue-hover);gap:14px}+.btn-tertiary:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:3px}+.hero-note{font-size:14px;color:var(--ibm-subtle);max-width:660px;font-weight:300;line-height:1.65;margin-top:30px}/* ── How-it-works ── */.steps{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--ibm-border);border:1px solid var(--ibm-border);list-style:none;margin-top:24px}@@ -448,22 +452,82 @@ a:focus-visible{outline-offset:3px}<button type="button" id="errBannerClose">Dismiss</button></div>+<!-- ══ IBM MASTHEAD + BREADCRUMB ══+ The IBM.com global-navigation design language: a thin top bar with the IBM+ wordmark, primary product links (to real ibm.com destinations), and the+ search / account / app-grid icons, followed by a content breadcrumb. The+ masthead logo is the neutral IBM Plex wordmark, NOT the registered 8-bar+ mark — a defensible placeholder; confirm the exact lockup with IBM brand+ before public launch (see HOSTING.md, "Note on branding"). -->+<style id="ibm-shell-styles">+.ibm-mast{position:sticky;top:0;z-index:40;background:var(--ibm-surface);border-bottom:1px solid var(--ibm-border)}+.ibm-mast .mast-inner{display:flex;align-items:center;height:48px;padding:0 16px;gap:0}+.ibm-mast .mast-logo{display:inline-flex;align-items:center;height:100%;padding:0 16px 0 0;font-weight:700;font-size:18px;letter-spacing:-.01em;color:var(--ibm-ink);line-height:1}+.ibm-mast .mast-logo:hover{text-decoration:none;color:var(--ibm-blue)}+.ibm-mast .mast-logo:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:-2px}+.ibm-mast .mast-nav{display:flex;align-items:stretch;height:100%;flex:1 1 auto;min-width:0}+.ibm-mast .mast-nav a{display:inline-flex;align-items:center;height:100%;padding:0 16px;font-size:14px;font-weight:400;color:var(--ibm-ink);border-bottom:2px solid transparent;transition:background .12s,border-color .12s,color .12s}+.ibm-mast .mast-nav a:hover{background:var(--ibm-field);text-decoration:none;border-bottom-color:var(--ibm-blue)}+.ibm-mast .mast-nav a:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:-2px}+.ibm-mast .mast-actions{display:flex;align-items:stretch;height:100%;margin-left:auto;flex:0 0 auto}+.ibm-mast .mast-actions a{display:inline-flex;align-items:center;justify-content:center;width:48px;height:100%;color:var(--ibm-ink);transition:background .12s,color .12s}+.ibm-mast .mast-actions a:hover{background:var(--ibm-field);color:var(--ibm-blue)}+.ibm-mast .mast-actions a:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:-2px}+.ibm-mast .mast-actions svg{width:20px;height:20px;display:block}+.breadcrumb{border-bottom:1px solid var(--ibm-border)}+.breadcrumb ol{display:flex;flex-wrap:wrap;align-items:center;gap:8px;list-style:none;margin:0 auto;max-width:880px;padding:14px 16px;font-size:14px}+.breadcrumb li{display:inline-flex;align-items:center;gap:8px;color:var(--ibm-subtle)}+.breadcrumb li+li::before{content:"/";color:var(--ibm-divider);font-size:14px}+.breadcrumb a{color:var(--ibm-link)}+.breadcrumb a:hover{text-decoration:underline}+.breadcrumb [aria-current="page"]{color:var(--ibm-subtle)}+@media(max-width:671px){+ .ibm-mast .mast-nav{display:none}+ .breadcrumb ol{padding:12px}+}+</style>+<nav class="ibm-mast" aria-label="IBM">+ <div class="mast-inner">+ <a class="mast-logo" href="https://www.ibm.com" target="_blank" rel="noopener" aria-label="IBM home">IBM</a>+ <div class="mast-nav">+ <a href="https://www.ibm.com/products/software" target="_blank" rel="noopener">Software</a>+ <a href="https://www.ibm.com/infrastructure" target="_blank" rel="noopener">Infrastructure</a>+ <a href="https://www.ibm.com/consulting" target="_blank" rel="noopener">Consulting</a>+ <a href="https://www.ibm.com/support" target="_blank" rel="noopener">Support</a>+ <a href="https://www.ibm.com/think" target="_blank" rel="noopener">Think</a>+ </div>+ <div class="mast-actions">+ <a href="https://www.ibm.com/search" target="_blank" rel="noopener" aria-label="Search ibm.com">+ <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="14" cy="14" r="9"/><path d="M21 21l6 6" stroke-linecap="round"/></svg>+ </a>+ <a href="https://www.ibm.com/profile" target="_blank" rel="noopener" aria-label="IBM account">+ <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="16" cy="11" r="5"/><path d="M6 27c0-5 4.5-8 10-8s10 3 10 8" stroke-linecap="round"/></svg>+ </a>+ <a href="https://www.ibm.com" target="_blank" rel="noopener" aria-label="IBM products and tools">+ <svg viewBox="0 0 32 32" fill="currentColor" aria-hidden="true"><rect x="4" y="4" width="7" height="7"/><rect x="13" y="4" width="7" height="7"/><rect x="22" y="4" width="7" height="7"/><rect x="4" y="13" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/><rect x="22" y="13" width="7" height="7"/><rect x="4" y="22" width="7" height="7"/><rect x="13" y="22" width="7" height="7"/><rect x="22" y="22" width="7" height="7"/></svg>+ </a>+ </div>+ </div>+</nav>+<nav class="breadcrumb" aria-label="Breadcrumb">+ <ol>+ <li><a href="https://www.ibm.com" target="_blank" rel="noopener">Home</a></li>+ <li><a href="https://www.ibm.com/partnerplus" target="_blank" rel="noopener">Strategic Partnerships</a></li>+ <li><span aria-current="page">three.ws</span></li>+ </ol>+</nav>+<!-- ══ HERO ══ --><header class="hero"><div class="inner">- <div class="partner-label">- <!-- IBM brand: neutral typographic wordmark (IBM Plex, Carbon blue) — a defensible- placeholder, NOT the registered 8-bar logo. Confirm the exact mark and the- "IBM Business Partner" lockup + wording with IBM brand before public launch- (see HOSTING.md, "Note on branding"). -->- <span class="ibm-mark">IBM</span>- <span>Business Partner</span>- <span style="color:var(--ibm-border)" aria-hidden="true">|</span>- <span class="mono">three.ws</span>+ <p class="hero-eyebrow">Strategic partnership</p>+ <h1>IBM and <strong>three.ws</strong> partnership</h1>+ <p class="hero-sub">IBM® and three.ws work together to unite payments, data, 3D and AI — pairing IBM Granite on watsonx.ai with three.ws's on-chain micropayments and 3D agent engine, so developers and brands can deliver trusted, personalized agent experiences at scale.</p>+ <div class="hero-cta">+ <a class="btn" href="#forge">Explore the live demos <span class="arrow" aria-hidden="true">→</span></a>+ <a class="btn-tertiary" href="https://three.ws/docs/ibm" target="_blank" rel="noopener">Explore IBM and three.ws technology collaborations <span aria-hidden="true">→</span></a></div>- <h1>A live showcase of agentic commerce, built with <strong>IBM</strong></h1>- <p class="hero-sub">IBM has shaped computing for over a century — and it stays at the frontier by backing what comes next. three.ws is one of those bets: a platform for on-chain micropayments and 3D AI agents. As an IBM Business Partner, we built this page to demonstrate that partnership in the open — every demo below runs against real, production three.ws systems. Nothing is mocked, nothing is a slide.</p>- <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay a few cents to turn text into a 3D model, forge a rigged, animated avatar from a sentence for free, fly through a 3D galaxy of every agent mapped by <span class="mono">IBM Granite</span>, a shared 3D world, and an agent placed in augmented reality. Try each one yourself — the paid Forge demo settles real USDC from your own wallet; the rest are free, no wallet needed.</p>+ <p class="hero-note">Every demo below runs against real, production three.ws systems: pay a few cents to turn text into a 3D model, forge a rigged avatar from a sentence, pose it by hand, fly a 3D galaxy of agents mapped by <span class="mono">IBM Granite</span>, enter a shared world, or place an agent in augmented reality. The paid Forge settles real USDC from your own wallet; the rest are free, no wallet needed. Nothing is mocked.</p><nav class="demo-nav" aria-label="The demos on this page"><a href="#webinar" class="nav-live"><span class="live-dot" aria-hidden="true"></span>Watch live</a><a href="#forge"><span class="n">01</span>Forge</a>@@ -1144,6 +1208,33 @@ a:focus-visible{outline-offset:3px}</section><!-- ══ EMBED ══ -->+<style id="three-x402-styles">+.x402-live{margin-top:28px;border:1px solid var(--ibm-border);background:var(--ibm-surface)}+.x402-live .xl-head{padding:16px 18px;border-bottom:1px solid var(--ibm-border)}+.x402-live .xl-kicker{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-blue);font-weight:500;margin-bottom:6px}+.x402-live .xl-title{font-size:18px;font-weight:600}+.x402-live .xl-body{padding:18px}+.x402-live .xl-row{display:flex;flex-wrap:wrap;align-items:center;gap:16px 24px;margin-top:16px}+.x402-live .xl-note{font-size:12.5px;color:var(--ibm-subtle);margin-top:14px;line-height:1.55}+.ti-result{margin-top:18px}+.ti-empty{font-size:14px;color:var(--ibm-subtle);line-height:1.6;margin:0}+.ti-topline{display:flex;align-items:center;gap:12px;margin-bottom:14px}+.ti-sym{font-size:20px;font-weight:600}+.ti-signal{display:inline-flex;align-items:center;gap:7px;padding:5px 12px;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.04em;border-radius:2px}+.ti-signal::before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor}+.ti-signal.bullish{background:var(--ibm-green-fill);color:var(--ibm-green-ink)}+.ti-signal.bearish{background:var(--ibm-red-fill);color:var(--ibm-red-ink)}+.ti-signal.neutral{background:var(--ibm-amber-fill);color:var(--ibm-amber)}+.ti-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(118px,1fr));gap:1px;background:var(--ibm-border);border:1px solid var(--ibm-border)}+.ti-cell{background:var(--ibm-surface);padding:12px 14px}+.ti-cell .k{font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--ibm-subtle);margin-bottom:5px}+.ti-cell .v{font-size:16px;font-weight:600;font-family:var(--font-mono)}+.ti-cell .v.ti-up{color:var(--ibm-green-ink)}+.ti-cell .v.ti-down{color:var(--ibm-red-ink)}+.ti-headline{font-size:15px;font-weight:600;margin:16px 0 6px}+.ti-rationale{font-size:14px;color:var(--ibm-muted);line-height:1.55;margin:0}+.ti-meta{font-size:12px;color:var(--ibm-subtle);margin-top:12px;font-family:var(--font-mono)}+</style><section class="section" aria-labelledby="embed-h"><div class="inner"><div class="section-tag">For developers</div>@@ -1154,12 +1245,38 @@ a:focus-visible{outline-offset:3px}<span class="c-com"><!-- any element with data-x402-endpoint becomes payable --></span><span class="c-tag"><button</span>- <span class="c-attr">data-x402-endpoint</span>=<span class="c-str">"https://three.ws/api/x402/symbol-availability?ticker=GRANITE"</span>+ <span class="c-attr">data-x402-endpoint</span>=<span class="c-str">"https://three.ws/api/x402/three-intel"</span><span class="c-attr">data-x402-merchant</span>=<span class="c-str">"three.ws"</span>- <span class="c-attr">data-x402-action</span>=<span class="c-str">"Check symbol"</span><span class="c-tag">></span>- Pay $0.001 & run+ <span class="c-attr">data-x402-action</span>=<span class="c-str">"$THREE intel"</span><span class="c-tag">></span>+ Pay $0.01 & get $THREE intel<span class="c-tag"></button></span></div><div class="copy-row"><button class="copy-btn" id="copyBtn" type="button">Copy snippet</button></div>++ <!-- The snippet above, wired live. x402.js (loaded near </body>) binds any+ [data-x402-endpoint]; this is the same $THREE Town Oracle the in-world+ kiosk on /play buys from, settled in real USDC over x402. -->+ <div class="x402-live" id="threeOracle">+ <div class="xl-head">+ <div class="xl-kicker">Live · runs right here</div>+ <div class="xl-title">The <span class="mono">$THREE</span> Town Oracle</div>+ </div>+ <div class="xl-body">+ <p class="section-lead" style="margin-top:0">That exact button, wired to the real endpoint. Pay <strong>$0.01 USDC</strong> from your own wallet and get live <span class="mono">$THREE</span> market intel — price, 24-hour move, market cap, liquidity, volume, and a bullish / bearish / neutral signal — from the same oracle the paid kiosk in the <span class="mono">$THREE</span> town on <a href="https://three.ws/play" target="_blank" rel="noopener">/play</a> sells from.</p>+ <div class="xl-row">+ <button class="btn" id="threeOracleBtn" type="button"+ data-x402-endpoint="https://three.ws/api/x402/three-intel"+ data-x402-merchant="three.ws"+ data-x402-action="$THREE market intel">+ <span class="label">Pay $0.01 & fetch live $THREE intel</span> <span class="arrow" aria-hidden="true">→</span>+ </button>+ <a class="btn-tertiary" href="https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">View <span class="mono">$THREE</span> on pump.fun <span aria-hidden="true">→</span></a>+ </div>+ <div class="ti-result" id="threeOracleResult" aria-live="polite">+ <p class="ti-empty">You'll get back price, 24-hour change, market cap, liquidity, 24-hour volume, and a signal with a short rationale — live from DexScreener. Settles in USDC on Solana or Base; the network fee is sponsored by the facilitator.</p>+ </div>+ <p class="xl-note">Spends $0.01 of real USDC from your wallet. The only coin three.ws issues is <span class="mono">$THREE</span> · <span class="mono">FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</span>.</p>+ </div>+ </div></div></section></main>@@ -1285,10 +1402,10 @@ a:focus-visible{outline-offset:3px}var snippet ='<script type="module" src="https://three.ws/x402.js"><\/script>\n\n' +'<button\n' +- ' data-x402-endpoint="https://three.ws/api/x402/symbol-availability?ticker=GRANITE"\n' ++ ' data-x402-endpoint="https://three.ws/api/x402/three-intel"\n' +' data-x402-merchant="three.ws"\n' +- ' data-x402-action="Check symbol">\n' +- ' Pay $0.001 & run\n' ++ ' data-x402-action="$THREE intel">\n' ++ ' Pay $0.01 & get $THREE intel\n' +'</button>';var done = function (label) { var b = $('copyBtn'); b.textContent = label; setTimeout(function () { b.textContent = 'Copy snippet'; }, 1600); };if (navigator.clipboard && navigator.clipboard.writeText) {@@ -1298,6 +1415,52 @@ a:focus-visible{outline-offset:3px}}});+ // ── Live $THREE Town Oracle ($0.01 USDC over x402) ─────────────────────────+ // x402.js binds [data-x402-endpoint] and fires `x402:result` on the button+ // with detail { ok, result, payment, response } once payment settles. We+ // format the live oracle response into the on-page intel card.+ (function () {+ var btn = $('threeOracleBtn');+ var out = $('threeOracleResult');+ if (!btn || !out) return;+ var esc = function (s) { var d = document.createElement('div'); d.textContent = String(s == null ? '' : s); return d.innerHTML; };+ var num = function (n) { return typeof n === 'number' && isFinite(n); };+ var fmtPrice = function (n) { if (!num(n)) return '—'; return n >= 1 ? '$' + n.toLocaleString(undefined, { maximumFractionDigits: 4 }) : '$' + Number(n).toPrecision(4); };+ var fmtCompact = function (n) { if (!num(n)) return '—'; try { return '$' + new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 }).format(n); } catch (_) { return '$' + Math.round(n).toLocaleString(); } };+ var fmtPct = function (n) { if (!num(n)) return '—'; return (n >= 0 ? '+' : '') + n.toFixed(2) + '%'; };+ function render(r) {+ if (!r || typeof r !== 'object') { out.innerHTML = '<p class="ti-empty">The call settled but returned no data. Try again.</p>'; return; }+ var sig = String(r.signal || 'neutral').toLowerCase();+ if (['bullish', 'bearish', 'neutral'].indexOf(sig) < 0) sig = 'neutral';+ var chgCls = num(r.change_24h) ? (r.change_24h >= 0 ? 'ti-up' : 'ti-down') : '';+ var mintShort = r.mint ? (String(r.mint).slice(0, 4) + '…' + String(r.mint).slice(-4)) : '';+ out.innerHTML =+ '<div class="ti-topline"><span class="ti-sym mono">$' + esc(r.symbol || 'THREE') + '</span>' ++ '<span class="ti-signal ' + sig + '">' + esc(sig) + '</span></div>' ++ '<div class="ti-grid">' ++ '<div class="ti-cell"><div class="k">Price</div><div class="v">' + fmtPrice(r.price_usd) + '</div></div>' ++ '<div class="ti-cell"><div class="k">24h</div><div class="v ' + chgCls + '">' + fmtPct(r.change_24h) + '</div></div>' ++ '<div class="ti-cell"><div class="k">Market cap</div><div class="v">' + fmtCompact(r.market_cap_usd) + '</div></div>' ++ '<div class="ti-cell"><div class="k">Liquidity</div><div class="v">' + fmtCompact(r.liquidity_usd) + '</div></div>' ++ '<div class="ti-cell"><div class="k">24h volume</div><div class="v">' + fmtCompact(r.volume_24h_usd) + '</div></div>' ++ '</div>' ++ (r.headline ? '<p class="ti-headline">' + esc(r.headline) + '</p>' : '') ++ (r.rationale ? '<p class="ti-rationale">' + esc(r.rationale) + '</p>' : '') ++ '<p class="ti-meta">' + (mintShort ? 'mint ' + esc(mintShort) + ' · ' : '') + (num(r.confidence) ? 'confidence ' + Math.round(r.confidence * 100) + '% · ' : '') + 'live via x402</p>';+ }+ btn.addEventListener('x402:result', function (e) {+ var d = e.detail || {};+ var r = d.result;+ if (typeof r === 'string') { try { r = JSON.parse(r); } catch (_) {} }+ render(r);+ try { out.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } catch (_) {}+ });+ btn.addEventListener('x402:error', function (e) {+ var msg = (e.detail && e.detail.error) ? String(e.detail.error) : 'The payment was cancelled or failed.';+ out.innerHTML = '<p class="ti-empty">' + esc(msg) + ' Nothing was charged unless a receipt appeared — you can try again.</p>';+ });+ })();+wireLiveEmbeds();})();</script>diff --git a/public/brain-studio.css b/public/brain-studio.cssindex b2df6ae70..fbc3758de 100644--- a/public/brain-studio.css+++ b/public/brain-studio.css@@ -205,9 +205,11 @@ textarea.brainstudio__input { resize: vertical; }background: var(--bg-1);}.brainstudio__footer-save {+ margin-right: auto;font-size: var(--text-sm); color: var(--ink-faint);transition: color .2s;}+.brainstudio__footer-exit { padding: 8px 16px; }.brainstudio__footer-save[data-state="saving"] { color: var(--warn, #fbbf24); }.brainstudio__footer-save[data-state="saved"] { color: var(--node-market); }.brainstudio__footer-save[data-state="error"] { color: var(--node-output); }diff --git a/public/changelog.json b/public/changelog.jsonindex 5599c0e74..fc293b3bf 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T04:43:14.383Z",+ "generated_at": "2026-06-24T06:04:17.142Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -26,6 +26,102 @@"launch"]},+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Agent profile avatars now stand and breathe instead of freezing in a T-pose",+ "summary": "Open any agent's profile and its 3D body is alive: the avatar settles into a natural standing idle — arms down, weight on its feet, subtle breathing and blinks — and turns slowly on a turntable, instead of hanging in the stiff arms-out T-pose the old static viewer showed. The profile now runs the same real-time animation engine as the rest of the platform, so the idle and gesture clips are retargeted onto whatever rig your avatar uses. Tap the avatar to open it full-screen and orbit it freely. If a device can't run 3D, it cleanly falls back to a still image.",+ "link": "/agents",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Agent Studio's Brain editor now has a clear Save & exit",+ "summary": "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.",+ "link": "/agent-studio",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Agents can now record and verify each other's actions over MCP — signed, on-chain-provable provenance",+ "summary": "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.",+ "link": null,+ "tags": [+ "sdk",+ "feature",+ "security"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "AI agents can now find and follow copy-trade signal feeds over MCP",+ "summary": "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.",+ "link": null,+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "AI agents can now manage their own autopilot scopes and spend limits over MCP",+ "summary": "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.",+ "link": null,+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "AI agents can now manage their own portfolio, PnL, and on-chain transfers over MCP",+ "summary": "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.",+ "link": null,+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "AI agents can now run your copy-trading over MCP — follow leaders, tune guard rules, and track fees owed",+ "summary": "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.",+ "link": "/changelog",+ "tags": [+ "sdk",+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Buy live $THREE market intel over x402 — right on the IBM partnership page",+ "summary": "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.",+ "link": "/bazaar",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase",+ "summary": "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.",+ "link": "/pose",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 9b9662f5a..57ef5f4e0 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,78 @@<category>launch</category><description>Set up the three.ws authority wallet and SAS_AUTHORITY_SECRET, bootstrap the Solana Attestation Service credential and schemas, and issue or read credentialed attestations.</description></item>+ <item>+ <title>Agent profile avatars now stand and breathe instead of freezing in a T-pose</title>+ <link>https://three.ws/agents</link>+ <guid isPermaLink="false">2026-06-24:Agent profile avatars now stand and breathe instead of freezing in a T-pose</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Open any agent's profile and its 3D body is alive: the avatar settles into a natural standing idle — arms down, weight on its feet, subtle breathing and blinks — and turns slowly on a turntable, instead of hanging in the stiff arms-out T-pose the old static viewer showed. The profile now runs the same real-time animation engine as the rest of the platform, so the idle and gesture clips are retargeted onto whatever rig your avatar uses. Tap the avatar to open it full-screen and orbit it freely. If a device can't run 3D, it cleanly falls back to a still image.</description>+ </item>+ <item>+ <title>Agent Studio's Brain editor now has a clear Save & exit</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-06-24:Agent Studio's Brain editor now has a clear Save & exit</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>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.</description>+ </item>+ <item>+ <title>Agents can now record and verify each other's actions over MCP — signed, on-chain-provable provenance</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:Agents can now record and verify each other's actions over MCP — signed, on-chain-provable provenance</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>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.</description>+ </item>+ <item>+ <title>AI agents can now find and follow copy-trade signal feeds over MCP</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:AI agents can now find and follow copy-trade signal feeds over MCP</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <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 their own autopilot scopes and spend limits over MCP</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:AI agents can now manage their own autopilot scopes and spend limits over MCP</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>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.</description>+ </item>+ <item>+ <title>AI agents can now manage their own portfolio, PnL, and on-chain transfers over MCP</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:AI agents can now manage their own portfolio, PnL, and on-chain transfers over MCP</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>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.</description>+ </item>+ <item>+ <title>AI agents can now run your copy-trading over MCP — follow leaders, tune guard rules, and track fees owed</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:AI agents can now run your copy-trading over MCP — follow leaders, tune guard rules, and track fees owed</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <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>Buy live $THREE market intel over x402 — right on the IBM partnership page</title>+ <link>https://three.ws/bazaar</link>+ <guid isPermaLink="false">2026-06-24:Buy live $THREE market intel over x402 — right on the IBM partnership page</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item>+ <item>+ <title>Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase</title>+ <link>https://three.ws/pose</link>+ <guid isPermaLink="false">2026-06-24:Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item><item><title>$THREE Tiers · Hold-to-Access</title><link>https://three.ws/three</link>diff --git a/public/features.json b/public/features.jsonindex b23cfa64b..b8263c5c1 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T04:43:14.369Z",+ "generated_at": "2026-06-24T06:04:17.130Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/nav-data.js b/public/nav-data.jsindex 5d84080b8..0eb72ebc3 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -45,7 +45,7 @@ export const NAV_GROUPS = [desc: 'Type a description → rigged 3D avatar in about a minute',},{- title: 'Create an agent',+ title: 'Create an avatar',href: '/create-agent',badge: 'New',desc: 'Guided wizard: name, 3D body, skills, personality → ship it',diff --git a/src/agent-detail.css b/src/agent-detail.cssindex 3d79c5b33..888f32089 100644--- a/src/agent-detail.css+++ b/src/agent-detail.css@@ -248,14 +248,22 @@ a {display: block;}-model-viewer.ad-hero-avatar {+/* Hero avatar is a live WebGL stage (real idle animation, never a T-pose). */+div.ad-hero-avatar {+ position: relative;width: 240px;height: 280px;border-radius: 18px;- --poster-color: transparent;+ overflow: hidden;background: transparent;border: 1px solid var(--ad-line);}+div.ad-hero-avatar canvas {+ display: block;+ width: 100% !important;+ height: 100% !important;+ border-radius: 18px;+}.ad-hero-body {width: 100%;@@ -370,12 +378,19 @@ model-viewer.ad-hero-avatar {line-height: 1;}.ad-3d-modal-close:hover { color: #fff; }-.ad-3d-modal model-viewer {+.ad-3d-modal #ad-avatar-modal-3d {+ position: relative;width: 100%; height: 100%;border-radius: 20px;- --poster-color: transparent;+ overflow: hidden;background: var(--ad-bg-2);}+.ad-3d-modal #ad-avatar-modal-3d canvas {+ display: block;+ width: 100% !important;+ height: 100% !important;+ border-radius: 20px;+}.ad-3d-modal-world {position: absolute;bottom: 16px; left: 50%;diff --git a/src/agent-detail.js b/src/agent-detail.jsindex a0d7053e1..301b47abf 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -16,6 +16,7 @@ import { mountStrategyPanel } from './shared/agent-strategy-panel.js';import { mountPatronagePanel } from './shared/agent-patronage.js';import { mountValidationBadge } from './shared/validation-badge.js';import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';+import { mountIdleAvatar } from './shared/idle-avatar.js';import { hydrateAvatarWallet } from './shared/wallet-aura.js';import { mountPresence } from './shared/networth-presence.js';import { mountStagePanel } from './shared/stage-link.js';@@ -45,6 +46,13 @@ let _streamHandle = null;let _strategyHandle = null;let _cardHandle = null;let _patronageHandle = null;+// Live WebGL avatar mounts (hero + fullscreen modal). Disposed on re-render so a+// fresh render() doesn't stack a second renderer onto the same container.+let _heroAvatarHandle = null;+let _modalAvatarHandle = null;+// Refreshed every render() so the once-wired modal-open handler always mounts the+// current avatar (enrichment can re-render with an updated GLB url).+let _mountModalAvatar = null;// The hero's wallet aura controller — torn down on re-render/unload so its live// poll + rAF never leak.@@ -93,6 +101,10 @@ if (typeof window !== 'undefined') {// past navigation (the engine also guards this internally).try { _streamHandle?.destroy?.(); } catch { /* idempotent */ } _streamHandle = null;try { _cardHandle?.destroy?.(); } catch { /* idempotent */ } _cardHandle = null;+ // Release the WebGL contexts so they don't count against the browser's+ // hard context budget once the user navigates away.+ try { _heroAvatarHandle?.dispose(); } catch { /* idempotent */ } _heroAvatarHandle = null;+ try { _modalAvatarHandle?.dispose(); } catch { /* idempotent */ } _modalAvatarHandle = null;}, { once: true });}@@ -653,7 +665,7 @@ function render(agent) {const $ = (id) => document.getElementById(id);- // Flat image fallback (hidden when model-viewer works)+ // Flat image fallback (hidden while the live WebGL avatar renders)const avatarImg = $('ad-avatar');if (avatarImg) {avatarImg.src = agent.avatar || avatarDataUri(agent.name);@@ -738,16 +750,30 @@ function render(agent) {renderAgentEmbed({ ...agent, avatar_glb_url: agent.avatar_glb_url || agentAvatarGlb(agent) });// ── Hero 3D avatar ────────────────────────────────────────────────────+ // A live, idle-animated body — the canonical idle clip is retargeted onto the+ // avatar's rig (arms drop, weight settles) and the procedural idle-life loop+ // (breathing, blink, weight shift) plays on top. Never a frozen bind-pose+ // T-pose, which is what a static <model-viewer> could only ever show.const glbUrl = agentAvatarGlb(agent);- const mv3d = document.getElementById('ad-avatar-3d');- if (mv3d) {- mv3d.setAttribute('src', glbUrl);- mv3d.addEventListener('error', () => {- // GLB failed — show the flat image fallback- mv3d.style.display = 'none';- const img = document.getElementById('ad-avatar');- if (img) img.style.display = '';- }, { once: true });+ // WebGL unavailable or the GLB failed → reveal the still image (already given a+ // real src — thumbnail or generated initials — earlier in render()).+ const showFlatFallback = () => {+ const host = document.getElementById('ad-avatar-3d');+ if (host) host.style.display = 'none';+ const img = document.getElementById('ad-avatar');+ if (img) img.style.display = '';+ };+ _heroAvatarHandle?.dispose();+ _heroAvatarHandle = null;+ const heroHost = document.getElementById('ad-avatar-3d');+ if (heroHost && glbUrl) {+ _heroAvatarHandle = mountIdleAvatar(heroHost, glbUrl, {+ autoRotate: true,+ seed: agent.id || agent.name || glbUrl,+ onError: showFlatFallback,+ });+ // null → no WebGL context available; fall back to the still image.+ if (!_heroAvatarHandle) showFlatFallback();}// Radial glow behind avatar derived from agent name colorconst glowEl = document.getElementById('ad-hero-glow');@@ -758,9 +784,21 @@ function render(agent) {// Net-Worth-Reactive Avatar: weld the agent's real wallet to its hero body so// its funded-ness is legible here exactly as on the viewer and in the galaxy.mountAgentDetailAura(agent);- // Fullscreen modal- const mvModal = document.getElementById('ad-avatar-modal-3d');- if (mvModal) mvModal.setAttribute('src', glbUrl);+ // Fullscreen modal — the orbitable, camera-controlled body. Mounted lazily on+ // first open so the page doesn't pay for a second WebGL context up front.+ _modalAvatarHandle?.dispose();+ _modalAvatarHandle = null;+ _mountModalAvatar = () => {+ if (_modalAvatarHandle) return;+ const host = document.getElementById('ad-avatar-modal-3d');+ if (host && glbUrl) {+ _modalAvatarHandle = mountIdleAvatar(host, glbUrl, {+ autoRotate: true,+ cameraControls: true,+ seed: agent.id || agent.name || glbUrl,+ });+ }+ };// "View in AR" link drops this agent into the live three.ws world (every// agent has a body — custom GLB or mannequin — so the href is always real).const modalWorld = document.getElementById('ad-3d-modal-world');@@ -778,9 +816,10 @@ function render(agent) {const closeModal = () => modal.classList.add('hidden');if (modal && avatarWrap && !avatarWrap._modalWired) {avatarWrap._modalWired = true;- avatarWrap.addEventListener('click', () => modal.classList.remove('hidden'));+ const openModal = () => { _mountModalAvatar?.(); modal.classList.remove('hidden'); };+ avatarWrap.addEventListener('click', openModal);avatarWrap.addEventListener('keydown', (e) => {- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); modal.classList.remove('hidden'); }+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openModal(); }});document.getElementById('ad-3d-modal-close')?.addEventListener('click', closeModal);modal.addEventListener('click', (e) => {diff --git a/src/shared/idle-avatar.js b/src/shared/idle-avatar.jsnew file mode 100644index 000000000..48adecac7--- /dev/null+++ b/src/shared/idle-avatar.js@@ -0,0 +1,145 @@+/**+ * Idle avatar mount — a living agent body, never a frozen T-pose.+ *+ * `<model-viewer>` can only render a GLB in its authored bind pose, which for+ * the vast majority of avatar rigs is a T-pose (arms straight out). three.ws+ * avatars carry no baked-in clips — idle/walk live in the runtime clip library+ * and are *retargeted* onto whatever skeleton the avatar ships with. So a static+ * viewer is structurally incapable of showing the avatar the way the platform+ * intends.+ *+ * This helper brings up the real Three.js `Viewer` (kiosk mode — no chrome),+ * loads the GLB, retargets the canonical `idle` clip onto it (arms come down,+ * weight settles), and layers the procedural idle-life loop (breathing, blink,+ * micro-saccades, weight shift) on top. The result reads as a person standing+ * there, not a mannequin pinned to a wall.+ *+ * Reuses the exact pattern proven in `avatar-embed.js`, packaged so any surface+ * that wants a small living portrait (agent hero, cards, modals) can drop it in.+ */++import { Viewer } from '../viewer.js';+import { IdleAnimation } from '../idle-animation.js';+import { log } from './log.js';++// The clip manifest is identical for every avatar and never changes within a+// session, so fetch it once and share the promise across every mount on the page.+let _manifestPromise = null;+function loadAnimationDefs() {+ if (!_manifestPromise) {+ _manifestPromise = fetch('/animations/manifest.json')+ .then((r) => (r.ok ? r.json() : []))+ .catch(() => []);+ }+ return _manifestPromise;+}++/**+ * Mount a living, idle-animated avatar into `container`.+ *+ * @param {HTMLElement} container Positioned element to fill (gets a relative+ * position if static). The WebGL stage is appended as an absolute child so it+ * inherits the container's border-radius/size from CSS.+ * @param {string} glbUrl Avatar model URL.+ * @param {Object} [opts]+ * @param {boolean} [opts.autoRotate=true] Slowly turn the figure on a turntable.+ * @param {string} [opts.seed] Stable seed so the idle phase is deterministic per agent.+ * @param {string} [opts.environment='Neutral'] Lighting environment name.+ * @param {boolean} [opts.cameraControls=false] Allow orbit/zoom (used in the modal).+ * @param {() => void} [opts.onError] Called if WebGL is unavailable or the GLB fails.+ * @returns {{ viewer: Viewer, setAutoRotate(v:boolean):void, dispose():void } | null}+ * null when a WebGL context can't be created (caller should fall back to a still image).+ */+export function mountIdleAvatar(container, glbUrl, opts = {}) {+ const {+ autoRotate = true,+ seed = glbUrl,+ environment = 'Neutral',+ cameraControls = false,+ onError,+ } = opts;++ if (getComputedStyle(container).position === 'static') {+ container.style.position = 'relative';+ }++ const stage = document.createElement('div');+ stage.className = 'idle-avatar-stage';+ stage.style.position = 'absolute';+ stage.style.inset = '0';+ container.appendChild(stage);++ let viewer;+ try {+ viewer = new Viewer(stage, { kiosk: true });+ } catch (err) {+ // GPU blocklist, context budget exhausted, headless — degrade to the+ // caller's still-image fallback rather than throwing into the page.+ stage.remove();+ log.warn('[idle-avatar] WebGL unavailable', err?.message);+ onError?.(err);+ return null;+ }++ viewer.state.environment = environment;+ viewer.state.autoRotate = autoRotate;+ viewer.controls.enabled = cameraControls;+ viewer.controls.enableZoom = cameraControls;+ viewer.controls.enablePan = false;+ // Transparent backdrop so the agent's radial glow shows through behind the body.+ viewer.renderer?.setClearAlpha(0);+ if (viewer.scene) viewer.scene.background = null;+ viewer.updateEnvironment?.();+ viewer.updateDisplay?.();++ // Procedural idle-life: breathing, blink, saccades, weight shift. Additive on+ // top of whatever clip plays, so the figure is never perfectly still.+ const idle = new IdleAnimation({ getRoot: () => viewer.content, seed });+ if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];+ viewer._afterAnimateHooks.push((dt) => idle.update(dt));++ let disposed = false;++ viewer+ .load(glbUrl, '', new Map())+ .then(async () => {+ if (disposed) return;+ const defs = await loadAnimationDefs();+ if (disposed || !Array.isArray(defs) || defs.length === 0) return;+ viewer.animationManager.setAnimationDefs(defs);+ // Retarget the idle clip first so the arms drop out of the bind pose+ // immediately; load the rest of the library in the background for any+ // later gesture playback. crossfadeTo handles rigs that can't accept+ // canonical clips by no-op'ing — the procedural idle still gives life.+ try {+ const ready = await viewer.animationManager.ensureLoaded('idle');+ if (!disposed && ready) await viewer.animationManager.crossfadeTo('idle', 0.4);+ } catch (err) {+ log.warn('[idle-avatar] idle clip retarget failed', err?.message);+ }+ viewer.animationManager.loadAll().catch(() => {});+ })+ .catch((err) => {+ if (disposed) return;+ log.warn('[idle-avatar] GLB load failed', err?.message);+ onError?.(err);+ });++ return {+ viewer,+ setAutoRotate(v) {+ viewer.state.autoRotate = !!v;+ viewer.updateDisplay?.();+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ try {+ viewer.dispose?.();+ } catch (err) {+ log.warn('[idle-avatar] dispose failed', err?.message);+ }+ stage.remove();+ },+ };+}diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.jsindex 8313bbfef..805bbad13 100644--- a/src/studio/brain/brain-studio.js+++ b/src/studio/brain/brain-studio.js@@ -108,6 +108,7 @@ class BrainStudio {</div><div class="brainstudio__footer"><span class="brainstudio__footer-save" id="bsFooterSave">Auto-saved</span>+ <button class="studio__btn brainstudio__footer-exit" id="bsExit" title="Save your brain and leave the studio">Save & exit ↗</button><button class="studio__btn studio__btn-primary brainstudio__footer-continue" id="bsContinue">Save & continue →</button></div></div>@@ -127,6 +128,7 @@ class BrainStudio {this.el.querySelector('#bsSave').addEventListener('click', () => this._saveNow());this.el.querySelector('#bsDone').addEventListener('click', () => this._done());this.el.querySelector('#bsContinue').addEventListener('click', () => this._done());+ this.el.querySelector('#bsExit').addEventListener('click', (e) => this._exit(e));this.el.querySelector('#bsCompose').addEventListener('submit', (e) => { e.preventDefault(); this._send(); });const input = this.el.querySelector('#bsInput');input.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); this._send(); } });@@ -219,6 +221,20 @@ class BrainStudio {}}+ // Save the brain and leave the studio. The graph's other actions (Done / Save &+ // continue) advance to Memory, so without this the editor reads as forward-only+ // with no way out. We delegate the real save + navigate to the shell via+ // `studio:exit` — its flushAndCommit pulls our latest wiring through `studio:flush`+ // first, and it owns the destination (the live agent page) so it stays in one place.+ _exit(e) {+ const btn = e.currentTarget;+ if (btn.dataset.busy) return;+ btn.dataset.busy = '1';+ btn.disabled = true;+ btn.textContent = 'Saving…';+ document.dispatchEvent(new CustomEvent('studio:exit'));+ }+_renderPalette() {const pal = this.el.querySelector('#bsPalette');pal.innerHTML = PALETTE.map((t) => `<button class="brainstudio__chip brainstudio__chip--${NODE_TYPES[t].accent}" data-add="${t}" title="Add ${NODE_TYPES[t].title}">+ ${esc(NODE_TYPES[t].title)}</button>`).join('');diff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.jsindex 0b3d947ed..80fce02e2 100644--- a/src/studio/studio-shell.js+++ b/src/studio/studio-shell.js@@ -291,6 +291,13 @@ class StudioShell {};document.addEventListener('studio:navigate', this._navHandler);+ // A focused sub-studio can also ask to leave the studio entirely (save + exit+ // to the live agent). The Brain editor's "Save & exit" fires this so the graph+ // is never a forward-only dead-end — its own controls otherwise only advance to+ // the next tab. The shell owns the destination so it lives in exactly one place.+ this._exitHandler = () => this._leaveStudio();+ document.addEventListener('studio:exit', this._exitHandler);+// Keep the header in sync if another surface edits the same agent.this._unsub = studio.subscribe((agent) => {if (!agent) return;@@ -346,14 +353,22 @@ class StudioShell {e.preventDefault();if (link.dataset.busy) return;link.dataset.busy = '1';- const href = link.getAttribute('href') || '/';link.textContent = 'Saving…';+ await this._leaveStudio(link.getAttribute('href'));+ }++ // Flush every sub-studio's edits, commit, then navigate out to the live agent.+ // Shared by the header "View agent" link and any sub-studio's studio:exit request+ // so a save-and-leave always lands somewhere real. We navigate even if the save+ // throws — leaving must never trap the user.+ async _leaveStudio(href) {+ const dest = href || this.root.querySelector('#studio-exit')?.getAttribute('href') || '/';try {await this._flushAndCommit();} catch {/* navigate anyway — leaving must never trap the user */}- location.href = href;+ location.href = dest;}_onTabKeydown(e, tabs) {