Skip to content

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.

feat: add audio, clash, loom MCP packages and complete tool implementations

nirholasf7f71b5f41d7
diff --git a/packages/activity-mcp/src/index.js b/packages/activity-mcp/src/index.js
new file mode 100644
index 000000000..d0229da1c
--- /dev/null
+++ b/packages/activity-mcp/src/index.js
@@ -0,0 +1,125 @@
+#!/usr/bin/env node
+// @three-ws/activity-mcp — MCP server entry point.
+//
+// Gives any AI assistant the three.ws live discovery surface over stdio:
+// • get_trending_agents — agents ranked by real chat activity (24h/7d/all)
+// • get_trending_coins — coins ranked by Oracle conviction
+// • get_holder_leaderboard — the $THREE holder board, ranked by on-chain balance
+// • get_tier_info — the $THREE holder tier ladder (thresholds + badges)
+// • get_feed_events — the site-wide activity ticker, newest-first
+//
+// A thin wrapper over the PUBLIC three.ws API. No keys, no signer, no payment —
+// point THREE_WS_BASE at a deployment and go.
+//
+// Run standalone:
+// node packages/activity-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 getTrendingAgents } from './tools/get-trending-agents.js';
+import { def as getTrendingCoins } from './tools/get-trending-coins.js';
+import { def as getHolderLeaderboard } from './tools/get-holder-leaderboard.js';
+import { def as getTierInfo } from './tools/get-tier-info.js';
+import { def as getFeedEvents } from './tools/get-feed-events.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 = [
+ getTrendingAgents,
+ getTrendingCoins,
+ getHolderLeaderboard,
+ getTierInfo,
+ getFeedEvents,
+];
+
+/**
+ * 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: 'activity-mcp', title: 'three.ws Activity', version: PKG_VERSION },
+ {
+ capabilities: { tools: {} },
+ instructions:
+ 'three.ws Activity MCP — the "what\'s hot right now" surface. get_trending_agents ranks ' +
+ 'agents by real chat activity over a 24h/7d/all window (optionally blending wallet-trust ' +
+ 'reputation). get_trending_coins ranks coins by the Oracle\'s conviction score — runtime ' +
+ 'launch-directory discovery data, not financial advice. get_holder_leaderboard returns the ' +
+ '$THREE holder board ranked by on-chain balance, with each holder\'s tier and an optional ' +
+ '"you are #N" lookup for a given wallet. get_tier_info returns the $THREE holder tier ladder ' +
+ '(thresholds + badge accents). get_feed_events returns the site-wide activity ticker — coin ' +
+ 'buys, agent deploys, level-ups, payments, and more, newest-first. $THREE is the only coin ' +
+ 'three.ws ranks holders for. All data comes live from the public three.ws API — no API key, ' +
+ 'signer, or payment required. Every tool is read-only.',
+ },
+ );
+
+ for (const tool of TOOLS) {
+ server.registerTool(
+ tool.name,
+ {
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ annotations: tool.annotations,
+ },
+ async (args, extra) => {
+ try {
+ const result = await tool.handler(args, extra);
+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
+ return { content: [{ type: 'text', text }] };
+ } catch (err) {
+ const payload = {
+ ok: false,
+ error: err?.code || 'unhandled',
+ message: err?.message || String(err),
+ ...(err?.status ? { status: err.status } : {}),
+ };
+ return {
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
+ isError: true,
+ };
+ }
+ },
+ );
+ }
+
+ return server;
+}
+
+async function main() {
+ const server = buildServer();
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ console.error(`[activity-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('[activity-mcp] fatal:', err);
+ process.exit(1);
+ });
+}
diff --git a/packages/activity-mcp/test/registration.test.mjs b/packages/activity-mcp/test/registration.test.mjs
new file mode 100644
index 000000000..697d1525f
--- /dev/null
+++ b/packages/activity-mcp/test/registration.test.mjs
@@ -0,0 +1,71 @@
+// Tool-surface invariants for @three-ws/activity-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/activity-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_trending_agents',
+ 'get_trending_coins',
+ 'get_holder_leaderboard',
+ 'get_tier_info',
+ 'get_feed_events',
+];
+
+test('exactly the expected tools are registered', () => {
+ assert.equal(TOOLS.length, 5);
+ assert.deepEqual(new Set(TOOLS.map((t) => t.name)), new Set(EXPECTED_NAMES));
+});
+
+test('every tool has a title, description, input schema and complete annotations', () => {
+ for (const tool of TOOLS) {
+ assert.equal(typeof tool.title, 'string', `${tool.name} is missing a title`);
+ assert.ok(tool.title.length > 0, `${tool.name} has an empty title`);
+ assert.equal(typeof tool.description, 'string', `${tool.name} is missing a description`);
+ assert.ok(tool.description.length > 0, `${tool.name} has an empty description`);
+ assert.ok(tool.inputSchema && typeof tool.inputSchema === 'object', `${tool.name} is missing inputSchema`);
+ assert.equal(typeof tool.handler, 'function', `${tool.name} is missing a handler`);
+ assert.ok(tool.annotations, `${tool.name} is missing MCP ToolAnnotations`);
+ assert.equal(typeof tool.annotations.readOnlyHint, 'boolean', `${tool.name} must set readOnlyHint`);
+ assert.equal(typeof tool.annotations.idempotentHint, 'boolean', `${tool.name} must set idempotentHint`);
+ assert.equal(typeof tool.annotations.openWorldHint, 'boolean', `${tool.name} must set openWorldHint`);
+ }
+});
+
+test('every tool is a read-only, live-data query', () => {
+ for (const tool of TOOLS) {
+ 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 discovery data is never idempotent — rankings, the board, and the
+ // feed all move between calls.
+ assert.equal(tool.annotations.idempotentHint, false, `${tool.name} reads live data, not idempotent`);
+ }
+});
+
+test('read-only tools do not set destructiveHint (spec ignores it when readOnlyHint is true)', () => {
+ for (const tool of TOOLS) {
+ assert.equal(
+ tool.annotations.destructiveHint,
+ undefined,
+ `${tool.name} is read-only — destructiveHint should be omitted`,
+ );
+ }
+});
+
+test('buildServer registers every tool with its annotations, without a signer', () => {
+ const server = buildServer();
+ const registered = server._registeredTools;
+ assert.ok(registered, 'McpServer should expose its tool registry');
+ for (const tool of TOOLS) {
+ const entry = registered[tool.name];
+ assert.ok(entry, `${tool.name} not registered on the server`);
+ assert.deepEqual(entry.annotations, tool.annotations, `${tool.name} annotations must survive registration`);
+ }
+});
diff --git a/packages/agenc-mcp/src/tools/link-agent.js b/packages/agenc-mcp/src/tools/link-agent.js
new file mode 100644
index 000000000..776a53c2f
--- /dev/null
+++ b/packages/agenc-mcp/src/tools/link-agent.js
@@ -0,0 +1,75 @@
+// `link_agent` — resolve a three.ws identity to its canonical AgenC agent id
+// and check whether that identity is registered on-chain. Read-only: it derives
+// + looks up, it does not itself register or sign anything.
+//
+// Wraps POST /api/agenc/link. Give it any one of: an ERC-8004 agent id, an
+// MPL-Core asset, or a three.ws handle. The bridge computes the deterministic
+// AgenC agentId + PDA via the identity bridge, builds the metadata URI three.ws
+// would publish, and reports whether that PDA already holds a registration.
+
+import { z } from 'zod';
+
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'link_agent',
+ title: 'Link a three.ws identity to its AgenC agent id',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Resolve a three.ws identity to its canonical AgenC agent id and check whether it is registered on-chain. Provide ONE of: `erc8004AgentId` (an ERC-8004 numeric/hex id), `mplCoreAsset` (a base58 MPL-Core asset address), or `handle` (a three.ws handle). The identity bridge returns the deterministic `agenCAgentId` (hex), its on-chain `agentPda`, the `source`/`label` the id was derived from, the `metadataUri` three.ws would publish for it, and `registered:true|false`. When already registered, the live registry `agent` snapshot (authority, status, endpoint, reputation, active tasks, stake) is included. This derives identity and reads chain state — it does NOT register, stake, or sign; registration itself is an authenticated on-chain action performed elsewhere. Read-only; registration state is live, so results are not idempotent. Free, no key required.',
+ inputSchema: {
+ erc8004AgentId: z
+ .union([z.string(), z.number()])
+ .optional()
+ .describe('ERC-8004 agent id (numeric or hex). Provide exactly one identity input.'),
+ mplCoreAsset: z
+ .string()
+ .min(32)
+ .max(44)
+ .optional()
+ .describe('Base58 MPL-Core asset address backing the agent identity.'),
+ handle: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('three.ws handle to resolve to an AgenC agent id.'),
+ baseUrl: z
+ .string()
+ .url()
+ .optional()
+ .describe('Base URL used to build the published metadata URI (default https://three.ws).'),
+ cluster: z
+ .enum(['mainnet', 'devnet'])
+ .default('mainnet')
+ .describe('Solana cluster to check registration on (default mainnet).'),
+ },
+ async handler(args) {
+ const erc8004AgentId = args?.erc8004AgentId ?? null;
+ const mplCoreAsset = args?.mplCoreAsset ? String(args.mplCoreAsset).trim() : null;
+ const handle = args?.handle ? String(args.handle).trim() : null;
+ if (erc8004AgentId === null && !mplCoreAsset && !handle) {
+ throw Object.assign(
+ new Error('provide one identity input: erc8004AgentId, mplCoreAsset, or handle'),
+ { code: 'validation_error' },
+ );
+ }
+ const cluster = args?.cluster === 'devnet' ? 'devnet' : 'mainnet';
+ const body = { erc8004AgentId, mplCoreAsset, handle, cluster };
+ if (args?.baseUrl) body.baseUrl = String(args.baseUrl).trim();
+
+ const data = await apiRequest('/api/agenc/link', { method: 'POST', body });
+ return {
+ ok: true,
+ cluster: data?.cluster ?? cluster,
+ programId: data?.programId ?? null,
+ source: data?.source ?? null,
+ label: data?.label ?? null,
+ agenCAgentId: data?.agenCAgentId ?? null,
+ agentPda: data?.agentPda ?? null,
+ metadataUri: data?.metadataUri ?? null,
+ registered: data?.registered ?? false,
+ agent: data?.agent ?? null,
+ fetchedAt: data?.fetchedAt ?? null,
+ };
+ },
+};
diff --git a/packages/audio-mcp/LICENSE b/packages/audio-mcp/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/audio-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/audio-mcp/src/config.js b/packages/audio-mcp/src/config.js
new file mode 100644
index 000000000..611c01057
--- /dev/null
+++ b/packages/audio-mcp/src/config.js
@@ -0,0 +1,46 @@
+// Centralized env + HTTP base for the audio MCP.
+//
+// This server is a thin wrapper over the three.ws audio/animation pipeline:
+// • /api/tts/speak — text-to-speech (free NVIDIA Magpie, OpenAI backstop)
+// • /api/asr — speech-to-text (free NVIDIA Riva)
+// • /api/a2f — audio-to-face lipsync (free NVIDIA Audio2Face-3D)
+// • /api/mocap/* — the stored motion-capture clip library (face/pose/hand)
+//
+// It signs nothing on-chain. The endpoints are metered: anonymous callers get a
+// tight per-IP budget, authenticated callers a higher per-user one — and the
+// mocap clip library only returns your private clips when you authenticate. So
+// the one optional secret is a three.ws API key (bearer token); without it the
+// server still works against everything public, exactly like intel-mcp.
+
+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(/\/+$/, '');
+
+// Optional three.ws API key (bearer token). When set it is sent as
+// `Authorization: Bearer <key>` on every call, which raises the metered TTS/ASR/
+// A2F rate limits and unlocks your own private/unlisted mocap clips. Leave it
+// unset to use the public surface anonymously.
+export const THREE_WS_API_KEY = env('THREE_WS_API_KEY');
+
+// Per-request timeout (ms). Audio synthesis, recognition, and Audio2Face are
+// real upstream model calls (gRPC to NVIDIA NIM, OpenAI on the backstop) — a
+// long line of TTS or a 4-minute ASR clip needs headroom, so this is generous.
+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/audio-mcp';
diff --git a/packages/billing-mcp/src/tools/billing-summary.js b/packages/billing-mcp/src/tools/billing-summary.js
new file mode 100644
index 000000000..99de70fff
--- /dev/null
+++ b/packages/billing-mcp/src/tools/billing-summary.js
@@ -0,0 +1,52 @@
+// `get_billing_summary` — your plan, its quotas, and current usage against them.
+// Account-scoped (session). Read-only.
+//
+// Wraps GET /api/billing/summary. The route resolves the caller from the
+// three.ws session and returns the plan tier, the quota ceilings for that tier,
+// and the live usage roll-ups counted against them (avatars + storage bytes,
+// agents, MCP tool calls in the last 24h, LLM calls this month). This is the
+// "how much of my plan have I used?" call.
+
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'get_billing_summary',
+ title: 'My plan, quotas, and current usage',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Your account\'s plan tier, the quota ceilings for that tier, and live usage measured against them — the ' +
+ '"how much of my plan is left?" call. Returns `plan` (e.g. free | pro), `quotas` (max_avatars, ' +
+ 'max_bytes_per_avatar, max_total_bytes, mcp_calls_per_day — or null when the tier has no metered ceilings), ' +
+ 'and `usage` (avatar_count, total_bytes of avatar storage, agent_count, mcp_calls_24h tool calls in the last ' +
+ '24 hours, llm_calls_month LLM calls since the start of this UTC month). Each tool returns a `remaining` map ' +
+ 'computed from quotas − usage so an agent can see headroom at a glance. Resolved from your three.ws session; ' +
+ 'requires THREE_WS_SESSION. Read-only.',
+ inputSchema: {},
+ async handler() {
+ const data = await apiRequest('/api/billing/summary', { auth: true });
+ const quotas = data?.quotas ?? null;
+ const usage = data?.usage ?? {};
+
+ // Headroom: quota − usage, clamped at 0. null quota → unmetered (null remaining).
+ const left = (cap, used) =>
+ cap === null || cap === undefined ? null : Math.max(0, Number(cap) - Number(used || 0));
+
+ return {
+ ok: true,
+ plan: data?.plan ?? 'free',
+ quotas,
+ usage: {
+ avatar_count: usage.avatar_count ?? 0,
+ total_bytes: usage.total_bytes ?? 0,
+ agent_count: usage.agent_count ?? 0,
+ mcp_calls_24h: usage.mcp_calls_24h ?? 0,
+ llm_calls_month: usage.llm_calls_month ?? 0,
+ },
+ remaining: {
+ avatars: left(quotas?.max_avatars, usage.avatar_count),
+ total_bytes: left(quotas?.max_total_bytes, usage.total_bytes),
+ mcp_calls_today: left(quotas?.mcp_calls_per_day, usage.mcp_calls_24h),
+ },
+ };
+ },
+};
diff --git a/packages/billing-mcp/src/tools/query-usage.js b/packages/billing-mcp/src/tools/query-usage.js
new file mode 100644
index 000000000..fe7213815
--- /dev/null
+++ b/packages/billing-mcp/src/tools/query-usage.js
@@ -0,0 +1,64 @@
+// `query_usage` — your metered usage rolled up into an invoice statement for a
+// billing period. Account-scoped (session). Read-only.
+//
+// Wraps GET /api/billing/invoices. The route sums your usage_events ledger over
+// the period into per-action line items (count, units, gross/fee/net in USDC) and
+// statement totals, each line tracing to a real settlement, plus a reconciliation
+// summary (do all charges map to a real on-chain settlement?). Defaults to the
+// current UTC calendar month; accepts a `period=YYYY-MM` or an explicit from/to.
+
+import { z } from 'zod';
+
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'query_usage',
+ title: 'My metered usage / invoice statement for a period',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Your metered usage rolled up into an invoice statement for a billing period — what you were charged for, ' +
+ 'broken down by action. Returns `period_label` + `period` ({from,to} ISO), `line_items` (one per billed ' +
+ 'action: action id, human label, count, units, gross_usd, fee_usd, gross/fee/net atomics in USDC 6dp, ' +
+ 'discount_bps holder-tier discount applied), `totals` (charge_count, gross_usd, fee_usd, net_usd, currency), ' +
+ 'and `reconciliation` (total / reconciled / unreconciled / all_reconciled — whether every charge maps to a ' +
+ 'real settlement). Defaults to the current UTC calendar month. Pass `period` (YYYY-MM) for a calendar month, ' +
+ 'or `from`/`to` (ISO-8601) for an explicit window — `period` wins if both are given. For a downloadable CSV ' +
+ 'of the same line items use export_billing_history. Requires THREE_WS_SESSION. Read-only.',
+ inputSchema: {
+ period: z
+ .string()
+ .regex(/^\d{4}-\d{2}$/, 'period must be YYYY-MM')
+ .optional()
+ .describe('A calendar month as YYYY-MM (e.g. 2026-06). Takes precedence over from/to. Omit for the current month.'),
+ from: z
+ .string()
+ .optional()
+ .describe('Window start, ISO-8601 (e.g. 2026-06-01T00:00:00Z). Ignored when `period` is set.'),
+ to: z
+ .string()
+ .optional()
+ .describe('Window end (exclusive), ISO-8601. Ignored when `period` is set.'),
+ },
+ async handler(args) {
+ const query = {};
+ if (args?.period) query.period = args.period;
+ else {
+ if (args?.from) query.from = args.from;
+ if (args?.to) query.to = args.to;
+ }
+
+ const data = await apiRequest('/api/billing/invoices', { auth: true, query });
+ const invoice = data?.invoice ?? {};
+ const lineItems = Array.isArray(invoice.line_items) ? invoice.line_items : [];
+
+ return {
+ ok: true,
+ period_label: invoice.period_label ?? null,
+ period: invoice.period ?? null,
+ line_item_count: lineItems.length,
+ line_items: lineItems,
+ totals: invoice.totals ?? null,
+ reconciliation: invoice.reconciliation ?? null,
+ };
+ },
+};
diff --git a/packages/clash-mcp/LICENSE b/packages/clash-mcp/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/clash-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/clash-mcp/src/config.js b/packages/clash-mcp/src/config.js
new file mode 100644
index 000000000..db67b1d8a
--- /dev/null
+++ b/packages/clash-mcp/src/config.js
@@ -0,0 +1,44 @@
+// Centralized env + HTTP base for the Coin Clash MCP.
+//
+// Reads (state, leaderboard) wrap the PUBLIC three.ws Coin Clash API and need
+// no secret — point THREE_WS_BASE at a deployment and go. Writes (enlist,
+// rally) are wallet-scoped: the soldier must prove they hold the faction coin
+// by signing a challenge with their Solana key. That key is supplied per-call
+// via the `secret` argument, or once via SOLANA_SECRET_KEY in the server
+// environment. We never embed a default key and never sign on anyone's behalf
+// without their key.
+
+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 state read does live pump.fun price + community
+// fan-outs, and enlist-verify reads on-chain balances — 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/clash-mcp';
+
+// Optional default signer for the write tools (enlist_faction, rally_faction).
+// A base58-encoded 64-byte Solana secret key. Per-call `secret` arguments
+// override this. Treat it like cash — it controls the wallet whose coin
+// holdings gate enlistment. Absent → reads still work; writes require a `secret`
+// arg instead.
+export const SOLANA_DEFAULT_SECRET =
+ env('SOLANA_SECRET_KEY') || env('CLASH_SOLANA_SECRET') || '';
diff --git a/packages/clash-mcp/src/lib/api.js b/packages/clash-mcp/src/lib/api.js
new file mode 100644
index 000000000..4b01992d6
--- /dev/null
+++ b/packages/clash-mcp/src/lib/api.js
@@ -0,0 +1,66 @@
+// 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 } 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/intel/smart-money`).
+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]
+ * @returns {Promise<any>} Parsed JSON response.
+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),
+ * and on upstream errors `.status` + `.body`.
+ */
+export async function apiRequest(path, { method = 'GET', query, body } = {}) {
+ const url = new URL(`${THREE_WS_BASE}${path}`);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') continue;
+ url.searchParams.set(key, String(value));
+ }
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
+
+ let res;
+ try {
+ res = await fetch(url, {
+ method,
+ headers: {
+ accept: 'application/json',
+ 'user-agent': USER_AGENT,
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ if (err?.name === 'AbortError') {
+ throw Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), {
+ code: 'timeout',
+ });
+ }
+ throw Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), {
+ code: 'network_error',
+ });
+ }
+ clearTimeout(timer);
+
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!res.ok) {
+ 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/clash-mcp/src/lib/signer.js b/packages/clash-mcp/src/lib/signer.js
new file mode 100644
index 000000000..004dcf612
--- /dev/null
+++ b/packages/clash-mcp/src/lib/signer.js
@@ -0,0 +1,67 @@
+// Solana message signing for the Coin Clash write path.
+//
+// Enlisting is a Sign-In-with-Solana style proof: the server hands back a
+// challenge string bound to a wallet + faction, and the soldier signs it with
+// the wallet's ed25519 key. The backend verifies the signature, then confirms a
+// live on-chain holding of the faction coin before issuing a war pass.
+//
+// We sign the raw UTF-8 message bytes (ed25519, detached) and return a base58
+// signature — exactly what api/_lib/siws.js#verifySiwsSignature accepts. No RPC,
+// no transaction: this module only proves key ownership. The on-chain balance
+// check happens server-side.
+
+import nacl from 'tweetnacl';
+import bs58 from 'bs58';
+
+const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;
+const bs58encode = bs58.default ? bs58.default.encode : bs58.encode;
+
+import { SOLANA_DEFAULT_SECRET } from '../config.js';
+
+/**
+ * Load a signer from a base58-encoded 64-byte Solana secret key. Falls back to
+ * SOLANA_SECRET_KEY (SOLANA_DEFAULT_SECRET) when no per-call secret is given.
+ * @param {string} [secret] base58 secret key
+ * @returns {{ wallet: string, secretKey: Uint8Array }}
+ */
+export function loadSigner(secret) {
+ const trimmed = String(secret || SOLANA_DEFAULT_SECRET || '').trim();
+ if (!trimmed) {
+ throw Object.assign(
+ new Error(
+ 'Solana secret required to enlist or rally. Pass `secret` (base58) in the tool call, ' +
+ 'or set SOLANA_SECRET_KEY in the MCP server environment.',
+ ),
+ { code: 'no_signer' },
+ );
+ }
+
+ let bytes;
+ try {
+ bytes = bs58decode(trimmed);
+ } catch {
+ throw Object.assign(new Error('Solana secret is not valid base58.'), { code: 'invalid_secret' });
+ }
+ if (bytes.length !== 64) {
+ throw Object.assign(
+ new Error(`Solana secret must decode to 64 bytes (got ${bytes.length}).`),
+ { code: 'invalid_secret' },
+ );
+ }
+
+ const pair = nacl.sign.keyPair.fromSecretKey(Uint8Array.from(bytes));
+ return { wallet: bs58encode(pair.publicKey), secretKey: pair.secretKey };
+}
+
+/**
+ * Sign a challenge message with the loaded signer's key.
+ * @param {string} message the exact challenge text returned by the enlist call
+ * @param {string} [secret] base58 secret key (else env default)
+ * @returns {{ wallet: string, signature: string }} base58 detached signature
+ */
+export function signMessage(message, secret) {
+ const { wallet, secretKey } = loadSigner(secret);
+ const msgBytes = new TextEncoder().encode(String(message));
+ const sig = nacl.sign.detached(msgBytes, secretKey);
+ return { wallet, signature: bs58encode(sig) };
+}
diff --git a/packages/kol-mcp/src/index.js b/packages/kol-mcp/src/index.js
new file mode 100644
index 000000000..e10db1911
--- /dev/null
+++ b/packages/kol-mcp/src/index.js
@@ -0,0 +1,115 @@
+#!/usr/bin/env node
+// @three-ws/kol-mcp — MCP server entry point.
+//
+// The "track one smart trader" surface. Where intel-mcp ranks the whole KOL set
+// (kol_leaderboard) and shows everyone's trades on a mint (kol_trades), this
+// server is the per-wallet deep dive: one tracked trader's portfolio P&L and
+// their own trades on a given token, for copy/analysis decisions.
+// • get_wallet_portfolio — a KOL wallet's realized/unrealized P&L card
+// • get_wallet_trades — that wallet's recent trades on a given mint
+//
+// A thin wrapper over the PUBLIC three.ws KOL API. No keys, no signer, no
+// payment on the client — the Birdeye key that backs the portfolio P&L lives
+// server-side on three.ws. Point THREE_WS_BASE at a deployment and go.
+//
+// Run standalone:
+// node packages/kol-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 getWalletPortfolio } from './tools/get-wallet-portfolio.js';
+import { def as getWalletTrades } from './tools/get-wallet-trades.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 = [getWalletPortfolio, getWalletTrades];
+
+/**
+ * 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: 'kol-mcp', title: 'three.ws KOL', version: PKG_VERSION },
+ {
+ capabilities: { tools: {} },
+ instructions:
+ 'three.ws KOL MCP — track one smart trader. get_wallet_portfolio pulls a single ' +
+ "tracked KOL wallet's live portfolio P&L card: realized P&L, unrealized (open-position) " +
+ 'P&L, win rate, total trades, and its largest holding. get_wallet_trades returns that ' +
+ "same wallet's recent buys/sells of a specific mint — side, SOL size, price, USD value, " +
+ 'and timing, newest first. This is the per-wallet deep dive; to rank the whole KOL set or ' +
+ 'see every wallet\'s trades on a mint, use the intel-mcp server (kol_leaderboard, ' +
+ 'kol_trades). All data comes live from the public three.ws KOL API — no API key, signer, ' +
+ 'or payment required on the client. Every tool is read-only.',
+ },
+ );
+
+ for (const tool of TOOLS) {
+ server.registerTool(
+ tool.name,
+ {
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ annotations: tool.annotations,
+ },
+ async (args, extra) => {
+ try {
+ const result = await tool.handler(args, extra);
+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
+ return { content: [{ type: 'text', text }] };
+ } catch (err) {
+ const payload = {
+ ok: false,
+ error: err?.code || 'unhandled',
+ message: err?.message || String(err),
+ ...(err?.status ? { status: err.status } : {}),
+ };
+ return {
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
+ isError: true,
+ };
+ }
+ },
+ );
+ }
+
+ return server;
+}
+
+async function main() {
+ const server = buildServer();
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ console.error(`[kol-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('[kol-mcp] fatal:', err);
+ process.exit(1);
+ });
+}
diff --git a/packages/kol-mcp/src/tools/get-wallet-trades.js b/packages/kol-mcp/src/tools/get-wallet-trades.js
new file mode 100644
index 000000000..8b300f465
--- /dev/null
+++ b/packages/kol-mcp/src/tools/get-wallet-trades.js
@@ -0,0 +1,62 @@
+// `get_wallet_trades` — one KOL wallet's recent trades on a given mint. Read-only.
+//
+// Wraps GET /api/kol/trades?mint=<mint>&limit=100, then narrows the cross-wallet
+// feed down to a single trader. The three.ws trade feed is mint-keyed (it scans
+// every tracked KOL wallet for activity on one mint via Helius), so a per-wallet
+// view is that feed filtered to the wallet you care about. We always pull the
+// upstream max so the wallet's own slice is as complete as the feed allows.
+
+import { z } from 'zod';
+
+import { apiRequest } from '../lib/api.js';
+
+const UPSTREAM_MAX = 100;
+
+export const def = {
+ name: 'get_wallet_trades',
+ title: "A KOL wallet's trades on a mint",
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Get one specific KOL trader\'s recent buys/sells of a given mint. The three.ws trade ' +
+ 'feed is scanned for that mint across all tracked wallets and narrowed to the wallet you ' +
+ 'pass, so you see exactly how that trader is positioning in that token — side (buy/sell), ' +
+ 'SOL size, token amount, per-trade price, USD value, and timestamp, newest first. Use it ' +
+ 'to inspect a single smart trader\'s moves before copying. For every tracked wallet\'s ' +
+ 'trades on a mint (not just one), use intel-mcp `kol_trades`. Read-only live data.',
+ inputSchema: {
+ wallet: z
+ .string()
+ .min(1)
+ .describe('The KOL wallet address whose trades to return.'),
+ mint: z
+ .string()
+ .min(1)
+ .describe('The token mint address to scan that wallet\'s activity on.'),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(100)
+ .optional()
+ .describe('Max number of this wallet\'s trades to return (1–100, default 20).'),
+ },
+ async handler(args) {
+ const wallet = String(args?.wallet ?? '').trim();
+ const mint = String(args?.mint ?? '').trim();
+ const limit = Math.min(100, Math.max(1, Number(args?.limit) || 20));
+
+ const data = await apiRequest('/api/kol/trades', {
+ query: { mint, limit: UPSTREAM_MAX },
+ });
+ const all = Array.isArray(data?.trades) ? data.trades : [];
+ const trades = all.filter((t) => t?.wallet === wallet).slice(0, limit);
+
+ return {
+ ok: true,
+ wallet,
+ mint: data?.mint ?? mint,
+ count: trades.length,
+ trades,
+ };
+ },
+};
diff --git a/packages/loom-mcp/LICENSE b/packages/loom-mcp/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/loom-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/loom-mcp/src/config.js b/packages/loom-mcp/src/config.js
new file mode 100644
index 000000000..7188b0959
--- /dev/null
+++ b/packages/loom-mcp/src/config.js
@@ -0,0 +1,33 @@
+// Centralized env + HTTP base for the loom MCP.
+//
+// This server is a thin wrapper over the PUBLIC three.ws Loom API (/api/loom) —
+// the community 3D-creation gallery. The feed and single-creation reads are fully
+// public; submitting a creation is also public, gated server-side only by an IP
+// rate limit (no key, no signer, no account). The only knobs are which deployment
+// to talk to and how long to wait. Every creation comes live from the endpoint.
+
+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 that serves /api/loom. 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 light reads + a small JSON POST, so a
+// modest default is plenty while still riding 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;
+})();
+
+// Identifies this client to the API in request logs.
+export const USER_AGENT = '@three-ws/loom-mcp';
diff --git a/packages/loom-mcp/src/lib/api.js b/packages/loom-mcp/src/lib/api.js
new file mode 100644
index 000000000..4b01992d6
--- /dev/null
+++ b/packages/loom-mcp/src/lib/api.js
@@ -0,0 +1,66 @@
+// 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 } 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/intel/smart-money`).
+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]
+ * @returns {Promise<any>} Parsed JSON response.
+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),
+ * and on upstream errors `.status` + `.body`.
+ */
+export async function apiRequest(path, { method = 'GET', query, body } = {}) {
+ const url = new URL(`${THREE_WS_BASE}${path}`);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') continue;
+ url.searchParams.set(key, String(value));
+ }
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
+
+ let res;
+ try {
+ res = await fetch(url, {
+ method,
+ headers: {
+ accept: 'application/json',
+ 'user-agent': USER_AGENT,
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ if (err?.name === 'AbortError') {
+ throw Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), {
+ code: 'timeout',
+ });
+ }
+ throw Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), {
+ code: 'network_error',
+ });
+ }
+ clearTimeout(timer);
+
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!res.ok) {
+ 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/loom-mcp/src/lib/viewer.js b/packages/loom-mcp/src/lib/viewer.js
new file mode 100644
index 000000000..2d112f521
--- /dev/null
+++ b/packages/loom-mcp/src/lib/viewer.js
@@ -0,0 +1,90 @@
+// Viewer + embed helpers for Loom creations, and the GLB-URL guard.
+//
+// These mirror two real platform sources so an agent sees the SAME shapes the
+// three.ws web app uses — never a divergent guess:
+// • the host allowlist + validation in api/loom.js (validateGlbUrl)
+// • the /forge/embed URL + iframe snippet in src/forge-embed-snippets.js
+//
+// A Loom creation is a forged GLB. The canonical way to preview one is the
+// zero-dependency three.ws viewer page at /forge/embed?src=<glb> (orbit + AR +
+// branding), which is exactly what we hand back as viewer_url.
+
+import { THREE_WS_BASE } from '../config.js';
+
+// Hosts a forged GLB can legitimately live on — kept in lockstep with
+// ALLOWED_GLB_HOST_SUFFIXES in api/loom.js. The server is the source of truth and
+// rejects anything else; we check here too so submit_creation fails fast with a
+// clear message instead of a round-trip 400.
+export const ALLOWED_GLB_HOST_SUFFIXES = [
+ 'three.ws',
+ 'r2.dev',
+ 'cloudflarestorage.com',
+ 'replicate.delivery',
+ 'githubusercontent.com',
+];
+
+/**
+ * Validate a model URL is an https URL on an allowlisted host. Returns the
+ * normalized href on success, or null if it fails any check — same contract as
+ * the server's validateGlbUrl so client and server never disagree.
+ */
+export function validateGlbUrl(raw) {
+ if (typeof raw !== 'string' || !raw.trim()) return null;
+ let url;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ return null;
+ }
+ if (url.protocol !== 'https:') return null;
+ const host = url.hostname.toLowerCase();
+ const ok = ALLOWED_GLB_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
+ return ok ? url.href : null;
+}
+
+function escAttr(s) {
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/"/g, '&quot;');
+}
+
+/** The /forge/embed viewer URL for a GLB, optionally carrying a title. */
+export function viewerUrl(glbUrl, title) {
+ if (!glbUrl) return null;
+ const q = new URLSearchParams({ src: glbUrl });
+ if (title) q.set('title', String(title).slice(0, 120));
+ return `${THREE_WS_BASE}/forge/embed?${q.toString()}`;
+}
+
+/** Open Graph / social card image for a GLB (same endpoint the web app uses). */
+export function ogImageUrl(glbUrl) {
+ if (!glbUrl) return null;
+ return `${THREE_WS_BASE}/api/avatar-og?src=${encodeURIComponent(glbUrl)}`;
+}
+
+/** A paste-ready iframe embed for the creation — matches forge-embed-snippets.js. */
+export function iframeSnippet(glbUrl, title, { width = 640, height = 360 } = {}) {
+ if (!glbUrl) return null;
+ const src = viewerUrl(glbUrl, title);
+ return (
+ `<iframe src="${escAttr(src)}" width="${width}" height="${height}" ` +
+ `style="border:0;border-radius:14px;max-width:100%" ` +
+ `allow="xr-spatial-tracking; fullscreen" loading="lazy" ` +
+ `title="${escAttr(title || '3D model forged on three.ws')}"></iframe>`
+ );
+}
+
+/**
+ * Decorate a raw creation record from /api/loom with the viewer URL, OG image,
+ * and a ready-to-embed iframe — so every read tool returns something an MCP
+ * client can preview inline without a second lookup. Returns null for a missing
+ * record; passes through unknown fields untouched.
+ */
+export function decorateCreation(rec) {
+ if (!rec || typeof rec !== 'object') return null;
+ const glb = typeof rec.glbUrl === 'string' ? rec.glbUrl : null;
+ return {
+ ...rec,
+ viewer_url: glb ? viewerUrl(glb, rec.prompt) : null,
+ og_image_url: glb ? ogImageUrl(glb) : null,
+ iframe_snippet: glb ? iframeSnippet(glb, rec.prompt) : null,
+ };
+}
diff --git a/packages/tutor-mcp/package.json b/packages/tutor-mcp/package.json
new file mode 100644
index 000000000..219d3036b
--- /dev/null
+++ b/packages/tutor-mcp/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@three-ws/tutor-mcp",
+ "version": "0.1.0",
+ "mcpName": "io.github.nirholas/tutor-mcp",
+ "description": "three.ws Pay-As-You-Learn tutor ledger from any AI agent — read a learning session's itemized running tab and close it for an attested invoice. Free, no key, no signer; answering questions is the paid action handled elsewhere.",
+ "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/tutor-mcp"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "keywords": [
+ "mcp",
+ "three.ws",
+ "tutor",
+ "learning",
+ "session",
+ "ledger",
+ "invoice",
+ "billing"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "src",
+ "server.json",
+ "README.md",
+ "LICENSE"
+ ],
+ "bin": {
+ "tutor-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/tutor-mcp/src/index.js b/packages/tutor-mcp/src/index.js
new file mode 100644
index 000000000..2cea6df70
--- /dev/null
+++ b/packages/tutor-mcp/src/index.js
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+// @three-ws/tutor-mcp — MCP server entry point.
+//
+// Gives any AI assistant the three.ws Pay-As-You-Learn tutor ledger over stdio:
+// • load_session — read a session's itemized running tab (free, read-only)
+// • close_session — finalize the session + return its attested invoice (free)
+//
+// A thin wrapper over the three.ws tutor session API. Sessions are addressed by
+// an opaque sessionId — no key, no signer. Answering questions is the paid
+// action (handled elsewhere); viewing the tab and closing the session are free,
+// so a learner is never charged to see what they owe or to end the session.
+//
+// Run standalone:
+// node packages/tutor-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 loadSession } from './tools/load-session.js';
+import { def as closeSession } from './tools/close-session.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 = [
+ loadSession,
+ closeSession,
+];
+
+/**
+ * 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: 'tutor-mcp', title: 'three.ws Tutor', version: PKG_VERSION },
+ {
+ capabilities: { tools: {} },
+ instructions:
+ 'three.ws Tutor MCP — manage the ledger for a Pay-As-You-Learn tutoring session. ' +
+ 'load_session reads a session\'s itemized running tab by sessionId: one line item per ' +
+ 'answered question (text, level, output tokens, per-item cost in USDC atomics + a "$x.xxxxxx" ' +
+ 'string, timestamp), the status (open/closed), questionCount, and the running total. ' +
+ 'close_session finalizes the session and returns its attested invoice — it seals the ledger ' +
+ 'with a SHA-256 attestation, after which no further questions can be billed to it. Answering ' +
+ 'questions is the paid action and happens elsewhere; both tools here are FREE — viewing the ' +
+ 'tab and closing the session never charge the learner, and closing moves no funds. All data ' +
+ 'comes live from the three.ws tutor API — no API key or signer required.',
+ },
+ );
+
+ 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(`[tutor-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('[tutor-mcp] fatal:', err);
+ process.exit(1);
+ });
+}
diff --git a/packages/vision-mcp/src/tools/analyze-image.js b/packages/vision-mcp/src/tools/analyze-image.js
new file mode 100644
index 000000000..2dfa27624
--- /dev/null
+++ b/packages/vision-mcp/src/tools/analyze-image.js
@@ -0,0 +1,70 @@
+// `analyze_image` — ask a question about an image and get a grounded answer.
+// Read-only.
+//
+// Wraps POST /api/vision with the caller's own prompt. The platform runs the
+// request against its free-first VLM chain (NVIDIA NIM lanes, automatic paid
+// backstop) and returns the model's text plus which provider/model served it.
+
+import { z } from 'zod';
+
+import { apiRequest } from '../lib/api.js';
+import { buildVisionBody, ACCEPTED_IMAGE_TYPES } from '../lib/image.js';
+
+export const def = {
+ name: 'analyze_image',
+ title: 'Analyze an image against a prompt',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Let the agent SEE an image and answer a question about it. Supply the image as `imageUrl` (a public ' +
+ 'https URL the vision server fetches) OR `image` (raw base64 / a data: URI), and a `prompt` describing ' +
+ 'what to extract — e.g. "What objects are in this scene?", "Read the text in this screenshot", "Is this ' +
+ 'avatar render rigged correctly?". Returns the model\'s answer as `text`, plus the `provider` and `model` ' +
+ 'that served it (a free NVIDIA NIM lane when available, an automatic paid backstop otherwise — the caller ' +
+ 'never pays). Analysis only: it does not store or mutate anything. Accepts JPEG, PNG, WebP, or GIF up to ' +
+ '12 MB; base64 inputs are size-checked before upload.',
+ inputSchema: {
+ prompt: z
+ .string()
+ .min(1)
+ .max(2000)
+ .describe('The question or instruction about the image (what to extract, read, classify, or critique).'),
+ imageUrl: z
+ .string()
+ .url()
+ .optional()
+ .describe('Public https URL of the image to analyze. Provide this OR `image`, not both.'),
+ image: z
+ .string()
+ .optional()
+ .describe('The image as raw base64 or a `data:image/...;base64,...` URI. Provide this OR `imageUrl`, not both.'),
+ imageType: z
+ .enum(ACCEPTED_IMAGE_TYPES)
+ .optional()
+ .describe('MIME type of a raw base64 `image` (ignored for data URIs / `imageUrl`). Defaults to image/jpeg.'),
+ maxTokens: z
+ .number()
+ .int()
+ .min(16)
+ .max(2048)
+ .optional()
+ .describe('Maximum tokens in the answer (16–2048). Higher = longer, more detailed reads. Default 512.'),
+ },
+ async handler(args) {
+ const { body, source } = buildVisionBody({
+ imageUrl: args?.imageUrl,
+ image: args?.image,
+ imageType: args?.imageType,
+ prompt: args?.prompt,
+ maxTokens: args?.maxTokens,
+ });
+ const data = await apiRequest('/api/vision', { method: 'POST', body });
+ return {
+ ok: true,
+ text: typeof data?.text === 'string' ? data.text : '',
+ provider: data?.provider ?? null,
+ model: data?.model ?? null,
+ prompt: body.prompt ?? args?.prompt ?? '',
+ image_source: source,
+ };
+ },
+};