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 activity, agenc, billing, brain, kol, tutor, and vision MCP packages
nirholas69f2b9830458
diff --git a/packages/activity-mcp/LICENSE b/packages/activity-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/activity-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/activity-mcp/package.json b/packages/activity-mcp/package.jsonnew file mode 100644index 000000000..e21228ddf--- /dev/null+++ b/packages/activity-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/activity-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/activity-mcp",+ "description": "three.ws live discovery surface from any AI agent — trending agents and coins, the $THREE holder leaderboard with tiers, and the site-wide activity ticker. Read-only over the live public API. No key, no signer, no payment.",+ "type": "module",+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/activity-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "solana",+ "trending",+ "leaderboard",+ "activity-feed",+ "discovery",+ "three"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "activity-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/activity-mcp/server.json b/packages/activity-mcp/server.jsonnew file mode 100644index 000000000..0ed30da26--- /dev/null+++ b/packages/activity-mcp/server.json@@ -0,0 +1,49 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/activity-mcp",+ "title": "three.ws Activity",+ "description": "Trending agents and coins, the $THREE holder leaderboard with tiers, and the site-wide activity ticker.",+ "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/activity-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/activity-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 trending, leaderboard, and feed 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 discovery reads.",+ "format": "number",+ "isRequired": false,+ "default": "20000"+ }+ ]+ }+ ]+}diff --git a/packages/activity-mcp/src/config.js b/packages/activity-mcp/src/config.jsnew file mode 100644index 000000000..996597f44--- /dev/null+++ b/packages/activity-mcp/src/config.js@@ -0,0 +1,34 @@+// Centralized env + HTTP base for the activity MCP.+//+// This server is a thin, read-only wrapper over the PUBLIC three.ws discovery+// API (/api/trending, /api/leaderboard, /api/feed). It signs nothing and holds+// no secret — the only knobs are which deployment to talk to and how long to+// wait. Every ranking, tier, and event comes from the live endpoints; nothing+// is computed or cached here.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Base URL of the three.ws API. Override only when self-hosting or pointing at a+// preview deployment.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Per-request timeout (ms). These are live reads (trending joins over usage+// events, a Helius holder scan on a cold cache) — 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/activity-mcp';diff --git a/packages/activity-mcp/src/lib/api.js b/packages/activity-mcp/src/lib/api.jsnew file mode 100644index 000000000..4b01992d6--- /dev/null+++ b/packages/activity-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/activity-mcp/src/tools/get-feed-events.js b/packages/activity-mcp/src/tools/get-feed-events.jsnew file mode 100644index 000000000..10f8c368a--- /dev/null+++ b/packages/activity-mcp/src/tools/get-feed-events.js@@ -0,0 +1,35 @@+// `get_feed_events` — the site-wide live activity ticker. Read-only.+//+// Wraps GET /api/feed?limit=<n>. Returns recent platform events newest-first —+// the same stream that powers the on-site activity widget.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_feed_events',+ title: 'Site-wide activity feed',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "The site-wide activity ticker — recent things that just happened across three.ws, newest-first. Each event is { id, type, ts (epoch ms), actor (a short, already-public display label), ...typeSpecific }. Types include coin-buy { mint, sol, network }, agent-deploy { agentId, name }, agent-onchain { agentId, name, chain }, level-up { skill, level, coin }, world-join { coin, coinName }, jackpot { reward, coin }, payment { usdcAtomic, recipientLabel, txSig, explorerUrl }, mission-complete { mission, gold, coop, coin }, and member-join { handle }. Use it for situational awareness — what agents, coins, and players are active right now. Read-only live data; new events arrive constantly.",+ inputSchema: {+ limit: z+ .number()+ .int()+ .min(1)+ .max(100)+ .optional()+ .describe('How many recent events to return, newest-first (1–100, default 30).'),+ },+ async handler(args) {+ const limit = args?.limit;+ const data = await apiRequest('/api/feed', { query: { limit } });+ const events = Array.isArray(data?.events) ? data.events : [];+ return {+ ok: true,+ count: events.length,+ events,+ };+ },+};diff --git a/packages/activity-mcp/src/tools/get-holder-leaderboard.js b/packages/activity-mcp/src/tools/get-holder-leaderboard.jsnew file mode 100644index 000000000..eb32a18cd--- /dev/null+++ b/packages/activity-mcp/src/tools/get-holder-leaderboard.js@@ -0,0 +1,59 @@+// `get_holder_leaderboard` — the public $THREE holder leaderboard. Read-only.+//+// Wraps GET /api/leaderboard?limit=<n>&offset=<n>&wallet=<base58>. $THREE is the+// only coin three.ws ranks holders for; the board is derived from the live+// on-chain holder set.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_holder_leaderboard',+ title: '$THREE holder leaderboard',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "The public $THREE holder leaderboard, ranked by on-chain balance. $THREE is the only coin three.ws ranks holders for. Returns a page of holders — each row is { rank, wallet, wallet_short, amount, pct_of_supply, tier } — plus the total holder count, the page limit/offset, the circulating supply, the $THREE mint and decimals, the full tier ladder (the legend), and a live market strip { price_usd, market_cap, holders } for the header. Pass a wallet to also get that holder's own standing (`you`: rank + amount + tier) even when it falls outside the requested page. Read-only live data; balances and ranks move between calls.",+ inputSchema: {+ limit: z+ .number()+ .int()+ .min(1)+ .max(100)+ .optional()+ .describe('Page size — how many ranked holders to return (1–100, default 50).'),+ offset: z+ .number()+ .int()+ .min(0)+ .optional()+ .describe('Page offset into the ranking (default 0). Combine with limit to page through the board.'),+ wallet: z+ .string()+ .trim()+ .optional()+ .describe("Optional base58 Solana wallet. When supplied, the response's `you` field reports that wallet's own rank, amount, % of supply, and tier even if it's outside the page."),+ },+ async handler(args) {+ const limit = args?.limit;+ const offset = args?.offset;+ const wallet = typeof args?.wallet === 'string' ? args.wallet.trim() : undefined;+ const data = await apiRequest('/api/leaderboard', { query: { limit, offset, wallet } });+ const holders = Array.isArray(data?.holders) ? data.holders : [];+ return {+ ok: true,+ mint: data?.mint ?? null,+ total: Number(data?.total) || 0,+ limit: Number(data?.limit) || holders.length,+ offset: Number(data?.offset) || 0,+ count: holders.length,+ supply: data?.supply ?? null,+ decimals: data?.decimals ?? null,+ holders,+ tiers: Array.isArray(data?.tiers) ? data.tiers : [],+ market: data?.market ?? null,+ you: data?.you ?? null,+ ts: data?.ts ?? null,+ };+ },+};diff --git a/packages/activity-mcp/src/tools/get-tier-info.js b/packages/activity-mcp/src/tools/get-tier-info.jsnew file mode 100644index 000000000..375d10099--- /dev/null+++ b/packages/activity-mcp/src/tools/get-tier-info.js@@ -0,0 +1,31 @@+// `get_tier_info` — the $THREE holder tier ladder. Read-only.+//+// Wraps GET /api/leaderboard (reads its `tiers` legend; the leaderboard always+// returns the ladder, even on an empty board). The thresholds are derived purely+// from on-chain $THREE balance — the same ladder the board badges, the 3D PFP+// gate, and the share card all use.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_tier_info',+ title: '$THREE holder tier ladder',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "The $THREE holder tier ladder — the membership bands a wallet earns purely from its on-chain $THREE balance. Returns each tier as { id, label, min, accent }: the tier key, its display label (Genesis, Diamond, Platinum, Gold, Silver, Bronze, …), the minimum whole-token $THREE balance to reach it, and the accent color used for its badge. Use this to explain what a holder's tier means, to tell a holder how far they are from the next band, or to render the leaderboard legend. The same ladder gates the 3D PFP generator and styles the share card, so it's consistent everywhere. Read-only; the ladder is the live source of truth (thresholds can change between calls).",+ inputSchema: {},+ async handler() {+ // limit=1 keeps the holder page tiny — we only need the `tiers` legend,+ // which the leaderboard returns on every response (even an empty board).+ const data = await apiRequest('/api/leaderboard', { query: { limit: 1 } });+ const tiers = Array.isArray(data?.tiers) ? data.tiers : [];+ return {+ ok: true,+ mint: data?.mint ?? null,+ count: tiers.length,+ tiers,+ };+ },+};diff --git a/packages/activity-mcp/src/tools/get-trending-agents.js b/packages/activity-mcp/src/tools/get-trending-agents.jsnew file mode 100644index 000000000..2be530fe4--- /dev/null+++ b/packages/activity-mcp/src/tools/get-trending-agents.js@@ -0,0 +1,48 @@+// `get_trending_agents` — agents ranked by real chat activity. Read-only.+//+// Wraps GET /api/trending?window=24h|7d|all&limit=<n>&sort=activity|trust and+// returns the agents ranking (the public /trending leaderboard's agent column).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_trending_agents',+ title: 'Trending agents by activity',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "The agents that are hot on three.ws right now, ranked by REAL chat activity. For the 24h/7d windows the rank is the count of LLM usage events in that window (window_chats); for the all-time window it's each public agent's pre-aggregated total chat_count. Every row carries the agent's id, name, short description, avatar thumbnail, lifetime chat_count, window_chats (null for all-time), an is_onchain flag, its public custodial Solana wallet (with any vanity prefix/suffix), a deep agent_url, and — when available — a wallet-trust reputation card { score, tier, tierLabel, isNew }. Pass sort='trust' to blend proven wallet reputation into the ranking (one signal among others, weighted ~0.45, never pay-to-win) instead of pure activity. Read-only live data; the ranking moves between calls.",+ inputSchema: {+ window: z+ .enum(['24h', '7d', 'all'])+ .default('24h')+ .describe('Activity window to rank over: 24h or 7d count LLM usage events in that window; all uses lifetime chat_count (default 24h).'),+ sort: z+ .enum(['activity', 'trust'])+ .default('activity')+ .describe("Ranking mode: 'activity' ranks purely by chat volume; 'trust' blends wallet-trust reputation in as one signal (default activity)."),+ limit: z+ .number()+ .int()+ .min(1)+ .max(20)+ .optional()+ .describe('How many ranked agents to return (1–20, default 10).'),+ },+ async handler(args) {+ const window = ['24h', '7d', 'all'].includes(args?.window) ? args.window : '24h';+ const sort = args?.sort === 'trust' ? 'trust' : 'activity';+ const limit = args?.limit;+ const data = await apiRequest('/api/trending', { query: { window, sort, limit } });+ const agents = Array.isArray(data?.agents) ? data.agents : [];+ return {+ ok: true,+ window,+ sort,+ generated_at: data?.generated_at ?? null,+ count: agents.length,+ agents,+ };+ },+};diff --git a/packages/activity-mcp/src/tools/get-trending-coins.js b/packages/activity-mcp/src/tools/get-trending-coins.jsnew file mode 100644index 000000000..f07571b29--- /dev/null+++ b/packages/activity-mcp/src/tools/get-trending-coins.js@@ -0,0 +1,38 @@+// `get_trending_coins` — coins ranked by Oracle conviction. Read-only.+//+// Wraps GET /api/trending and returns the coins ranking — the platform launch+// directory's top Oracle-conviction coins, rendered from real launch records at+// runtime. This is discovery data, not an endorsement: the tool surfaces what+// the Oracle scored highest, it never markets or recommends any specific mint.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_trending_coins',+ title: 'Trending coins by Oracle conviction',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "The coins three.ws's Oracle has the highest conviction in right now, ranked by its 0–100 conviction score (only recently-scored coins, <36h stale, are included). Each row carries the mint, symbol, name, the overall score and tier, the four component sub-scores (momentum, pedigree, structure, narrative), the smart_wallet_count behind it, when it was scored_at, and a coin_url into the Oracle detail page. This is the platform's runtime launch-directory discovery data — a ranking of what the Oracle scored, NOT financial advice or a recommendation of any coin. Read-only live data; the ranking moves between calls.",+ inputSchema: {+ limit: z+ .number()+ .int()+ .min(1)+ .max(20)+ .optional()+ .describe('How many ranked coins to return (1–20, default 10).'),+ },+ async handler(args) {+ const limit = args?.limit;+ const data = await apiRequest('/api/trending', { query: { limit } });+ const coins = Array.isArray(data?.coins) ? data.coins : [];+ return {+ ok: true,+ generated_at: data?.generated_at ?? null,+ count: coins.length,+ coins,+ };+ },+};diff --git a/packages/agenc-mcp/LICENSE b/packages/agenc-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/agenc-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/agenc-mcp/src/config.js b/packages/agenc-mcp/src/config.jsnew file mode 100644index 000000000..fc4b22b80--- /dev/null+++ b/packages/agenc-mcp/src/config.js@@ -0,0 +1,36 @@+// Centralized env + HTTP base for the AgenC MCP.+//+// This server is a thin, read-first wrapper over the PUBLIC three.ws AgenC+// bridge (/api/agenc/*) — the on-chain task marketplace + agent registry of the+// AgenC coordination protocol (agenc.tech, Tetsuo Corp), exposed over plain+// HTTP so agents don't have to stand up Anchor + an IDL pipeline. It signs+// nothing and holds no secret — the only knobs are which deployment to talk to+// and how long to wait. Every task, agent, and service comes from the live+// endpoints; nothing is computed or cached here.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Base URL of the three.ws API. Override only when self-hosting or pointing at a+// preview deployment.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Per-request timeout (ms). These are live reads — the bridge fans out to a+// Solana RPC to scan task/agent PDAs, so give it room to ride out a cold edge+// while staying fast in practice.+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 20000;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) {+ throw Object.assign(new Error(`THREE_WS_TIMEOUT_MS must be a positive number (got "${raw}")`), {+ code: 'bad_config',+ });+ }+ return n;+})();++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/agenc-mcp';diff --git a/packages/agenc-mcp/src/lib/api.js b/packages/agenc-mcp/src/lib/api.jsnew file mode 100644index 000000000..57ddc422d--- /dev/null+++ b/packages/agenc-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/agenc/list-tasks`).+ * @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/agenc-mcp/src/tools/get-agent.js b/packages/agenc-mcp/src/tools/get-agent.jsnew file mode 100644index 000000000..ab88659de--- /dev/null+++ b/packages/agenc-mcp/src/tools/get-agent.js@@ -0,0 +1,65 @@+// `get_agent` — one AgenC registry entry (ERC-8004-style on-chain identity).+// Read-only.+//+// Wraps GET /api/agenc/get-agent. Address an agent either by its PDA or by+// agentId (0x/64-char hex seed, or a plain label the bridge hashes).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_agent',+ title: 'Get AgenC agent registry entry',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Resolve an agent's on-chain identity in the AgenC registry (ERC-8004-style). Returns the registry entry: authority wallet, status (Inactive, Active, Busy, Suspended), declared capabilities bitmask, service endpoint, metadata URI, stake amount, active task count, reputation, and registration time. Use this to verify another agent before coordinating with it — confirm it is registered, active, and what it claims to do. Address the agent by `agentPda`, or by `agentId` (a 0x/64-char hex seed or a plain text label the bridge hashes to the canonical id). Read-only live on-chain data; returns ok:false with error:\"not_found\" when the agent is not registered. Free, no key required.",+ inputSchema: {+ agentPda: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Base58 PDA of the agent registry entry. Provide this OR agentId.'),+ agentId: z+ .string()+ .min(1)+ .optional()+ .describe('Agent id: a 0x/64-char hex seed, or a plain text label hashed to the canonical 32-byte id.'),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .default('mainnet')+ .describe('Solana cluster to query (default mainnet).'),+ },+ async handler(args) {+ const agentPda = args?.agentPda ? String(args.agentPda).trim() : undefined;+ const agentId = args?.agentId ? String(args.agentId).trim() : undefined;+ if (!agentPda && !agentId) {+ throw Object.assign(new Error('provide agentPda or agentId'), { code: 'validation_error' });+ }+ const cluster = args?.cluster === 'devnet' ? 'devnet' : 'mainnet';+ try {+ const data = await apiRequest('/api/agenc/get-agent', { query: { agentPda, agentId, cluster } });+ return {+ ok: true,+ cluster: data?.cluster ?? cluster,+ programId: data?.programId ?? null,+ agentPda: data?.agentPda ?? agentPda ?? null,+ agent: data?.agent ?? null,+ fetchedAt: data?.fetchedAt ?? null,+ };+ } catch (err) {+ if (err?.code === 'upstream_error' && err.status === 404) {+ const body = err.body || {};+ return {+ ok: false,+ error: 'not_found',+ cluster: body.cluster ?? cluster,+ programId: body.programId ?? null,+ agentPda: body.agentPda ?? agentPda ?? null,+ };+ }+ throw err;+ }+ },+};diff --git a/packages/agenc-mcp/src/tools/get-task.js b/packages/agenc-mcp/src/tools/get-task.jsnew file mode 100644index 000000000..7568432b7--- /dev/null+++ b/packages/agenc-mcp/src/tools/get-task.js@@ -0,0 +1,81 @@+// `get_task` — one AgenC task's full status, optionally with its lifecycle+// timeline. Read-only.+//+// Wraps GET /api/agenc/get-task. Address a task either directly by its PDA, or+// by (creator + taskId) — taskId accepts a 0x/64-char hex seed or a plain label+// the bridge hashes to the canonical 32-byte id.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_task',+ title: 'Get AgenC task detail + lifecycle',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Fetch one AgenC task by its PDA, or by (creator + taskId). Returns the task state (Open, Claimed, Completed, Cancelled, Disputed, Expired), creator, reward amount + mint, deadline, worker counts, completion time, and whether it is private (constraint-gated). Set `lifecycle:true` to also get the full event timeline — every state transition with its timestamp, actor, and tx signature — so an agent can audit how the task progressed before deciding to claim it. `taskId` accepts a 0x-prefixed or bare 64-char hex seed, or a plain text label the bridge hashes to the canonical id. Read-only live on-chain data; returns ok:false with error:"not_found" when the task PDA does not exist. Free, no key required.',+ inputSchema: {+ taskPda: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Base58 PDA of the task to fetch. Provide this OR (creator + taskId).'),+ creator: z+ .string()+ .min(32)+ .max(44)+ .optional()+ .describe('Base58 creator wallet — combine with taskId to derive the task PDA.'),+ taskId: z+ .string()+ .min(1)+ .optional()+ .describe('Task id: a 0x/64-char hex seed, or a plain text label hashed to the canonical 32-byte id. Requires creator.'),+ lifecycle: z+ .boolean()+ .default(false)+ .describe('When true, include the full lifecycle event timeline (state transitions, actors, tx signatures).'),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .default('mainnet')+ .describe('Solana cluster to query (default mainnet).'),+ },+ async handler(args) {+ const taskPda = args?.taskPda ? String(args.taskPda).trim() : undefined;+ const creator = args?.creator ? String(args.creator).trim() : undefined;+ const taskId = args?.taskId ? String(args.taskId).trim() : undefined;+ if (!taskPda && !(creator && taskId)) {+ throw Object.assign(new Error('provide taskPda OR (creator + taskId)'), { code: 'validation_error' });+ }+ const cluster = args?.cluster === 'devnet' ? 'devnet' : 'mainnet';+ const lifecycle = args?.lifecycle === true ? '1' : undefined;+ try {+ const data = await apiRequest('/api/agenc/get-task', {+ query: { taskPda, creator, taskId, lifecycle, cluster },+ });+ return {+ ok: true,+ cluster: data?.cluster ?? cluster,+ programId: data?.programId ?? null,+ taskPda: data?.taskPda ?? taskPda ?? null,+ task: data?.task ?? null,+ lifecycle: data?.lifecycle ?? null,+ fetchedAt: data?.fetchedAt ?? null,+ };+ } catch (err) {+ if (err?.code === 'upstream_error' && err.status === 404) {+ const body = err.body || {};+ return {+ ok: false,+ error: 'not_found',+ cluster: body.cluster ?? cluster,+ programId: body.programId ?? null,+ taskPda: body.taskPda ?? taskPda ?? null,+ };+ }+ throw err;+ }+ },+};diff --git a/packages/agenc-mcp/src/tools/list-tasks.js b/packages/agenc-mcp/src/tools/list-tasks.jsnew file mode 100644index 000000000..e6e7b50a7--- /dev/null+++ b/packages/agenc-mcp/src/tools/list-tasks.js@@ -0,0 +1,42 @@+// `list_tasks` — every AgenC task a given creator wallet has posted. Read-only.+//+// Wraps GET /api/agenc/list-tasks?creator=<base58>&cluster=mainnet|devnet — the+// free three.ws bridge over the AgenC coordination protocol's on-chain task+// marketplace (agenc.tech, Tetsuo Corp).++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'list_tasks',+ title: 'List AgenC tasks by creator',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'List every AgenC task created by a given Solana wallet. AgenC (agenc.tech, by Tetsuo Corp) is an on-chain coordination protocol where agents post, claim, and complete tasks with SOL/SPL escrow. Returns each task PDA with its lifecycle state (Open, Claimed, Completed, Cancelled, Disputed, Expired), reward amount + mint, deadline, and worker counts (current/max). `private:true` flags a task gated by a constraint hash. Use this to see the work a specific creator has open or in-flight. Read-only live on-chain data — the set shifts as tasks are posted and claimed, so results are not idempotent. Free, no key required.',+ inputSchema: {+ creator: z+ .string()+ .min(32)+ .max(44)+ .describe('Base58 Solana pubkey of the task creator wallet whose tasks to list.'),+ cluster: z+ .enum(['mainnet', 'devnet'])+ .default('mainnet')+ .describe('Solana cluster to query (default mainnet).'),+ },+ async handler(args) {+ const creator = String(args?.creator ?? '').trim();+ const cluster = args?.cluster === 'devnet' ? 'devnet' : 'mainnet';+ const data = await apiRequest('/api/agenc/list-tasks', { query: { creator, cluster } });+ return {+ ok: true,+ cluster: data?.cluster ?? cluster,+ programId: data?.programId ?? null,+ creator: data?.creator ?? creator,+ count: data?.count ?? (Array.isArray(data?.tasks) ? data.tasks.length : 0),+ tasks: Array.isArray(data?.tasks) ? data.tasks : [],+ fetchedAt: data?.fetchedAt ?? null,+ };+ },+};diff --git a/packages/billing-mcp/LICENSE b/packages/billing-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/billing-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/billing-mcp/src/config.js b/packages/billing-mcp/src/config.jsnew file mode 100644index 000000000..83d30500f--- /dev/null+++ b/packages/billing-mcp/src/config.js@@ -0,0 +1,45 @@+// Centralized env + HTTP base for the billing MCP.+//+// This server is the account-economics surface: an agent reads its OWN plan+// quotas, metered usage, invoices, receipts, and earnings. Every one of those+// reads is private and account-scoped, so they authenticate with your three.ws+// session token (THREE_WS_SESSION) — the same `__Host-sid` cookie a signed-in+// browser carries. The API resolves the calling user from it and returns only+// that user's billing data. The single public read (get_fee_info) needs nothing.+//+// We never hold a baked-in key and we never sign anything: this server only+// reads. Without THREE_WS_SESSION the billing reads cannot resolve a user, so it+// is a required credential for everything except the public fee rate.++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 (usage roll-ups, reconciliation+// joins) — 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 billing 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 their plan, usage, invoices, and+// receipts. Required for every read except the public fee rate. Treat it like a+// password.+export const THREE_WS_SESSION = env('THREE_WS_SESSION', '');++// Identifies this client to the API in request logs.+export const USER_AGENT = '@three-ws/billing-mcp';diff --git a/packages/billing-mcp/src/lib/api.js b/packages/billing-mcp/src/lib/api.jsnew file mode 100644index 000000000..b14b2f65e--- /dev/null+++ b/packages/billing-mcp/src/lib/api.js@@ -0,0 +1,101 @@+// 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. The lone public read+// (fee rate) omits `auth` and works with no credential.++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/billing/summary`).+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown, auth?: boolean, accept?: string, raw?: boolean }} [opts]+ * `auth: true` attaches the session cookie and requires THREE_WS_SESSION to be set.+ * `raw: true` returns `{ status, contentType, text }` instead of parsing JSON (used for CSV export).+ * @returns {Promise<any>} Parsed JSON response, or the raw envelope when `raw` is set.+ * @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, accept = 'application/json', raw = 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,+ '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();++ // Raw mode: hand back the body untouched (CSV export). Still normalize errors.+ if (raw) {+ if (!res.ok) {+ let data;+ try {+ data = text ? JSON.parse(text) : {};+ } catch {+ data = { raw: text };+ }+ 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 { status: res.status, contentType: res.headers.get('content-type') || '', 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/brain-mcp/LICENSE b/packages/brain-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/brain-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/brain-mcp/package.json b/packages/brain-mcp/package.jsonnew file mode 100644index 000000000..b3fb91fe3--- /dev/null+++ b/packages/brain-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/brain-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/brain-mcp",+ "description": "Any model, one interface — the three.ws multi-provider LLM router over MCP. Discover available providers/models (Claude, GPT-4o, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite…) and run a chat completion through whichever one fits. Free tiers need no key; paid flagships unlock with a three.ws API key.",+ "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/brain-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "llm",+ "router",+ "claude",+ "openai",+ "chat-completion",+ "multi-provider"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "brain-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/brain-mcp/server.json b/packages/brain-mcp/server.jsonnew file mode 100644index 000000000..a5a9f91b8--- /dev/null+++ b/packages/brain-mcp/server.json@@ -0,0 +1,56 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/brain-mcp",+ "title": "three.ws Brain",+ "description": "Any model, one interface — list LLM providers and run chat completions through the three.ws multi-provider router.",+ "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/brain-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/brain-mcp",+ "version": "0.1.0",+ "runtimeHint": "npx",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "THREE_WS_BASE",+ "description": "Base URL of the three.ws API that fronts the LLM router (/api/brain/chat). Override only when self-hosting or targeting a preview deployment.",+ "format": "string",+ "isRequired": false,+ "default": "https://three.ws"+ },+ {+ "name": "THREE_WS_API_KEY",+ "description": "Optional three.ws API key (sk_live_… / sk_test_…) or OAuth access token, sent as a Bearer token. Required only to use paid first-party flagships (Claude, GPT-4o, o3, Qwen Plus, DeepSeek). Free open-weight tiers (GPT-OSS 120B, NVIDIA NIM models) work with no key. Create one at https://three.ws/account.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "THREE_WS_TIMEOUT_MS",+ "description": "Per-request timeout in milliseconds. Chat completions stream server-side and are collapsed into a single reply, so this is generous by default to ride out a long flagship answer.",+ "format": "number",+ "isRequired": false,+ "default": "120000"+ }+ ]+ }+ ]+}diff --git a/packages/brain-mcp/src/config.js b/packages/brain-mcp/src/config.jsnew file mode 100644index 000000000..b7aaf22e6--- /dev/null+++ b/packages/brain-mcp/src/config.js@@ -0,0 +1,41 @@+// Centralized env + HTTP base for the brain MCP.+//+// This server is a thin wrapper over the three.ws multi-provider LLM router+// (/api/brain/chat). It holds no model keys of its own — the router fronts+// Claude, GPT-4o, Qwen, DeepSeek, NVIDIA NIM, IBM Granite, and more on the+// server's billed keys. The only knobs here are which deployment to talk to,+// how long to wait, and an optional three.ws API key that unlocks the paid+// first-party flagships (free open-weight tiers need no 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(/\/+$/, '');++// Optional bearer credential (three.ws API key `sk_live_…`/`sk_test_…`, or an+// OAuth access token). Sent as `Authorization: Bearer …` on every request. The+// router serves the free open-weight tiers anonymously; the paid first-party+// flagships (Claude, GPT-4o, o3, Qwen Plus, DeepSeek) require this credential.+export const THREE_WS_API_KEY = env('THREE_WS_API_KEY');++// Per-request timeout (ms). A chat completion streams server-side and is+// collapsed into a single MCP reply, so a long flagship answer must not be cut+// short — default generously (the router itself caps at ~120s).+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 120000;+ 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/brain-mcp';diff --git a/packages/kol-mcp/LICENSE b/packages/kol-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/kol-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/kol-mcp/src/config.js b/packages/kol-mcp/src/config.jsnew file mode 100644index 000000000..9b31791f2--- /dev/null+++ b/packages/kol-mcp/src/config.js@@ -0,0 +1,33 @@+// Centralized env + HTTP base for the KOL MCP.+//+// This server is a thin, read-only wrapper over the PUBLIC three.ws KOL API+// (/api/kol). It signs nothing and holds no secret — the Birdeye key that backs+// the portfolio P&L lives server-side on three.ws, so the only knobs here are+// which deployment to talk to and how long to wait. Every portfolio figure and+// trade comes from the live endpoints; nothing is computed or cached here.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Base URL of the three.ws API. Override only when self-hosting or pointing at a+// preview deployment.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Per-request timeout (ms). These are live reads (Birdeye portfolio P&L proxy,+// Helius trade fan-outs) — 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/kol-mcp';diff --git a/packages/kol-mcp/src/lib/api.js b/packages/kol-mcp/src/lib/api.jsnew file mode 100644index 000000000..4b01992d6--- /dev/null+++ b/packages/kol-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/kol-mcp/src/tools/get-wallet-portfolio.js b/packages/kol-mcp/src/tools/get-wallet-portfolio.jsnew file mode 100644index 000000000..262e6ad73--- /dev/null+++ b/packages/kol-mcp/src/tools/get-wallet-portfolio.js@@ -0,0 +1,48 @@+// `get_wallet_portfolio` — one KOL wallet's portfolio P&L card. Read-only.+//+// Wraps GET /api/kol/wallets?addresses=<wallet>. The three.ws API proxies+// Birdeye's wallet portfolio (server-side key) and returns a normalized P&L+// summary per address. This tool focuses that on a single tracked trader.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'get_wallet_portfolio',+ title: 'KOL wallet portfolio + P&L',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Pull one KOL trader's live portfolio P&L card from the three.ws Birdeye proxy. " ++ 'Returns realized P&L, unrealized P&L (current open-position value), win rate, total ' ++ 'trades, and the single highest-value token the wallet holds (symbol + USD value). Use ' ++ 'this to size up a specific smart trader before copying or analyzing them. For ranking ' ++ 'many traders at once use intel-mcp `kol_leaderboard`; this is the per-wallet deep dive. ' ++ '`found:false` means the proxy returned no portfolio for that address (unknown wallet, ' ++ 'or Birdeye had nothing). Read-only live data.',+ inputSchema: {+ wallet: z+ .string()+ .min(1)+ .describe('The Solana wallet address of the KOL trader to pull a portfolio P&L card for.'),+ },+ async handler(args) {+ const wallet = String(args?.wallet ?? '').trim();+ const data = await apiRequest('/api/kol/wallets', { query: { addresses: wallet } });+ const rows = Array.isArray(data?.data) ? data.data : [];+ const row = rows.find((r) => r?.address === wallet) ?? rows[0] ?? null;+ if (!row) {+ return { ok: true, wallet, found: false };+ }+ return {+ ok: true,+ wallet: row.address ?? wallet,+ found: true,+ realized_pnl_usd: row.realizedPnl ?? 0,+ unrealized_pnl_usd: row.unrealizedPnl ?? 0,+ win_rate: row.winRate ?? 0,+ total_trades: row.totalTrades ?? 0,+ top_token: row.topToken ?? null,+ };+ },+};diff --git a/packages/tutor-mcp/LICENSE b/packages/tutor-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/tutor-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/tutor-mcp/src/config.js b/packages/tutor-mcp/src/config.jsnew file mode 100644index 000000000..379ec3067--- /dev/null+++ b/packages/tutor-mcp/src/config.js@@ -0,0 +1,33 @@+// Centralized env + HTTP base for the tutor MCP.+//+// This server is a thin wrapper over the three.ws tutor session ledger+// (/api/tutor/session). It signs nothing and holds no secret — sessions are+// addressed by an opaque sessionId, so the only knobs are which deployment to+// talk to and how long to wait. Every line item and total comes from the live+// endpoint; 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 KV-backed reads/writes against the session+// ledger — 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/tutor-mcp';diff --git a/packages/tutor-mcp/src/lib/api.js b/packages/tutor-mcp/src/lib/api.jsnew file mode 100644index 000000000..4b01992d6--- /dev/null+++ b/packages/tutor-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/tutor-mcp/src/tools/close-session.js b/packages/tutor-mcp/src/tools/close-session.jsnew file mode 100644index 000000000..eda601656--- /dev/null+++ b/packages/tutor-mcp/src/tools/close-session.js@@ -0,0 +1,44 @@+// `close_session` — finalize a tutoring session and return its attested+// invoice. Write (state transition), but free: closing charges nothing.+//+// Wraps POST /api/tutor/session { sessionId, action: "end" }. The per-question+// answers are what cost money (billed at answer time); closing only seals the+// ledger. After close the session is locked — no further charges can be appended+// to it. Closing is idempotent: re-closing returns the same itemized total.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'close_session',+ title: 'Close a tutoring session (finalize invoice)',+ annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: false, openWorldHint: true },+ description:+ 'Finalize a Pay-As-You-Learn tutoring session and return its itemized, attested invoice. Seals the ledger for the given sessionId: status flips to "closed", a SHA-256 attestation is stamped over the line items and total, and no further questions can be billed to this session afterward. Returns sessionId, createdAt, closedAt, questionCount, the full lineItems array, the totalAtomics / totalUsd owed, and the attestation hash. Closing itself is FREE and moves no funds — the learner was already charged per answered question; this only produces the final receipt. Idempotent: closing an already-closed session returns the same total. Use load_session first if you want to review the tab before sealing it.',+ inputSchema: {+ sessionId: z+ .string()+ .min(1)+ .max(100)+ .describe('Opaque tutoring session identifier to finalize. Truncated to 100 chars by the API.'),+ },+ async handler(args) {+ const sessionId = String(args?.sessionId ?? '').trim().slice(0, 100);+ const invoice = await apiRequest('/api/tutor/session', {+ method: 'POST',+ body: { sessionId, action: 'end' },+ });+ return {+ ok: true,+ sessionId: invoice?.sessionId ?? sessionId,+ createdAt: invoice?.createdAt ?? null,+ closedAt: invoice?.closedAt ?? null,+ questionCount: invoice?.questionCount ?? 0,+ lineItems: Array.isArray(invoice?.lineItems) ? invoice.lineItems : [],+ totalAtomics: invoice?.totalAtomics ?? 0,+ totalUsd: invoice?.totalUsd ?? '0.000000',+ attestation: invoice?.attestation ?? null,+ };+ },+};diff --git a/packages/tutor-mcp/src/tools/load-session.js b/packages/tutor-mcp/src/tools/load-session.jsnew file mode 100644index 000000000..8707e5782--- /dev/null+++ b/packages/tutor-mcp/src/tools/load-session.js@@ -0,0 +1,39 @@+// `load_session` — read a tutoring session's running tab. Read-only, free.+//+// Wraps GET /api/tutor/session?sessionId=<id>. Viewing what you owe is never+// charged: this returns the itemized ledger for an open or closed session so an+// agent can resume a learner's tab or audit the line items before closing.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'load_session',+ title: 'Load a tutoring session ledger',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Read the running tab for a Pay-As-You-Learn tutoring session by its sessionId. Returns the itemized ledger: one lineItem per answered question (question text, level, output tokens, per-item cost in USDC atomics and a "$x.xxxxxx" string, and the timestamp), plus the session status ("open" | "closed"), questionCount, and the running totalAtomics / totalUsd. If the session was already closed it also returns the finalized, attested invoice. A sessionId with no stored history returns an empty open session (questionCount 0) rather than an error — that is an honest "nothing billed yet", not a failure. Viewing the tab is always free; this never charges the learner. Read-only live data.',+ inputSchema: {+ sessionId: z+ .string()+ .min(1)+ .max(100)+ .describe('Opaque tutoring session identifier (the id the session was opened with). Truncated to 100 chars by the API.'),+ },+ async handler(args) {+ const sessionId = String(args?.sessionId ?? '').trim().slice(0, 100);+ const data = await apiRequest('/api/tutor/session', { query: { sessionId } });+ return {+ ok: true,+ sessionId: data?.sessionId ?? sessionId,+ status: data?.status ?? 'open',+ createdAt: data?.createdAt ?? null,+ questionCount: data?.questionCount ?? 0,+ lineItems: Array.isArray(data?.lineItems) ? data.lineItems : [],+ totalAtomics: data?.totalAtomics ?? 0,+ totalUsd: data?.totalUsd ?? '0.000000',+ ...(data?.invoice ? { invoice: data.invoice } : {}),+ };+ },+};diff --git a/packages/vision-mcp/LICENSE b/packages/vision-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/vision-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/vision-mcp/package.json b/packages/vision-mcp/package.jsonnew file mode 100644index 000000000..bedd95349--- /dev/null+++ b/packages/vision-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/vision-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/vision-mcp",+ "description": "Let any AI agent see — analyze and describe images through the three.ws vision pipeline. Free NVIDIA NIM VLMs first, with an automatic server-side paid backstop. Pass an image URL or base64 and get a structured, natural-language read. Read-only, no key required.",+ "type": "module",+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/vision-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "three.ws",+ "vision",+ "vlm",+ "image-understanding",+ "multimodal",+ "nvidia-nim",+ "describe-image"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "vision-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/vision-mcp/server.json b/packages/vision-mcp/server.jsonnew file mode 100644index 000000000..34da8005a--- /dev/null+++ b/packages/vision-mcp/server.json@@ -0,0 +1,55 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/vision-mcp",+ "title": "three.ws Vision",+ "description": "Image understanding for AI agents — analyze and describe any image via the free-first three.ws vision pipeline.",+ "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/vision-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/vision-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 vision endpoint. Override only when self-hosting or targeting a preview deployment.",+ "format": "string",+ "isRequired": false,+ "default": "https://three.ws"+ },+ {+ "name": "THREE_WS_TIMEOUT_MS",+ "description": "Per-request timeout in milliseconds for the vision call (the VLM may chain across free lanes before answering).",+ "format": "number",+ "isRequired": false,+ "default": "30000"+ },+ {+ "name": "THREE_WS_API_KEY",+ "description": "Optional three.ws API key (bearer token). Not required — the vision endpoint serves anonymous callers on a free per-IP rate limit. Set it to raise your rate limit to the per-user tier. Never needed to access the free model.",+ "format": "string",+ "isRequired": false+ }+ ]+ }+ ]+}diff --git a/packages/vision-mcp/src/config.js b/packages/vision-mcp/src/config.jsnew file mode 100644index 000000000..afbde47e3--- /dev/null+++ b/packages/vision-mcp/src/config.js@@ -0,0 +1,39 @@+// Centralized env + HTTP base for the vision MCP.+//+// This server is a thin wrapper over the PUBLIC three.ws vision endpoint+// (/api/vision): a free-first NVIDIA NIM VLM chain with an automatic, server-side+// paid backstop. The caller never pays and holds no provider secret — the only+// knobs are which deployment to talk to, how long to wait, and an OPTIONAL+// three.ws API key that raises the rate limit from the per-IP to the per-user+// tier. Every description comes from the live endpoint; nothing is computed 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). A vision call may fall over several free NIM lanes+// before one answers, so the default is more generous than a plain JSON read.+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 30000;+ 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;+})();++// Optional three.ws API key (bearer). When present it lifts the caller from the+// anonymous per-IP rate limit to the per-user tier. Absent is fully supported —+// the free model serves anonymous callers — so this is never required.+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/vision-mcp';diff --git a/packages/vision-mcp/src/lib/api.js b/packages/vision-mcp/src/lib/api.jsnew file mode 100644index 000000000..eb6d91039--- /dev/null+++ b/packages/vision-mcp/src/lib/api.js@@ -0,0 +1,72 @@+// 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';++/**+ * Call a three.ws HTTP endpoint and return its parsed JSON body.+ *+ * When THREE_WS_API_KEY is configured it is sent as a bearer token, which lifts+ * the vision endpoint's rate limit from the per-IP to the per-user tier. The key+ * is optional — the free model serves anonymous callers — so its absence is not+ * an error.+ *+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/vision`).+ * @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/vision-mcp/src/lib/image.js b/packages/vision-mcp/src/lib/image.jsnew file mode 100644index 000000000..205fa2681--- /dev/null+++ b/packages/vision-mcp/src/lib/image.js@@ -0,0 +1,116 @@+// Boundary validation + normalization for caller-supplied images.+//+// The /api/vision endpoint accepts a JSON body with EITHER `imageUrl` (a public+// https URL the model server fetches) OR `image` (base64 / data URI) + optional+// `imageType`. The server SSRF-guards URLs and enforces a 12 MB cap itself; we+// pre-validate here so an obviously-bad input fails fast with a clear, local+// error instead of a wasted round-trip — and so the MCP tool's contract is+// explicit. This is the only place the two tools turn raw args into a request.++// Mirrors the endpoint's ACCEPTED_TYPES (api/vision.js). Kept in sync by hand —+// both are short, stable lists.+export const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];++// Matches the endpoint's MAX_IMAGE_BYTES (12 MiB on the decoded image).+const MAX_IMAGE_BYTES = 12 * 1024 * 1024;++function boundaryError(message) {+ return Object.assign(new Error(message), { code: 'invalid_image', status: 400 });+}++function normalizeImageType(raw) {+ const type = String(raw || '').split(';')[0].trim().toLowerCase();+ return ACCEPTED_IMAGE_TYPES.includes(type) ? type : null;+}++// Reject the SSRF targets we can cheaply detect from the URL string itself+// (https only, no IP-literal loopback/private/link-local hosts, no *.local). The+// server applies the authoritative guard; this just turns the common mistakes+// into a clean local 400.+function assertPublicHttpsUrl(rawUrl) {+ let url;+ try {+ url = new URL(rawUrl);+ } catch {+ throw boundaryError(`imageUrl is not a valid URL: "${String(rawUrl).slice(0, 80)}"`);+ }+ if (url.protocol !== 'https:') {+ throw boundaryError(`imageUrl must be an https URL (got "${url.protocol.replace(':', '') || 'none'}")`);+ }+ const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase();+ const isPrivate =+ host === 'localhost' ||+ /\.(local|internal|localdomain)$/.test(host) ||+ /^127\./.test(host) ||+ /^10\./.test(host) ||+ /^192\.168\./.test(host) ||+ /^169\.254\./.test(host) ||+ /^172\.(1[6-9]|2\d|3[01])\./.test(host) ||+ host === '0.0.0.0' ||+ host === '::1';+ if (isPrivate) {+ throw boundaryError('imageUrl must resolve to a public host (private/loopback addresses are blocked)');+ }+ return url.toString();+}++// Decode-safe size check for a base64 payload without materializing the bytes:+// 4 base64 chars → 3 bytes, minus padding.+function base64ByteLength(b64) {+ const len = b64.length;+ const padding = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;+ return Math.floor((len * 3) / 4) - padding;+}++function assertBase64Image(raw, imageTypeHint) {+ const dataUri = String(raw).match(/^data:(image\/[a-z+]+);base64,(.*)$/is);+ const mimeType = dataUri ? normalizeImageType(dataUri[1]) : normalizeImageType(imageTypeHint) || 'image/jpeg';+ if (dataUri && !mimeType) {+ throw boundaryError(`unsupported image type in data URI; use one of ${ACCEPTED_IMAGE_TYPES.join(', ')}`);+ }+ const payload = (dataUri ? dataUri[2] : String(raw).replace(/^data:[^,]*,/, '')).replace(/\s+/g, '');+ if (!payload) throw boundaryError('image is empty');+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(payload)) {+ throw boundaryError('image is not valid base64 (pass raw base64 or a data: URI)');+ }+ if (base64ByteLength(payload) > MAX_IMAGE_BYTES) {+ throw boundaryError('image exceeds the 12 MB limit; downscale before sending');+ }+ return { payload, mimeType };+}++/**+ * Turn validated tool args into the /api/vision JSON request body. Exactly one+ * of `imageUrl` / `image` must be supplied.+ *+ * @param {{ imageUrl?: string, image?: string, imageType?: string, prompt?: string, maxTokens?: number }} args+ * @returns {{ body: object, source: 'url' | 'base64' }}+ */+export function buildVisionBody({ imageUrl, image, imageType, prompt, maxTokens } = {}) {+ const hasUrl = typeof imageUrl === 'string' && imageUrl.trim() !== '';+ const hasImage = typeof image === 'string' && image.trim() !== '';++ if (hasUrl && hasImage) {+ throw boundaryError('provide either imageUrl or image, not both');+ }+ if (!hasUrl && !hasImage) {+ throw boundaryError('an image is required: pass imageUrl (public https) or image (base64 / data URI)');+ }++ const body = {};+ let source;+ if (hasUrl) {+ body.imageUrl = assertPublicHttpsUrl(imageUrl.trim());+ source = 'url';+ } else {+ const { payload, mimeType } = assertBase64Image(image, imageType);+ body.image = payload;+ body.imageType = mimeType;+ source = 'base64';+ }++ if (typeof prompt === 'string' && prompt.trim()) body.prompt = prompt.trim().slice(0, 2000);+ if (Number.isFinite(maxTokens)) body.maxTokens = Math.min(Math.max(Math.trunc(maxTokens), 16), 2048);++ return { body, source };+}diff --git a/public/changelog.json b/public/changelog.jsonindex fc293b3bf..2ed9ad6c1 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T06:04:17.142Z",+ "generated_at": "2026-06-24T06:13:28.247Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex b8263c5c1..039c511e3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T06:04:17.130Z",+ "generated_at": "2026-06-24T06:13:28.211Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",