Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: MCP servers (3D Studio, x402 Bazaar, IBM watsonx, pumpfun) + dispatch

nirholasa8e4bc4094ae
diff --git a/.github/workflows/publish-ibm-watsonx-mcp.yml b/.github/workflows/publish-ibm-watsonx-mcp.yml
new file mode 100644
index 000000000..bd8b1740e
--- /dev/null
+++ b/.github/workflows/publish-ibm-watsonx-mcp.yml
@@ -0,0 +1,51 @@
+# Publish @three-ws/ibm-watsonx-mcp to npm and the official MCP Registry.
+#
+# Manual trigger. The npm step needs an NPM_TOKEN secret (Automation token with
+# publish rights). The MCP Registry step needs NO secret — it authenticates with
+# GitHub OIDC, which proves ownership of the io.github.nirholas/* namespace.
+#
+# Bump the version in packages/ibm-watsonx-mcp/package.json AND server.json
+# before running (both must match).
+name: publish-ibm-watsonx-mcp
+
+on:
+ workflow_dispatch:
+
+defaults:
+ run:
+ working-directory: packages/ibm-watsonx-mcp
+
+permissions:
+ contents: read
+ id-token: write # required for MCP Registry GitHub OIDC auth
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ registry-url: 'https://registry.npmjs.org'
+
+ - name: Install dependencies
+ run: npm install --no-package-lock
+
+ - name: Publish package to npm
+ run: npm publish --access public
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ - name: Install mcp-publisher
+ run: |
+ curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_linux_amd64.tar.gz" \
+ | tar xz mcp-publisher
+ sudo mv mcp-publisher /usr/local/bin/
+
+ - name: Authenticate to the MCP Registry (GitHub OIDC)
+ run: mcp-publisher login github-oidc
+
+ - name: Publish to the MCP Registry
+ run: mcp-publisher publish
diff --git a/api/_lib/mcp-dispatch.js b/api/_lib/mcp-dispatch.js
new file mode 100644
index 000000000..8fbcff7ac
--- /dev/null
+++ b/api/_lib/mcp-dispatch.js
@@ -0,0 +1,125 @@
+// Shared JSON-RPC 2.0 dispatcher for the focused, payment-free MCP servers
+// (3D Studio, x402 Bazaar). The main /api/mcp server keeps its own dispatch
+// because it layers pump-agent-payments gating on top; these servers don't, so
+// they share this slim core: method routing, scope checks, Ajv arg validation,
+// usage accounting, and the MCP error conventions.
+import { hasScope } from './auth.js';
+import { recordEvent, logger } from './usage.js';
+
+export const PROTOCOL_VERSION = '2025-06-18';
+
+function ok(id, result) {
+ return { jsonrpc: '2.0', id, result };
+}
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+
+function summarize(args) {
+ const o = {};
+ for (const [k, v] of Object.entries(args || {})) {
+ o[k] = typeof v === 'string' && v.length > 64 ? v.slice(0, 64) + '…' : v;
+ }
+ return o;
+}
+
+// Build a dispatch(msg, auth, req) function bound to one server's catalog.
+// serverInfo { name, version }
+// instructions string shown to clients on initialize
+// catalog tools/list array (schemas, no handlers)
+// tools { [name]: { scope?, handler, validate? } }
+// logName logger namespace + usage `server` tag
+export function makeDispatcher({ serverInfo, instructions, catalog, tools, logName }) {
+ const log = logger(logName);
+
+ async function onToolCall(params, auth, started) {
+ const { name, arguments: args = {} } = params || {};
+ const tool = tools[name];
+ if (!tool) throw rpcError(-32602, `unknown tool: ${name}`);
+ if (tool.scope && !hasScope(auth.scope, tool.scope)) {
+ throw rpcError(-32002, `insufficient scope, requires ${tool.scope}`);
+ }
+ if (tool.validate && !tool.validate(args)) {
+ const first = tool.validate.errors?.[0];
+ const detail = first
+ ? `${first.instancePath || '(root)'} ${first.message || 'invalid'}`
+ : 'invalid arguments';
+ throw rpcError(-32602, `invalid params for ${name}: ${detail}`);
+ }
+
+ const event = {
+ userId: auth.userId,
+ apiKeyId: auth.apiKeyId,
+ clientId: auth.clientId,
+ kind: 'tool_call',
+ tool: name,
+ };
+ try {
+ const result = await tool.handler(args, auth);
+ recordEvent({
+ ...event,
+ latencyMs: Date.now() - started,
+ meta: { args_summary: summarize(args), server: logName },
+ });
+ return result;
+ } catch (err) {
+ recordEvent({
+ ...event,
+ status: 'error',
+ latencyMs: Date.now() - started,
+ meta: { error: err.message, server: logName },
+ });
+ if (err.code && typeof err.code === 'number') throw err;
+ return {
+ content: [{ type: 'text', text: `Error: ${err.message || 'tool call failed'}` }],
+ isError: true,
+ };
+ }
+ }
+
+ return async function dispatch(msg, auth, _req) {
+ const started = Date.now();
+ const id = msg.id;
+ const isNotification = id === undefined;
+
+ try {
+ if (msg.jsonrpc !== '2.0') throw rpcError(-32600, 'invalid Request');
+ const method = msg.method;
+
+ if (method === 'initialize') {
+ return ok(id, {
+ protocolVersion: PROTOCOL_VERSION,
+ serverInfo,
+ capabilities: {
+ tools: { listChanged: false },
+ resources: { listChanged: false, subscribe: false },
+ logging: {},
+ },
+ instructions,
+ });
+ }
+ if (method === 'ping') return ok(id, {});
+ if (method === 'notifications/initialized') return null;
+ if (method === 'tools/list') return ok(id, { tools: catalog });
+ if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started));
+ if (method === 'resources/list') return ok(id, { resources: [] });
+ if (method === 'resources/templates/list') return ok(id, { resourceTemplates: [] });
+ if (method === 'prompts/list') return ok(id, { prompts: [] });
+ if (method === 'logging/setLevel') return ok(id, {});
+
+ throw rpcError(-32601, `method not found: ${method}`);
+ } catch (err) {
+ log.warn('rpc_error', { method: msg.method, code: err.code, message: err.message });
+ if (isNotification) return null;
+ return {
+ jsonrpc: '2.0',
+ id,
+ error: { code: err.code || -32603, message: err.message || 'internal error', data: err.data },
+ };
+ }
+ };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 74feaadbb..89ff1d554 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -73,6 +73,14 @@ export const limits = {
mcpValidate: (key) => getLimiter('mcp:validate', { limit: 10, window: '1 m' }).limit(key),
mcpInspect: (key) => getLimiter('mcp:inspect', { limit: 30, window: '1 m' }).limit(key),
mcpOptimize: (key) => getLimiter('mcp:optimize', { limit: 10, window: '1 m' }).limit(key),
+ // 3D Studio MCP. Generation submits a real GPU job on Replicate (text→image
+ // and/or image→3D reconstruction) that costs real money, so it gets a hard
+ // hourly ceiling per principal. Status polling is cheap and frequent.
+ mcp3dGenerate: (key) => getLimiter('mcp3d:generate', { limit: 12, window: '1 h' }).limit(key),
+ mcp3dStatus: (key) => getLimiter('mcp3d:status', { limit: 240, window: '1 m' }).limit(key),
+ // x402 Bazaar MCP. Discovery calls fan out to external facilitators, so cap
+ // per principal to keep that egress bounded without throttling normal use.
+ mcpBazaar: (key) => getLimiter('mcp:bazaar', { limit: 60, window: '1 m' }).limit(key),
oauthToken: (clientId) =>
getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),
upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),
diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.js
new file mode 100644
index 000000000..defe493c9
--- /dev/null
+++ b/api/_mcp3d/catalog.js
@@ -0,0 +1,26 @@
+import Ajv from 'ajv';
+
+import { toolDefs as studioDefs } from './tools/studio.js';
+import { toolDefs as modelDefs } from '../_mcp/tools/models.js';
+
+// Reuse the battle-tested inspect/optimize tools from the main MCP server so a
+// generated model can be analyzed in the same conversation — no duplicated
+// glTF logic. validate_model is omitted: in the studio context inspect already
+// covers "what is this mesh", and optimize covers "how do I ship it".
+const reusedModelDefs = modelDefs.filter((d) => d.name === 'inspect_model' || d.name === 'optimize_model');
+
+const allDefs = [...studioDefs, ...reusedModelDefs];
+
+// Schema objects for tools/list — strip internal fields (scope, handler).
+export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
+
+// Compile each tool's inputSchema once so dispatch can validate args before the
+// handler runs — same defense-in-depth + forgiving coercion the main server uses.
+const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
+
+export const TOOLS = Object.fromEntries(
+ allDefs.map(({ name, scope, handler, inputSchema }) => [
+ name,
+ { scope, handler, validate: inputSchema ? ajv.compile(inputSchema) : null },
+ ]),
+);
diff --git a/api/_mcp3d/dispatch.js b/api/_mcp3d/dispatch.js
new file mode 100644
index 000000000..007e23bec
--- /dev/null
+++ b/api/_mcp3d/dispatch.js
@@ -0,0 +1,22 @@
+// JSON-RPC dispatch for the 3D Studio MCP server — thin binding of the shared
+// payment-free dispatcher (api/_lib/mcp-dispatch.js) to this server's catalog.
+import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';
+import { TOOL_CATALOG, TOOLS } from './catalog.js';
+
+export { PROTOCOL_VERSION };
+
+const INSTRUCTIONS = [
+ 'three.ws 3D Studio turns text or images into interactive 3D models.',
+ 'text_to_3d(prompt) and image_to_3d(image_url) start a generation job and return a job_id;',
+ 'poll generation_status(job_id) until it returns a GLB and an inline <model-viewer> artifact.',
+ 'preview_3d(glb_url) renders any GLB as an artifact; inspect_model / optimize_model analyze one.',
+ 'Always display returned text/html resources as inline 3D artifacts.',
+].join(' ');
+
+export const dispatch = makeDispatcher({
+ serverInfo: { name: 'three-ws-3d-studio', version: '1.0.0' },
+ instructions: INSTRUCTIONS,
+ catalog: TOOL_CATALOG,
+ tools: TOOLS,
+ logName: 'mcp3d',
+});
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
new file mode 100644
index 000000000..fd671bd02
--- /dev/null
+++ b/api/_mcp3d/text-to-image.js
@@ -0,0 +1,113 @@
+// Text → image helper for the 3D Studio MCP.
+//
+// The image-to-3D backend (Microsoft TRELLIS via Replicate) reconstructs a
+// textured GLB from a single reference image. To support `text_to_3d` we first
+// turn the prompt into an image with a fast text-to-image model, then feed that
+// image into the same reconstruction pipeline. Both steps run on the one
+// REPLICATE_API_TOKEN already provisioned for the avatar regen pipeline.
+//
+// REPLICATE_API_TOKEN — required, from replicate.com/account
+// REPLICATE_TXT2IMG_MODEL — optional override (owner/name[:version] or version hash)
+//
+// Default model: black-forest-labs/flux-schnell — Apache-2.0 weights,
+// commercial-OK, ~1–3s per image on Replicate's fleet, $0.003/run. Pinned to
+// the model slug (not a version hash) so it tracks Replicate's latest build.
+
+const REPLICATE_BASE = 'https://api.replicate.com/v1';
+const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';
+
+function readEnv(name) {
+ if (typeof process !== 'undefined' && process.env && process.env[name]) return process.env[name];
+ return null;
+}
+
+// Pull the first https image URL out of Replicate's `output`, which flux models
+// emit as an array of URLs (sometimes a bare string for single-image models).
+function extractImageUrl(output) {
+ if (!output) return null;
+ if (typeof output === 'string') return /^https?:\/\//.test(output) ? output : null;
+ if (Array.isArray(output)) {
+ for (const v of output) if (typeof v === 'string' && /^https?:\/\//.test(v)) return v;
+ }
+ if (typeof output === 'object') {
+ for (const k of ['image', 'url', 'output']) {
+ if (typeof output[k] === 'string' && /^https?:\/\//.test(output[k])) return output[k];
+ }
+ }
+ return null;
+}
+
+// Generate a single image from a text prompt. Uses Replicate's synchronous
+// prediction mode (`Prefer: wait`) so the caller gets a URL back in one round
+// trip — flux-schnell is fast enough that the request returns within the MCP
+// tool-call window without needing a separate poll.
+export async function textToImage(prompt, { aspectRatio = '1:1' } = {}) {
+ const token = readEnv('REPLICATE_API_TOKEN');
+ if (!token) {
+ throw Object.assign(new Error('text-to-3D is not configured (REPLICATE_API_TOKEN missing)'), {
+ code: 'unconfigured',
+ });
+ }
+
+ const modelRef = readEnv('REPLICATE_TXT2IMG_MODEL') || DEFAULT_TXT2IMG_MODEL;
+ const isVersionHash = /^[a-f0-9]{40,64}$/i.test(modelRef);
+ const slug = modelRef.match(/^([a-z0-9-]+)\/([a-z0-9._-]+)(?::([a-f0-9]+))?$/i);
+
+ const input = {
+ prompt,
+ aspect_ratio: aspectRatio,
+ num_outputs: 1,
+ output_format: 'png',
+ // A clean, evenly-lit, single-subject image on a plain background
+ // reconstructs into a far better mesh than a busy scene — steer flux
+ // toward that without overriding a caller's own composition cues.
+ go_fast: true,
+ };
+
+ let endpoint;
+ let body;
+ if (isVersionHash) {
+ endpoint = `${REPLICATE_BASE}/predictions`;
+ body = JSON.stringify({ version: modelRef, input });
+ } else if (slug) {
+ const [, owner, name, pinned] = slug;
+ endpoint = `${REPLICATE_BASE}/models/${owner}/${name}/predictions`;
+ body = JSON.stringify(pinned ? { version: pinned, input } : { input });
+ } else {
+ throw new Error(`invalid REPLICATE_TXT2IMG_MODEL reference: ${modelRef}`);
+ }
+
+ let res;
+ try {
+ res = await fetch(endpoint, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ prefer: 'wait',
+ },
+ body,
+ });
+ } catch (err) {
+ throw Object.assign(new Error(`text-to-image provider unreachable: ${err?.message}`), {
+ code: 'provider_unreachable',
+ });
+ }
+
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(data?.detail || data?.title || `text-to-image returned ${res.status}`);
+ }
+
+ // With `Prefer: wait` the prediction usually completes inline. If Replicate
+ // returned before completion (slow model, timeout), surface the partial
+ // state so the handler can decide — but for flux-schnell this is rare.
+ const url = extractImageUrl(data.output);
+ if (!url) {
+ if (data.status && data.status !== 'succeeded') {
+ throw new Error(`text-to-image did not complete (status: ${data.status})`);
+ }
+ throw new Error('text-to-image finished but produced no image');
+ }
+ return { imageUrl: url, predictionId: data.id, model: modelRef };
+}
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
new file mode 100644
index 000000000..719bb6704
--- /dev/null
+++ b/api/_mcp3d/tools/studio.js
@@ -0,0 +1,297 @@
+// three.ws 3D Studio MCP — generation tools.
+//
+// text_to_3d / image_to_3d submit a real reconstruction job to Replicate
+// (Microsoft TRELLIS by default) and return a job handle. generation_status
+// polls that job and, when finished, hands back the GLB URL plus an inline
+// <model-viewer> artifact so the model appears directly in the chat. preview_3d
+// renders any public GLB the same way.
+
+import { limits } from '../../_lib/rate-limit.js';
+import { createRegenProvider } from '../../_providers/replicate.js';
+import { textToImage } from '../text-to-image.js';
+import {
+ renderModelViewerHtml,
+ safeCssValue,
+ safeCssLength,
+ safeHttpsUrl,
+} from '../../_mcp/render.js';
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+
+function rateKey(auth) {
+ return auth.userId || auth.rateKey || 'anon';
+}
+
+async function enforce(limiter, auth) {
+ const rl = await limiter(rateKey(auth));
+ if (!rl.success) {
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+}
+
+// Lazily construct the Replicate-backed provider so a missing token surfaces as
+// a clean tool error rather than crashing module load for the whole server.
+function regenProvider() {
+ try {
+ return createRegenProvider();
+ } catch (err) {
+ throw rpcError(-32000, '3D generation is not configured', { reason: err.message });
+ }
+}
+
+function isPublicHttpsUrl(s) {
+ try {
+ const u = new URL(String(s));
+ if (u.protocol !== 'https:') return false;
+ const h = u.hostname;
+ if (h === 'localhost' || h === '127.0.0.1' || h === '0.0.0.0') return false;
+ if (h.startsWith('169.254.') || h.startsWith('10.') || h.startsWith('192.168.')) return false;
+ if (h.endsWith('.internal') || h.endsWith('.local')) return false;
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const POLL_HINT =
+ 'Call generation_status with this job_id to check progress. ' +
+ 'Reconstruction typically finishes in 30–90 seconds.';
+
+function viewerArtifact({ glbUrl, name, options = {} }) {
+ const html = renderModelViewerHtml({
+ src: glbUrl,
+ name: name || '3D model',
+ poster: safeHttpsUrl(options.poster),
+ background: safeCssValue(options.background, 'transparent'),
+ height: safeCssLength(options.height, '480px'),
+ width: safeCssLength(options.width, '100%'),
+ autoRotate: options.auto_rotate !== false,
+ ar: options.ar !== false,
+ cameraOrbit: safeCssValue(options.camera_orbit, ''),
+ });
+ return {
+ type: 'resource',
+ resource: { uri: glbUrl, mimeType: 'text/html', text: html },
+ };
+}
+
+export const toolDefs = [
+ {
+ name: 'text_to_3d',
+ title: 'Generate a 3D model from a text prompt',
+ description:
+ 'Turn a text description into a textured 3D model (GLB). Runs a fast text-to-image pass, then reconstructs a mesh from that image with Microsoft TRELLIS. Returns a job_id (poll with generation_status) plus the intermediate preview image. Best results: a single, clearly described object — "a worn leather armchair", "a low-poly red fox", "a sci-fi helmet".',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ prompt: {
+ type: 'string',
+ minLength: 3,
+ maxLength: 1000,
+ description: 'What to generate. Describe one subject clearly.',
+ },
+ aspect_ratio: {
+ type: 'string',
+ enum: ['1:1', '4:3', '3:4', '16:9', '9:16'],
+ default: '1:1',
+ description: 'Aspect ratio of the intermediate reference image.',
+ },
+ },
+ required: ['prompt'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ const provider = regenProvider();
+ const { imageUrl, model } = await textToImage(args.prompt, {
+ aspectRatio: args.aspect_ratio || '1:1',
+ });
+ const job = await provider.submit({
+ mode: 'reconstruct',
+ params: { image: imageUrl, prompt: args.prompt },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Started generating a 3D model for "${args.prompt}".\n` +
+ `Reference image: ${imageUrl}\n` +
+ `Job ID: ${job.extJobId}\n${POLL_HINT}`,
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ prompt: args.prompt,
+ preview_image_url: imageUrl,
+ text_to_image_model: model,
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
+ {
+ name: 'image_to_3d',
+ title: 'Reconstruct a 3D model from an image',
+ description:
+ 'Reconstruct a textured 3D model (GLB) from a single reference image URL using Microsoft TRELLIS. Returns a job_id to poll with generation_status. The cleaner the input — one subject, plain background, even lighting — the better the mesh.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ image_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the reference image (PNG/JPG/WebP).',
+ },
+ prompt: {
+ type: 'string',
+ maxLength: 1000,
+ description: 'Optional text hint passed to the reconstruction model.',
+ },
+ },
+ required: ['image_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!isPublicHttpsUrl(args.image_url)) {
+ return {
+ content: [{ type: 'text', text: 'Error: image_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ const provider = regenProvider();
+ const job = await provider.submit({
+ mode: 'reconstruct',
+ params: { image: args.image_url, prompt: args.prompt },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Started reconstructing a 3D model from the image.\nJob ID: ${job.extJobId}\n${POLL_HINT}`,
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ source_image_url: args.image_url,
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
+ {
+ name: 'generation_status',
+ title: 'Check a 3D generation job',
+ description:
+ 'Poll a text_to_3d or image_to_3d job by its job_id. While running it reports the status; when finished it returns the GLB download URL and an inline <model-viewer> artifact — display that text/html resource as an interactive 3D artifact.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ job_id: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 200,
+ description: 'The job_id returned by text_to_3d or image_to_3d.',
+ },
+ },
+ required: ['job_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dStatus, auth);
+ const provider = regenProvider();
+ const result = await provider.status(args.job_id);
+
+ if (result.status === 'done' && result.resultGlbUrl) {
+ const glbUrl = result.resultGlbUrl;
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Your 3D model is ready.\nGLB: ${glbUrl}\n` +
+ 'Display the attached text/html resource as an inline 3D artifact.',
+ },
+ viewerArtifact({ glbUrl, name: '3D model' }),
+ ],
+ structuredContent: { job_id: args.job_id, status: 'done', glb_url: glbUrl },
+ };
+ }
+
+ if (result.status === 'failed') {
+ return {
+ content: [
+ { type: 'text', text: `Generation failed: ${result.error || 'unknown error'}` },
+ ],
+ structuredContent: { job_id: args.job_id, status: 'failed', error: result.error || null },
+ isError: true,
+ };
+ }
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Still ${result.status}. ${POLL_HINT}`,
+ },
+ ],
+ structuredContent: { job_id: args.job_id, status: result.status },
+ };
+ },
+ },
+ {
+ name: 'preview_3d',
+ title: 'Preview any GLB as an interactive 3D artifact',
+ description:
+ 'Render any public GLB URL as an inline <model-viewer> HTML artifact — orbit controls, AR on mobile, auto-rotate. Display the returned text/html resource as an inline 3D artifact. Use it to view a generated model, or any GLB on the web.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ glb_url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb file.' },
+ auto_rotate: { type: 'boolean', default: true },
+ ar: { type: 'boolean', default: true },
+ background: {
+ type: 'string',
+ default: 'transparent',
+ description: 'CSS background color or gradient.',
+ },
+ height: { type: 'string', default: '480px' },
+ width: { type: 'string', default: '100%' },
+ camera_orbit: {
+ type: 'string',
+ description: 'model-viewer camera-orbit value, e.g. "0deg 80deg 2m".',
+ },
+ },
+ required: ['glb_url'],
+ additionalProperties: false,
+ },
+ async handler(args) {
+ if (!isPublicHttpsUrl(args.glb_url)) {
+ return {
+ content: [{ type: 'text', text: 'Error: glb_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ return {
+ content: [
+ {
+ type: 'text',
+ text: 'Display the attached text/html resource as an inline 3D artifact.',
+ },
+ viewerArtifact({ glbUrl: args.glb_url, name: '3D model', options: args }),
+ ],
+ structuredContent: { glb_url: args.glb_url },
+ };
+ },
+ },
+];
diff --git a/api/_mcpbazaar/catalog.js b/api/_mcpbazaar/catalog.js
new file mode 100644
index 000000000..3ce4a22fa
--- /dev/null
+++ b/api/_mcpbazaar/catalog.js
@@ -0,0 +1,15 @@
+import Ajv from 'ajv';
+
+import { toolDefs } from './tools.js';
+
+// Schema objects for tools/list — strip internal fields (scope, handler).
+export const TOOL_CATALOG = toolDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
+
+const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
+
+export const TOOLS = Object.fromEntries(
+ toolDefs.map(({ name, scope, handler, inputSchema }) => [
+ name,
+ { scope, handler, validate: inputSchema ? ajv.compile(inputSchema) : null },
+ ]),
+);
diff --git a/api/_mcpbazaar/dispatch.js b/api/_mcpbazaar/dispatch.js
new file mode 100644
index 000000000..45750d34b
--- /dev/null
+++ b/api/_mcpbazaar/dispatch.js
@@ -0,0 +1,21 @@
+// JSON-RPC dispatch for the x402 Bazaar MCP server — thin binding of the shared
+// payment-free dispatcher (api/_lib/mcp-dispatch.js) to this server's catalog.
+import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';
+import { TOOL_CATALOG, TOOLS } from './catalog.js';
+
+export { PROTOCOL_VERSION };
+
+const INSTRUCTIONS = [
+ 'The x402 Bazaar lets you discover paid agent services across the live x402 facilitator network.',
+ 'search_services(query) finds services; browse_services() lists them; get_service(resource_url) returns',
+ 'the exact price, payment networks, input schema, and a ready pay link.',
+ 'Use this to answer "what can I pay for?" and to price and locate an external service before calling it.',
+].join(' ');
+
+export const dispatch = makeDispatcher({
+ serverInfo: { name: 'three-ws-x402-bazaar', version: '1.0.0' },
+ instructions: INSTRUCTIONS,
+ catalog: TOOL_CATALOG,
+ tools: TOOLS,
+ logName: 'mcp-bazaar',
+});
diff --git a/api/_mcpbazaar/tools.js b/api/_mcpbazaar/tools.js
new file mode 100644
index 000000000..bcba3afe0
--- /dev/null
+++ b/api/_mcpbazaar/tools.js
@@ -0,0 +1,211 @@
+// x402 Bazaar MCP — discovery tools over the live x402 facilitator network.
+//
+// Every tool hits real facilitators (no cache of fake data): search and browse
+// the merged catalog of paid agent services, and pull the full payment + input
+// schema for any one service. The result is everything a client needs to decide
+// to pay and exactly how — price, network, recipient, and a ready pay link.
+import { limits } from '../_lib/rate-limit.js';
+import { env } from '../_lib/env.js';
+import {
+ Bazaar,
+ filterByNetwork,
+ filterByMaxPrice,
+} from '../_lib/x402/bazaar-client.js';
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+
+async function enforce(auth) {
+ const rl = await limits.mcpBazaar(auth.userId || auth.rateKey || 'anon');
+ if (!rl.success) {
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+}
+
+// USDC and most x402 stablecoins use 6 decimals — convert a human dollar cap to
+// the atomic units filterByMaxPrice compares against.
+function usdcToAtomic(usd) {
+ return String(Math.round(Number(usd) * 1_000_000));
+}
+
+// Project a normalized bazaar item down to the fields a client actually needs,
+// dropping the bulky `raw` facilitator payload.
+function slim(it) {
+ return {
+ type: it.type,
+ resource: it.resource,
+ tool_name: it.toolName || undefined,
+ name: it.serviceName || undefined,
+ description: it.description || undefined,
+ price: it.minPriceLabel || undefined,
+ price_atomic: it.minPriceAtomic ?? undefined,
+ networks: it.networks,
+ tags: it.tags?.length ? it.tags : undefined,
+ method: it.method || undefined,
+ facilitator: it.facilitator,
+ };
+}
+
+function applyFilters(resources, { network, max_price_usdc }) {
+ let out = resources;
+ if (network) out = filterByNetwork(out, network);
+ if (max_price_usdc != null) out = filterByMaxPrice(out, usdcToAtomic(max_price_usdc));
+ return out;
+}
+
+function payUrl(resource, toolName) {
+ const u = new URL(`${env.APP_ORIGIN}/pay`);
+ u.searchParams.set('resource', resource);
+ if (toolName) u.searchParams.set('tool', toolName);
+ return u.toString();
+}
+
+function formatList(items, { query } = {}) {
+ if (!items.length) {
+ return query
+ ? `No x402 services matched "${query}".`
+ : 'No x402 services found on the configured facilitators.';
+ }
+ return items
+ .map((s, i) => {
+ const head = `${i + 1}. ${s.name || s.resource}${s.price ? ` — ${s.price}` : ''}`;
+ const desc = s.description ? `\n ${s.description}` : '';
+ const net = s.networks?.length ? `\n networks: ${s.networks.join(', ')}` : '';
+ const res = `\n ${s.tool_name ? `${s.resource} #${s.tool_name}` : s.resource}`;
+ return head + desc + net + res;
+ })
+ .join('\n');
+}
+
+export const toolDefs = [
+ {
+ name: 'search_services',
+ title: 'Search the x402 bazaar',
+ description:
+ 'Ranked search across the live x402 facilitator network for paid agent services (APIs and MCP tools you can pay for in stablecoin). Returns matching services with price, networks, and resource URL. Use get_service for full payment + input details.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'What you need, e.g. "weather", "image upscale", "onchain data".' },
+ type: { type: 'string', enum: ['http', 'mcp'], default: 'http', description: 'http API or mcp tool.' },
+ network: { type: 'string', description: 'Filter by CAIP-2 network, e.g. "eip155:8453" (Base) or "solana:*".' },
+ max_price_usdc: { type: 'number', minimum: 0, description: 'Only services at or below this price (USDC).' },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
+ },
+ required: ['query'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(auth);
+ const type = args.type || 'http';
+ const baz = new Bazaar({});
+ const { resources, sources, errors } = await baz.search({ query: args.query, type });
+ const filtered = applyFilters(resources, args).slice(0, args.limit || 20).map(slim);
+ return {
+ content: [{ type: 'text', text: formatList(filtered, { query: args.query }) }],
+ structuredContent: {
+ query: args.query,
+ type,
+ count: filtered.length,
+ services: filtered,
+ sources,
+ errors,
+ },
+ };
+ },
+ },
+ {
+ name: 'browse_services',
+ title: 'Browse the x402 bazaar',
+ description:
+ 'List paid agent services from the live x402 facilitator network without a search query — useful for "what can I pay for?". Returns services with price, networks, and resource URL, cheapest filters applied.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ type: { type: 'string', enum: ['http', 'mcp'], default: 'http' },
+ network: { type: 'string', description: 'Filter by CAIP-2 network, e.g. "eip155:8453".' },
+ max_price_usdc: { type: 'number', minimum: 0 },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 30 },
+ },
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(auth);
+ const type = args.type || 'http';
+ const baz = new Bazaar({});
+ const { items, sources, errors } = await baz.list({ type });
+ const filtered = applyFilters(items, args).slice(0, args.limit || 30).map(slim);
+ return {
+ content: [{ type: 'text', text: formatList(filtered) }],
+ structuredContent: { type, count: filtered.length, services: filtered, sources, errors },
+ };
+ },
+ },
+ {
+ name: 'get_service',
+ title: 'Get full details for one x402 service',
+ description:
+ 'Resolve a single x402 service by its resource URL (and tool_name for MCP services). Returns the exact payment requirements (price, asset, network, recipient), the input/output schema, and a ready-to-use pay link on three.ws. This is what you read before paying.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ resource_url: { type: 'string', format: 'uri', description: 'The service resource URL.' },
+ tool_name: { type: 'string', description: 'For MCP services, the tool name on that resource.' },
+ },
+ required: ['resource_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(auth);
+ const baz = new Bazaar({});
+ const item = await baz.get(args.resource_url, { toolName: args.tool_name });
+ if (!item) {
+ return {
+ content: [
+ { type: 'text', text: `No x402 service found for ${args.resource_url}${args.tool_name ? ` #${args.tool_name}` : ''}.` },
+ ],
+ isError: true,
+ };
+ }
+ const accepts = item.accepts.map((a) => ({
+ network: a.network,
+ price: a.priceLabel,
+ amount_atomic: a.amountAtomic,
+ asset: a.asset,
+ pay_to: a.payTo,
+ scheme: a.scheme,
+ }));
+ const pay_link = payUrl(item.resource, item.toolName);
+ const lines = [
+ `${item.serviceName || item.resource}`,
+ item.description ? item.description : '',
+ `Price: ${item.minPriceLabel || 'see options'}`,
+ `Payment options:`,
+ ...accepts.map((a) => ` • ${a.price} on ${a.network} → ${a.pay_to || '(recipient in challenge)'}`),
+ ``,
+ `Pay & call via three.ws: ${pay_link}`,
+ ].filter((l) => l !== '');
+ return {
+ content: [{ type: 'text', text: lines.join('\n') }],
+ structuredContent: {
+ type: item.type,
+ resource: item.resource,
+ tool_name: item.toolName || undefined,
+ name: item.serviceName || undefined,
+ description: item.description || undefined,
+ accepts,
+ input_schema: item.input || undefined,
+ output_schema: item.output || undefined,
+ tags: item.tags?.length ? item.tags : undefined,
+ pay_link,
+ },
+ };
+ },
+ },
+];
diff --git a/api/mcp-3d.js b/api/mcp-3d.js
new file mode 100644
index 000000000..81e401d6d
--- /dev/null
+++ b/api/mcp-3d.js
@@ -0,0 +1,49 @@
+// three.ws 3D Studio — MCP server (Streamable HTTP transport, MCP 2025-06-18).
+// POST /api/mcp-3d — tool calls GET /api/mcp-3d — SSE DELETE — terminate.
+//
+// A second, focused MCP server alongside /api/mcp: it does one thing — turn
+// text or images into interactive 3D models — and shares the main server's
+// OAuth/x402 auth, rate limiting, and transport plumbing. Registered with the
+// MCP Registry as io.github.nirholas/three-ws-3d-studio (see server-3d.json).
+import { cors, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { PROTOCOL_VERSION, dispatch } from './_mcp3d/dispatch.js';
+import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;
+
+ if (req.method === 'GET' || req.method === 'HEAD') return handleSse(req, res);
+ if (req.method === 'DELETE') return handleTerminate(req, res);
+ if (req.method !== 'POST') return send401(res, 'method not supported');
+
+ const result = await authenticateRequest(req, res);
+ if (!result) return;
+ const { auth } = result;
+
+ const ipRl = await limits.mcpIp(clientIp(req));
+ if (!ipRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
+ });
+ const userRl = await limits.mcpUser(auth.userId || auth.rateKey || clientIp(req));
+ if (!userRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
+ });
+
+ const body = await readJson(req, 1_000_000);
+ const batch = Array.isArray(body) ? body : [body];
+ if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
+
+ const responses = [];
+ for (const msg of batch) {
+ const r = await dispatch(msg, auth, req);
+ if (r !== null) responses.push(r);
+ }
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));
+});
diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.js
new file mode 100644
index 000000000..ead9fb7a5
--- /dev/null
+++ b/api/mcp-bazaar.js
@@ -0,0 +1,49 @@
+// three.ws x402 Bazaar — MCP server (Streamable HTTP transport, MCP 2025-06-18).
+// POST /api/mcp-bazaar — tool calls GET — SSE DELETE — terminate.
+//
+// Discovery surface over the live x402 facilitator network: search, browse, and
+// price paid agent services from any MCP client. Shares the main server's
+// OAuth/x402 auth, rate limiting, and transport. Registered with the MCP
+// Registry as io.github.nirholas/three-ws-x402-bazaar (see server-bazaar.json).
+import { cors, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { PROTOCOL_VERSION, dispatch } from './_mcpbazaar/dispatch.js';
+import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;
+
+ if (req.method === 'GET' || req.method === 'HEAD') return handleSse(req, res);
+ if (req.method === 'DELETE') return handleTerminate(req, res);
+ if (req.method !== 'POST') return send401(res, 'method not supported');
+
+ const result = await authenticateRequest(req, res);
+ if (!result) return;
+ const { auth } = result;
+
+ const ipRl = await limits.mcpIp(clientIp(req));
+ if (!ipRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
+ });
+ const userRl = await limits.mcpUser(auth.userId || auth.rateKey || clientIp(req));
+ if (!userRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
+ });
+
+ const body = await readJson(req, 1_000_000);
+ const batch = Array.isArray(body) ? body : [body];
+ if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
+
+ const responses = [];
+ for (const msg of batch) {
+ const r = await dispatch(msg, auth, req);
+ if (r !== null) responses.push(r);
+ }
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));
+});
diff --git a/docs/mcp-3d-studio.md b/docs/mcp-3d-studio.md
new file mode 100644
index 000000000..7b8c49eef
--- /dev/null
+++ b/docs/mcp-3d-studio.md
@@ -0,0 +1,67 @@
+# three.ws 3D Studio — MCP server
+
+Turn text or an image into an interactive, textured 3D model — directly from
+Claude, Cursor, or any MCP client. A focused companion to the main three.ws MCP
+server, registered separately as **`io.github.nirholas/three-ws-3d-studio`**.
+
+- **Endpoint:** `https://three.ws/api/mcp-3d`
+- **Transport:** Streamable HTTP (MCP `2025-06-18`)
+- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`) or x402
+- **Backend:** Microsoft TRELLIS image→3D and FLUX text→image, on Replicate
+
+## Tools
+
+| Tool | What it does |
+|------|--------------|
+| `text_to_3d(prompt, aspect_ratio?)` | Text → reference image → reconstructed GLB. Returns a `job_id` and the intermediate preview image. |
+| `image_to_3d(image_url, prompt?)` | Reconstruct a GLB from a single reference image. Returns a `job_id`. |
+| `generation_status(job_id)` | Poll a job. When done, returns the GLB URL **and** an inline `<model-viewer>` artifact. |
+| `preview_3d(glb_url, …)` | Render any public GLB as an interactive `<model-viewer>` artifact (orbit, AR, auto-rotate). |
+| `inspect_model(url)` | Structural stats: meshes, triangles, materials, textures, extensions. |
+| `optimize_model(url)` | Actionable size/perf suggestions: Draco/Meshopt, KTX2, triangle budget. |
+
+Generation is asynchronous: `text_to_3d` / `image_to_3d` return a `job_id`
+immediately, then you poll `generation_status` (reconstruction is typically
+30–90s). When a job finishes, `generation_status` returns a `text/html`
+resource — display it as an inline 3D artifact.
+
+## Use on claude.ai
+
+Add the connector with URL `https://three.ws/api/mcp-3d` and complete the OAuth
+flow. Then:
+
+> "Make a 3D model of a low-poly red fox sitting upright."
+
+Claude calls `text_to_3d`, polls `generation_status`, and renders the result as
+a live, orbitable 3D artifact in the chat.
+
+## Configuration
+
+The server needs a Replicate token (already used by the avatar regen pipeline):
+
+| Env | Purpose | Default |
+|-----|---------|---------|
+| `REPLICATE_API_TOKEN` | Required. From replicate.com/account. | — |
+| `REPLICATE_RECONSTRUCT_MODEL` | image→3D model. | `firtoz/trellis` |
+| `REPLICATE_TXT2IMG_MODEL` | text→image model for `text_to_3d`. | `black-forest-labs/flux-schnell` |
+
+Rate limits: generation is capped at 12 jobs/hour per principal (real GPU
+spend); status polling at 240/min.
+
+## Publishing to the MCP Registry
+
+The manifest is [`server-3d.json`](../server-3d.json). Publish with the
+`mcp-publisher` CLI (the GitHub-namespace ownership flow proves control of the
+`io.github.nirholas/*` namespace):
+
+```bash
+mcp-publisher login github
+mcp-publisher publish --file server-3d.json
+```
+
+## Local development
+
+```bash
+npm run dev
+npx @modelcontextprotocol/inspector http://localhost:5173/api/mcp-3d
+```
diff --git a/docs/mcp-x402-bazaar.md b/docs/mcp-x402-bazaar.md
new file mode 100644
index 000000000..a0068fbe2
--- /dev/null
+++ b/docs/mcp-x402-bazaar.md
@@ -0,0 +1,68 @@
+# three.ws x402 Bazaar — MCP server
+
+Discover paid agent services across the **live x402 facilitator network** —
+search, browse, and price any service from inside Claude, Cursor, or any MCP
+client. Registered with the MCP Registry as
+**`io.github.nirholas/three-ws-x402-bazaar`**.
+
+- **Endpoint:** `https://three.ws/api/mcp-bazaar`
+- **Transport:** Streamable HTTP (MCP `2025-06-18`)
+- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`) or x402
+- **Data:** live `/discovery/resources` from the configured x402 facilitators — no cached or synthetic listings
+
+## Tools
+
+| Tool | What it does |
+|------|--------------|
+| `search_services(query, type?, network?, max_price_usdc?, limit?)` | Ranked search over the merged facilitator catalog. |
+| `browse_services(type?, network?, max_price_usdc?, limit?)` | List services without a query — "what can I pay for?". |
+| `get_service(resource_url, tool_name?)` | Full payment requirements (price, asset, network, recipient), input/output schema, and a ready pay link. |
+
+`type` is `http` (paid HTTP APIs) or `mcp` (paid MCP tools). `network` is a
+CAIP-2 id, e.g. `eip155:8453` (Base) or `solana:*`. `max_price_usdc` filters to
+services at or below a dollar ceiling.
+
+## Use on claude.ai
+
+Add the connector with URL `https://three.ws/api/mcp-bazaar` and complete OAuth.
+Then:
+
+> "Find me a cheap weather API I can pay for, on Base."
+
+Claude calls `search_services`, then `get_service` for the top hit, and shows
+the price, the network, and a one-click pay link.
+
+## Paying
+
+The bazaar is a **discovery** surface. `get_service` returns the exact x402
+payment requirements plus a `pay_link` to the three.ws hosted payer
+(`/pay`), which settles the payment with your three.ws agent wallet and returns
+the service response.
+
+Autonomous in-MCP `pay_and_call` (the server pays and calls on your behalf) is a
+deliberate, wallet-gated extension — it spends real funds, so it ships only
+behind explicit per-user wallet authorization rather than being enabled for any
+connected client by default.
+
+## Configuration
+
+Facilitators come from the platform default set (`defaultFacilitators()` in
+`api/_lib/x402/bazaar-client.js`); no extra env is required to read the bazaar.
+Discovery is rate-limited to 60 calls/min per principal to bound facilitator
+egress.
+
+## Publishing to the MCP Registry
+
+Manifest: [`server-bazaar.json`](../server-bazaar.json).
+
+```bash
+mcp-publisher login github
+mcp-publisher publish --file server-bazaar.json
+```
+
+## Local development
+
+```bash
+npm run dev
+npx @modelcontextprotocol/inspector http://localhost:5173/api/mcp-bazaar
+```
diff --git a/package.json b/package.json
index 5ec92c1d1..71c738ad3 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,9 @@
"multiplayer",
"packages/avatar-schema",
"packages/avatar-cli",
- "packages/viewer-presets"
+ "packages/viewer-presets",
+ "packages/pumpfun-mcp",
+ "packages/ibm-watsonx-mcp"
],
"main": "src/app.js",
"browserslist": [
diff --git a/packages/ibm-watsonx-mcp/LICENSE b/packages/ibm-watsonx-mcp/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/ibm-watsonx-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/ibm-watsonx-mcp/README.md b/packages/ibm-watsonx-mcp/README.md
new file mode 100644
index 000000000..6031078b1
--- /dev/null
+++ b/packages/ibm-watsonx-mcp/README.md
@@ -0,0 +1,94 @@
+# @three-ws/ibm-watsonx-mcp
+
+An [MCP](https://modelcontextprotocol.io) server for **IBM watsonx.ai**. It exposes IBM Granite (and any model in your watsonx.ai account) to MCP clients — Claude Desktop, Claude Code, Cursor, and any other MCP host — as five tools: chat, text generation, embeddings, tokenization, and model discovery.
+
+The server talks **directly** to the watsonx.ai as-a-Service REST API using **your own IBM Cloud credentials**. It mints an IAM bearer token from your API key, caches it until just before expiry, and scopes every call to your project. No intermediary backend, no telemetry, no mock data.
+
+> Community-built and not affiliated with IBM. Registry name: `io.github.nirholas/ibm-watsonx`.
+
+## Tools
+
+| Tool | What it does |
+| --- | --- |
+| `watsonx_chat` | Chat completion from a list of role/content messages. Returns reply + token usage. |
+| `watsonx_generate` | Raw prompt completion with decoding control (greedy/sample, stop sequences). |
+| `watsonx_embed` | Embedding vectors for one or more texts. Returns one vector per input. |
+| `watsonx_tokenize` | Token count (and optionally the tokens) for a text against a model tokenizer. |
+| `watsonx_list_models` | List foundation models available to your account/region, optionally filtered. |
+
+## Prerequisites
+
+1. An IBM Cloud account with watsonx.ai provisioned — [sign up](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx) (free tier available).
+2. An **IBM Cloud API key** — create one at <https://cloud.ibm.com/iam/apikeys>.
+3. Your **watsonx.ai project id** — open the project → **Manage** → **General** → **Project ID**.
+
+## Configuration
+
+| Env var | Required | Default |
+| --- | --- | --- |
+| `WATSONX_API_KEY` | ✅ | — |
+| `WATSONX_PROJECT_ID` | ✅ (or `WATSONX_SPACE_ID`) | — |
+| `WATSONX_URL` | | `https://us-south.ml.cloud.ibm.com` |
+| `WATSONX_MODEL_ID` | | `ibm/granite-3-8b-instruct` |
+| `WATSONX_EMBED_MODEL_ID` | | `ibm/granite-embedding-278m-multilingual` |
+| `WATSONX_API_VERSION` | | `2024-05-31` |
+
+Regional hosts: `us-south`, `eu-de`, `eu-gb`, `jp-tok`, `au-syd`, `ca-tor` — e.g. `https://eu-de.ml.cloud.ibm.com`.
+
+## Use with Claude Desktop / Claude Code / Cursor
+
+Add to your MCP config (`claude_desktop_config.json`, or via `claude mcp add`):
+
+```json
+{
+ "mcpServers": {
+ "ibm-watsonx": {
+ "command": "npx",
+ "args": ["-y", "@three-ws/ibm-watsonx-mcp"],
+ "env": {
+ "WATSONX_API_KEY": "your-ibm-cloud-api-key",
+ "WATSONX_PROJECT_ID": "your-watsonx-project-id"
+ }
+ }
+ }
+}
+```
+
+## Run standalone
+
+```bash
+WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp
+```
+
+Inspect the tool surface with the MCP Inspector:
+
+```bash
+npx -y @modelcontextprotocol/inspector npx @three-ws/ibm-watsonx-mcp
+```
+
+## Example calls
+
+```jsonc
+// watsonx_chat
+{ "messages": [{ "role": "user", "content": "Explain MCP in one sentence." }] }
+
+// watsonx_generate
+{ "input": "Write a haiku about Kubernetes.", "decoding_method": "sample", "temperature": 0.7, "max_new_tokens": 60 }
+
+// watsonx_embed
+{ "inputs": ["lakehouse", "data warehouse"] }
+
+// watsonx_list_models
+{ "filter": "function_embedding" }
+```
+
+## How auth works
+
+`WATSONX_API_KEY` is exchanged for a short-lived IAM bearer token at
+`https://iam.cloud.ibm.com/identity/token` (`grant_type=urn:ibm:params:oauth:grant-type:apikey`).
+The token is cached in-process and refreshed ~5 minutes before it expires. Your API
+key never leaves your machine except in that single IAM exchange.
+
+## License
+
+Apache-2.0
diff --git a/packages/ibm-watsonx-mcp/package.json b/packages/ibm-watsonx-mcp/package.json
new file mode 100644
index 000000000..c00a5c713
--- /dev/null
+++ b/packages/ibm-watsonx-mcp/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "@three-ws/ibm-watsonx-mcp",
+ "version": "0.1.0",
+ "description": "MCP server for IBM watsonx.ai — chat, text generation, embeddings, tokenization, and model discovery with IBM Granite foundation models. Uses your own IBM Cloud credentials.",
+ "type": "module",
+ "author": "nirholas",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "mcpName": "io.github.nirholas/ibm-watsonx",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws.git",
+ "directory": "packages/ibm-watsonx-mcp"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "keywords": [
+ "mcp",
+ "model-context-protocol",
+ "ibm",
+ "watsonx",
+ "watsonx.ai",
+ "granite",
+ "ibm-granite",
+ "foundation-models",
+ "embeddings",
+ "llm",
+ "ai-agent",
+ "three.ws"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "src",
+ "server.json",
+ "README.md",
+ "LICENSE"
+ ],
+ "bin": {
+ "ibm-watsonx-mcp": "./src/index.js"
+ },
+ "main": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "start": "node src/index.js",
+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0"
+ }
+}
diff --git a/packages/ibm-watsonx-mcp/server.json b/packages/ibm-watsonx-mcp/server.json
new file mode 100644
index 000000000..783ba17cb
--- /dev/null
+++ b/packages/ibm-watsonx-mcp/server.json
@@ -0,0 +1,66 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/ibm-watsonx",
+ "description": "IBM watsonx.ai MCP server — chat, text generation, embeddings, tokenization, and model discovery with IBM Granite foundation models, using your own IBM Cloud credentials.",
+ "repository": {
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github",
+ "subfolder": "packages/ibm-watsonx-mcp"
+ },
+ "version": "0.1.0",
+ "packages": [
+ {
+ "registryType": "npm",
+ "identifier": "@three-ws/ibm-watsonx-mcp",
+ "version": "0.1.0",
+ "transport": {
+ "type": "stdio"
+ },
+ "environmentVariables": [
+ {
+ "name": "WATSONX_API_KEY",
+ "description": "IBM Cloud API key (create one at https://cloud.ibm.com/iam/apikeys).",
+ "isRequired": true,
+ "isSecret": true,
+ "format": "string"
+ },
+ {
+ "name": "WATSONX_PROJECT_ID",
+ "description": "watsonx.ai project id (Project → Manage → General → Project ID). Provide this or WATSONX_SPACE_ID.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "WATSONX_SPACE_ID",
+ "description": "watsonx.ai deployment space id. Alternative to WATSONX_PROJECT_ID.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "WATSONX_URL",
+ "description": "Regional inference host. Defaults to https://us-south.ml.cloud.ibm.com.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "WATSONX_MODEL_ID",
+ "description": "Default chat/generation model id. Defaults to ibm/granite-3-8b-instruct.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "WATSONX_EMBED_MODEL_ID",
+ "description": "Default embedding model id. Defaults to ibm/granite-embedding-278m-multilingual.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "WATSONX_API_VERSION",
+ "description": "watsonx.ai REST API version date. Defaults to 2024-05-31.",
+ "isRequired": false,
+ "format": "string"
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/ibm-watsonx-mcp/src/index.js b/packages/ibm-watsonx-mcp/src/index.js
new file mode 100644
index 000000000..7cc37b5bd
--- /dev/null
+++ b/packages/ibm-watsonx-mcp/src/index.js
@@ -0,0 +1,99 @@
+#!/usr/bin/env node
+// @three-ws/ibm-watsonx-mcp — stdio MCP server for IBM watsonx.ai.
+//
+// Exposes IBM Granite (and any model in your watsonx.ai account) as MCP tools:
+// chat, raw text generation, embeddings, tokenization, and model discovery.
+//
+// Architecture: this process talks DIRECTLY to the watsonx.ai as-a-Service REST
+// API using YOUR IBM Cloud credentials. It mints an IAM bearer token from your
+// API key, caches it until just before expiry, and scopes every inference call
+// to your project (or deployment space). There is no intermediary backend and
+// no mock path — all data comes from IBM. Configure via environment variables:
+//
+// WATSONX_API_KEY (required) IBM Cloud API key → https://cloud.ibm.com/iam/apikeys
+// WATSONX_PROJECT_ID (required, or WATSONX_SPACE_ID) watsonx.ai project id
+// WATSONX_URL (optional) region host, default https://us-south.ml.cloud.ibm.com
+// WATSONX_MODEL_ID (optional) default chat/gen model, default ibm/granite-3-8b-instruct
+// WATSONX_EMBED_MODEL_ID(optional) default embedding model
+// WATSONX_API_VERSION (optional) REST version date, default 2024-05-31
+//
+// Run standalone: WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp
+// Inspect: npx -y @modelcontextprotocol/inspector npx @three-ws/ibm-watsonx-mcp
+
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+import {
+ ListToolsRequestSchema,
+ CallToolRequestSchema,
+} from '@modelcontextprotocol/sdk/types.js';
+
+import { loadConfig, WatsonxClient, WatsonxError } from './watsonx.js';
+import { buildTools } from './tools.js';
+
+const SERVER_NAME = 'three.ws-ibm-watsonx-mcp';
+const SERVER_VERSION = '0.1.0';
+
+async function main() {
+ // Fail fast and clearly if credentials are missing — the message names the
+ // exact env var and where to get its value.
+ let config;
+ try {
+ config = loadConfig();
+ } catch (err) {
+ process.stderr.write(`[ibm-watsonx-mcp] configuration error: ${err.message}\n`);
+ process.exit(1);
+ return;
+ }
+
+ const client = new WatsonxClient(config);
+ const tools = buildTools(client);
+ const byName = new Map(tools.map((t) => [t.definition.name, t]));
+
+ const server = new Server(
+ { name: SERVER_NAME, version: SERVER_VERSION },
+ {
+ capabilities: { tools: { listChanged: false } },
+ instructions:
+ 'IBM watsonx.ai tools powered by Granite foundation models. Use watsonx_chat ' +
+ 'for conversational completions, watsonx_generate for raw prompt completion with ' +
+ 'decoding control, watsonx_embed for embedding vectors, watsonx_tokenize to count ' +
+ 'tokens before a call, and watsonx_list_models to discover available models. ' +
+ `Default model: ${config.chatModel}. All calls use your own IBM Cloud account.`,
+ },
+ );
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
+ tools: tools.map((t) => t.definition),
+ }));
+
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const { name, arguments: args } = request.params;
+ const tool = byName.get(name);
+ if (!tool) {
+ return { isError: true, content: [{ type: 'text', text: `Unknown tool: ${name}` }] };
+ }
+ try {
+ return await tool.handler(args || {});
+ } catch (err) {
+ // Surface the real upstream cause (IBM status + message) rather than a
+ // generic failure, so the client can act on auth/quota/model errors.
+ const text =
+ err instanceof WatsonxError
+ ? `${err.message}${err.detail ? ` (${JSON.stringify(err.detail)})` : ''}`
+ : `Tool ${name} failed: ${err.message}`;
+ return { isError: true, content: [{ type: 'text', text }] };
+ }
+ });
+
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ process.stderr.write(
+ `[ibm-watsonx-mcp] ${SERVER_NAME} v${SERVER_VERSION} ready — ${tools.length} tools, ` +
+ `model ${config.chatModel} @ ${config.url}\n`,
+ );
+}
+
+main().catch((err) => {
+ process.stderr.write(`[ibm-watsonx-mcp] fatal: ${err?.stack || err}\n`);
+ process.exit(1);
+});
diff --git a/packages/ibm-watsonx-mcp/src/tools.js b/packages/ibm-watsonx-mcp/src/tools.js
new file mode 100644
index 000000000..ed6a6451c
--- /dev/null
+++ b/packages/ibm-watsonx-mcp/src/tools.js
@@ -0,0 +1,208 @@
+// Tool surface for the IBM watsonx.ai MCP server.
+//
+// Each entry pairs an MCP tool definition (name + JSON-Schema input) with a
+// handler that maps validated arguments onto a WatsonxClient call and shapes
+// the response into MCP content. Handlers trust their inputs (the schema is the
+// boundary) and let WatsonxError propagate — the server turns those into MCP
+// tool errors with the real upstream cause.
+
+// Shared decoding parameters reused by chat and generate.
+const samplingProps = {
+ max_tokens: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 4096,
+ description: 'Maximum number of tokens to generate.',
+ },
+ temperature: {
+ type: 'number',
+ minimum: 0,
+ maximum: 2,
+ description: 'Sampling temperature. 0 is greedy/deterministic.',
+ },
+ top_p: { type: 'number', minimum: 0, maximum: 1, description: 'Nucleus sampling probability mass.' },
+};
+
+// Build a chat `parameters` object from loose tool args, omitting unset keys.
+function chatParams({ max_tokens, temperature, top_p }) {
+ const p = {};
+ if (max_tokens != null) p.max_tokens = max_tokens;
+ if (temperature != null) p.temperature = temperature;
+ if (top_p != null) p.top_p = top_p;
+ return Object.keys(p).length ? p : undefined;
+}
+
+// Render a JSON object as a pretty MCP text block plus structuredContent, so
+// both humans and programmatic clients get a usable result.
+function jsonResult(structured, summary) {
+ const text = summary ? `${summary}\n\n${JSON.stringify(structured, null, 2)}` : JSON.stringify(structured, null, 2);
+ return { content: [{ type: 'text', text }], structuredContent: structured };
+}
+
+export function buildTools(client) {
+ return [
+ {
+ definition: {
+ name: 'watsonx_chat',
+ description:
+ 'Chat completion with an IBM Granite (or other watsonx.ai) model. Pass a ' +
+ 'list of role/content messages and get the assistant reply plus token usage.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ messages: {
+ type: 'array',
+ minItems: 1,
+ description: 'Conversation so far, oldest first.',
+ items: {
+ type: 'object',
+ properties: {
+ role: { type: 'string', enum: ['system', 'user', 'assistant'] },
+ content: { type: 'string' },
+ },
+ required: ['role', 'content'],
+ },
+ },
+ model: {
+ type: 'string',
+ description: 'Override the model id (default: the server WATSONX_MODEL_ID).',
+ },
+ ...samplingProps,
+ },
+ required: ['messages'],
+ },
+ },
+ handler: async (args) => {
+ const result = await client.chat(args.messages, {
+ model: args.model,
+ parameters: chatParams(args),
+ });
+ return jsonResult(result, result.text);
+ },
+ },
+
+ {
+ definition: {
+ name: 'watsonx_generate',
+ description:
+ 'Raw text generation from a single prompt (no chat templating). Use for ' +
+ 'completion-style tasks and fine decoding control via greedy or sampling.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ input: { type: 'string', description: 'The prompt to complete.' },
+ model: { type: 'string', description: 'Override the model id.' },
+ max_new_tokens: { type: 'integer', minimum: 1, maximum: 4096 },
+ temperature: { type: 'number', minimum: 0, maximum: 2 },
+ decoding_method: {
+ type: 'string',
+ enum: ['greedy', 'sample'],
+ description: 'greedy is deterministic; sample uses temperature/top_p.',
+ },
+ stop_sequences: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Generation halts when any of these strings is produced.',
+ },
+ },
+ required: ['input'],
+ },
+ },
+ handler: async (args) => {
+ const parameters = {};
+ if (args.max_new_tokens != null) parameters.max_new_tokens = args.max_new_tokens;
+ if (args.temperature != null) parameters.temperature = args.temperature;
+ if (args.decoding_method) parameters.decoding_method = args.decoding_method;
+ if (args.stop_sequences?.length) parameters.stop_sequences = args.stop_sequences;
+ const result = await client.generate(args.input, {
+ model: args.model,
+ parameters: Object.keys(parameters).length ? parameters : undefined,
+ });
+ return jsonResult(result, result.text);
+ },
+ },
+
+ {
+ definition: {
+ name: 'watsonx_embed',
+ description:
+ 'Generate embedding vectors for one or more texts using an IBM Granite ' +
+ 'embedding model. Returns one vector per input plus the vector dimensionality.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ inputs: {
+ type: 'array',
+ minItems: 1,
+ maxItems: 1000,
+ items: { type: 'string' },
+ description: 'Texts to embed.',
+ },
+ model: { type: 'string', description: 'Override the embedding model id.' },
+ },
+ required: ['inputs'],
+ },
+ },
+ handler: async (args) => {
+ const result = await client.embed(args.inputs, { model: args.model });
+ return jsonResult(
+ result,
+ `Embedded ${result.inputCount} input(s) into ${result.dimensions}-dim vectors using ${result.model}.`,
+ );
+ },
+ },
+
+ {
+ definition: {
+ name: 'watsonx_tokenize',
+ description:
+ 'Count tokens (and optionally return them) for a text against a model ' +
+ "tokenizer. Use to budget context and cost before a generation call.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ input: { type: 'string' },
+ model: { type: 'string', description: 'Override the model id.' },
+ return_tokens: {
+ type: 'boolean',
+ default: false,
+ description: 'Include the token strings, not just the count.',
+ },
+ },
+ required: ['input'],
+ },
+ },
+ handler: async (args) => {
+ const result = await client.tokenize(args.input, {
+ model: args.model,
+ returnTokens: Boolean(args.return_tokens),
+ });
+ return jsonResult(result, `${result.tokenCount} tokens (${result.model}).`);
+ },
+ },
+
+ {
+ definition: {
+ name: 'watsonx_list_models',
+ description:
+ 'List the foundation models available to your watsonx.ai account and region. ' +
+ 'Optionally filter by supported function, e.g. text_generation or embedding.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ filter: {
+ type: 'string',
+ description:
+ 'Filter expression, e.g. "function_text_generation" or "function_embedding".',
+ },
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 100 },
+ },
+ },
+ },
+ handler: async (args) => {
+ const models = await client.listModels({ filter: args.filter, limit: args.limit });
+ return jsonResult({ count: models.length, models }, `${models.length} model(s) available.`);
+ },
+ },
+ ];
+}
diff --git a/packages/ibm-watsonx-mcp/src/watsonx.js b/packages/ibm-watsonx-mcp/src/watsonx.js
new file mode 100644
index 000000000..895f55dcc
--- /dev/null
+++ b/packages/ibm-watsonx-mcp/src/watsonx.js
@@ -0,0 +1,268 @@
+// IBM watsonx.ai REST client.
+//
+// A small, dependency-free wrapper over the watsonx.ai as-a-Service REST API.
+// It owns the two things every call needs: a fresh IAM bearer token (minted
+// from an IBM Cloud API key and cached until just before expiry) and the
+// project/space scoping that watsonx requires on every inference request.
+//
+// Every method hits a real IBM endpoint. There is no mock or sample path — a
+// missing credential or an upstream failure surfaces as a thrown WatsonxError
+// so the MCP layer can report the true cause to the caller.
+
+const IAM_TOKEN_URL = 'https://iam.cloud.ibm.com/identity/token';
+
+// Refresh the IAM token this many ms before its stated expiry, so an in-flight
+// request never races the hard expiry boundary.
+const TOKEN_SKEW_MS = 5 * 60 * 1000;
+
+export class WatsonxError extends Error {
+ constructor(message, { status, detail } = {}) {
+ super(message);
+ this.name = 'WatsonxError';
+ this.status = status;
+ this.detail = detail;
+ }
+}
+
+// Read and validate configuration from the environment exactly once. Throws a
+// WatsonxError with an actionable message if a required credential is absent,
+// so the server fails loudly at startup rather than on the first tool call.
+export function loadConfig(env = process.env) {
+ const apiKey = env.WATSONX_API_KEY?.trim();
+ if (!apiKey) {
+ throw new WatsonxError(
+ 'WATSONX_API_KEY is not set. Create an IBM Cloud API key at ' +
+ 'https://cloud.ibm.com/iam/apikeys and export it as WATSONX_API_KEY.',
+ );
+ }
+
+ const projectId = env.WATSONX_PROJECT_ID?.trim();
+ const spaceId = env.WATSONX_SPACE_ID?.trim();
+ if (!projectId && !spaceId) {
+ throw new WatsonxError(
+ 'Set WATSONX_PROJECT_ID (or WATSONX_SPACE_ID). Find your project id under ' +
+ 'the watsonx.ai project → Manage → General → Project ID.',
+ );
+ }
+
+ return {
+ apiKey,
+ projectId,
+ spaceId,
+ // Region inference host. us-south is the default deployment region.
+ url: (env.WATSONX_URL?.trim() || 'https://us-south.ml.cloud.ibm.com').replace(/\/$/, ''),
+ iamUrl: env.WATSONX_IAM_URL?.trim() || IAM_TOKEN_URL,
+ apiVersion: env.WATSONX_API_VERSION?.trim() || '2024-05-31',
+ chatModel: env.WATSONX_MODEL_ID?.trim() || 'ibm/granite-3-8b-instruct',
+ embedModel: env.WATSONX_EMBED_MODEL_ID?.trim() || 'ibm/granite-embedding-278m-multilingual',
+ timeoutMs: Number(env.WATSONX_TIMEOUT_MS) || 60_000,
+ };
+}
+
+export class WatsonxClient {
+ constructor(config) {
+ this.config = config;
+ // Cached IAM token: { token, expiresAt } where expiresAt is epoch ms.
+ this._token = null;
+ // In-flight token request, so concurrent calls share one IAM round-trip.
+ this._tokenPromise = null;
+ }
+
+ // Return the project/space scoping object that every inference body needs.
+ _scope() {
+ return this.config.projectId
+ ? { project_id: this.config.projectId }
+ : { space_id: this.config.spaceId };
+ }
+
+ // Mint (or reuse) an IAM bearer token. The IBM Cloud IAM service exchanges a
+ // long-lived API key for a ~1h bearer token; we cache it and refresh a few
+ // minutes early. Concurrent callers coalesce onto a single in-flight request.
+ async _getToken() {
+ const now = Date.now();
+ if (this._token && this._token.expiresAt - TOKEN_SKEW_MS > now) {
+ return this._token.token;
+ }
+ if (this._tokenPromise) return this._tokenPromise;
+
+ this._tokenPromise = (async () => {
+ const body = new URLSearchParams({
+ grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
+ apikey: this.config.apiKey,
+ });
+ const res = await this._fetch(this.config.iamUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ accept: 'application/json',
+ },
+ body,
+ });
+ const data = await this._json(res);
+ if (!res.ok || !data.access_token) {
+ throw new WatsonxError('IAM authentication failed — check WATSONX_API_KEY.', {
+ status: res.status,
+ detail: data.errorMessage || data.errorCode || data,
+ });
+ }
+ const expiresAt = now + (Number(data.expires_in) || 3600) * 1000;
+ this._token = { token: data.access_token, expiresAt };
+ return this._token.token;
+ })();
+
+ try {
+ return await this._tokenPromise;
+ } finally {
+ this._tokenPromise = null;
+ }
+ }
+
+ // fetch with an AbortController-backed timeout. Network/timeout failures
+ // become WatsonxError so callers never see a bare undefined.
+ async _fetch(url, init) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), this.config.timeoutMs);
+ try {
+ return await fetch(url, { ...init, signal: controller.signal });
+ } catch (err) {
+ if (err.name === 'AbortError') {
+ throw new WatsonxError(`Request to ${url} timed out after ${this.config.timeoutMs}ms.`);
+ }
+ throw new WatsonxError(`Network error calling ${url}: ${err.message}`);
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ async _json(res) {
+ const text = await res.text();
+ if (!text) return {};
+ try {
+ return JSON.parse(text);
+ } catch {
+ return { _raw: text };
+ }
+ }
+
+ // Authenticated POST to a watsonx ml endpoint. Adds the version query param,
+ // bearer token, and scoping; raises a WatsonxError carrying the upstream
+ // status and IBM error payload on any non-2xx response.
+ async _post(path, payload) {
+ const token = await this._getToken();
+ const url = `${this.config.url}${path}?version=${this.config.apiVersion}`;
+ const res = await this._fetch(url, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ },
+ body: JSON.stringify({ ...payload, ...this._scope() }),
+ });
+ const data = await this._json(res);
+ if (!res.ok) throw this._upstreamError(res.status, data);
+ return data;
+ }
+
+ async _get(path, params = {}) {
+ const token = await this._getToken();
+ const query = new URLSearchParams({ version: this.config.apiVersion, ...params });
+ const res = await this._fetch(`${this.config.url}${path}?${query}`, {
+ method: 'GET',
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
+ });
+ const data = await this._json(res);
+ if (!res.ok) throw this._upstreamError(res.status, data);
+ return data;
+ }
+
+ _upstreamError(status, data) {
+ const first = Array.isArray(data?.errors) ? data.errors[0] : null;
+ const message = first?.message || data?.message || data?._raw || 'watsonx.ai request failed';
+ return new WatsonxError(`watsonx.ai error (${status}): ${message}`, {
+ status,
+ detail: first?.code || data?.trace || undefined,
+ });
+ }
+
+ // --- Inference surface ---------------------------------------------------
+
+ // Chat completion. messages is an array of { role, content }. Returns the
+ // assistant text plus token usage and the model that served the request.
+ async chat(messages, { model, parameters } = {}) {
+ const data = await this._post('/ml/v1/text/chat', {
+ model_id: model || this.config.chatModel,
+ messages,
+ ...(parameters ? { parameters } : {}),
+ });
+ const choice = data.choices?.[0];
+ return {
+ text: choice?.message?.content ?? '',
+ finishReason: choice?.finish_reason,
+ usage: data.usage,
+ model: data.model_id || model || this.config.chatModel,
+ };
+ }
+
+ // Raw text generation (prompt in, completion out) for non-chat models and
+ // fine-grained decoding control (greedy/sampling, stop sequences, etc.).
+ async generate(input, { model, parameters } = {}) {
+ const data = await this._post('/ml/v1/text/generation', {
+ model_id: model || this.config.chatModel,
+ input,
+ ...(parameters ? { parameters } : {}),
+ });
+ const result = data.results?.[0];
+ return {
+ text: result?.generated_text ?? '',
+ generatedTokenCount: result?.generated_token_count,
+ inputTokenCount: result?.input_token_count,
+ stopReason: result?.stop_reason,
+ model: model || this.config.chatModel,
+ };
+ }
+
+ // Embeddings for one or more input strings. Returns a vector per input.
+ async embed(inputs, { model } = {}) {
+ const data = await this._post('/ml/v1/text/embeddings', {
+ model_id: model || this.config.embedModel,
+ inputs,
+ });
+ return {
+ model: model || this.config.embedModel,
+ vectors: (data.results || []).map((r) => r.embedding),
+ inputCount: inputs.length,
+ dimensions: data.results?.[0]?.embedding?.length ?? 0,
+ };
+ }
+
+ // Tokenize an input against a model's tokenizer — useful for cost/context
+ // budgeting before a generation call.
+ async tokenize(input, { model, returnTokens = false } = {}) {
+ const data = await this._post('/ml/v1/text/tokenization', {
+ model_id: model || this.config.chatModel,
+ input,
+ parameters: { return_tokens: returnTokens },
+ });
+ return {
+ model: model || this.config.chatModel,
+ tokenCount: data.result?.token_count ?? 0,
+ tokens: data.result?.tokens,
+ };
+ }
+
+ // List the foundation models available to this account/region. Optionally
+ // filter by supported function (e.g. text_generation, embedding).
+ async listModels({ filter, limit = 100 } = {}) {
+ const params = { limit: String(Math.min(limit, 200)) };
+ if (filter) params.filters = filter;
+ const data = await this._get('/ml/v1/foundation_model_specs', params);
+ return (data.resources || []).map((m) => ({
+ model_id: m.model_id,
+ label: m.label,
+ provider: m.provider,
+ functions: (m.functions || []).map((f) => f.id),
+ short_description: m.short_description,
+ }));
+ }
+}
diff --git a/packages/pumpfun-mcp/LICENSE b/packages/pumpfun-mcp/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/pumpfun-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/pumpfun-mcp/README.md b/packages/pumpfun-mcp/README.md
new file mode 100644
index 000000000..f3d725b38
--- /dev/null
+++ b/packages/pumpfun-mcp/README.md
@@ -0,0 +1,81 @@
+# @three-ws/pumpfun-mcp
+
+A **free, read-only** [Model Context Protocol](https://modelcontextprotocol.io) server for **pump.fun** and **Solana**. Give Claude — or any MCP client — live token discovery, on-chain bonding-curve and holder analysis, creator fee-claim tracking, Solana Name Service resolution, KOL signals, and read-only swap quotes.
+
+**No API keys. No RPC URL. No wallet.** Every Solana RPC and pump.fun API call runs server-side on the canonical [three.ws](https://three.ws) backend, so the data is live and on-chain and the client stays zero-config.
+
+## Install
+
+### Claude Desktop / Claude Code / Cursor
+
+Add to your MCP config (`claude_desktop_config.json`, `.mcp.json`, etc.):
+
+```json
+{
+ "mcpServers": {
+ "pumpfun": {
+ "command": "npx",
+ "args": ["-y", "@three-ws/pumpfun-mcp"]
+ }
+ }
+}
+```
+
+That's it — restart the client and the pump.fun tools appear.
+
+### Run directly
+
+```bash
+npx @three-ws/pumpfun-mcp
+# or
+npm i -g @three-ws/pumpfun-mcp && pumpfun-mcp
+```
+
+### Inspect the tools
+
+```bash
+npx -y @modelcontextprotocol/inspector npx @three-ws/pumpfun-mcp
+```
+
+## Tools
+
+| Tool | What it does |
+| --- | --- |
+| `searchTokens` | Search pump.fun tokens by name, symbol, or mint. |
+| `getTokenDetails` | Full metadata for a mint. |
+| `getBondingCurve` | Real/virtual reserves + graduation progress (on-chain). |
+| `getTokenTrades` | Recent buy/sell history for a token. |
+| `getTrendingTokens` | Top tokens by market cap. |
+| `getNewTokens` | Most recently launched tokens. |
+| `getGraduatedTokens` | Tokens that graduated to the Raydium AMM. |
+| `getKingOfTheHill` | Highest-cap token still on the bonding curve. |
+| `getTokenHolders` | Top holders with concentration analysis (on-chain). |
+| `getCreatorProfile` | A creator's tokens with rug-pull risk flags. |
+| `kol_radar` | gmgn-style early-detection radar signals. |
+| `kol_leaderboard` | Top KOL traders ranked by P&L. |
+| `pumpfun_list_claims` | Recent creator fee-claim events (on-chain). |
+| `pumpfun_watch_claims` | Fee claims for a creator within a look-back window. |
+| `pumpfun_first_claims` | First-ever creator claims — a cash-out signal. |
+| `pumpfun_quote_swap` | Read-only pump.fun AMM swap quote (no signing). |
+| `pumpfun_watch_whales` | Collect large trades on a token over a short window. |
+| `pumpfun_vanity_mint` | Grind a vanity Solana keypair (returns secret to caller; never stored). |
+| `sns_resolve` | Resolve a `.sol` domain to its owner wallet. |
+| `sns_reverseLookup` | Reverse-lookup a wallet to its primary `.sol` domain. |
+| `social_cashtag_sentiment` | Deterministic lexicon sentiment over supplied posts. |
+| `social_x_post_impact` | Correlate an X post to bonding-curve price impact. |
+
+Read-only by design: no tool signs or sends a transaction. `pumpfun_quote_swap` only quotes; `pumpfun_vanity_mint` returns a keypair for you to use yourself.
+
+## Configuration
+
+| Env var | Default | Purpose |
+| --- | --- | --- |
+| `PUMPFUN_MCP_URL` | `https://three.ws/api/pump-fun-mcp` | Backend endpoint. Override only to self-host the handler. |
+
+## How it works
+
+This package is a small stdio ↔ HTTP bridge. It forwards MCP `tools/call` requests to the canonical three.ws pump.fun JSON-RPC backend, which performs the actual Solana RPC reads and pump.fun API queries. That keeps one authoritative implementation, ships no secrets to clients, and means the tool surface stays current automatically (the live `tools/list` is fetched at startup, with a bundled fallback for offline use).
+
+## License
+
+Apache-2.0 — see [LICENSE](./LICENSE).
diff --git a/packages/pumpfun-mcp/package.json b/packages/pumpfun-mcp/package.json
new file mode 100644
index 000000000..65203b26d
--- /dev/null
+++ b/packages/pumpfun-mcp/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@three-ws/pumpfun-mcp",
+ "version": "0.1.0",
+ "description": "Free, read-only pump.fun + Solana MCP server — token discovery, on-chain bonding-curve & holder analysis, creator fee-claim tracking, SNS resolution, KOL signals, and swap quotes. No API keys.",
+ "type": "module",
+ "author": "nirholas",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws.git",
+ "directory": "packages/pumpfun-mcp"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "keywords": [
+ "mcp",
+ "model-context-protocol",
+ "pump.fun",
+ "pumpfun",
+ "solana",
+ "memecoin",
+ "bonding-curve",
+ "sns",
+ "solana-name-service",
+ "ai-agent",
+ "three.ws"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "src",
+ "server.json",
+ "README.md",
+ "LICENSE"
+ ],
+ "bin": {
+ "pumpfun-mcp": "./src/index.js"
+ },
+ "main": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "start": "node src/index.js",
+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0"
+ }
+}
diff --git a/packages/pumpfun-mcp/server.json b/packages/pumpfun-mcp/server.json
new file mode 100644
index 000000000..21342ad68
--- /dev/null
+++ b/packages/pumpfun-mcp/server.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/pumpfun-solana-mcp",
+ "description": "Free, read-only pump.fun + Solana MCP server: token discovery, on-chain bonding-curve & holder analysis, creator fee-claim tracking, SNS name resolution, KOL radar/leaderboard signals, and read-only swap quotes. No API keys required.",
+ "repository": {
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github"
+ },
+ "version": "0.1.0",
+ "packages": [
+ {
+ "registryType": "npm",
+ "identifier": "@three-ws/pumpfun-mcp",
+ "version": "0.1.0",
+ "transport": {
+ "type": "stdio"
+ },
+ "environmentVariables": [
+ {
+ "name": "PUMPFUN_MCP_URL",
+ "description": "Override the canonical pump.fun MCP backend endpoint. Defaults to https://three.ws/api/pump-fun-mcp — set this only when self-hosting the handler.",
+ "format": "string",
+ "isRequired": false,
+ "default": "https://three.ws/api/pump-fun-mcp"
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/pumpfun-mcp/src/index.js b/packages/pumpfun-mcp/src/index.js
new file mode 100644
index 000000000..398f14795
--- /dev/null
+++ b/packages/pumpfun-mcp/src/index.js
@@ -0,0 +1,145 @@
+#!/usr/bin/env node
+// @three-ws/pumpfun-mcp — stdio MCP server for pump.fun + Solana read-only data.
+//
+// A zero-config, free MCP server. It exposes pump.fun token discovery, on-chain
+// bonding-curve / holder analysis, creator fee-claim tracking, SNS name
+// resolution, KOL radar/leaderboard signals, and read-only swap quotes.
+//
+// Architecture: this process is a thin stdio <-> HTTP bridge in front of the
+// canonical three.ws pump.fun MCP backend (https://three.ws/api/pump-fun-mcp).
+// The backend is the single source of truth — it performs every Solana RPC and
+// pump.fun API call server-side, so clients need no RPC URL, no API keys, and
+// no secrets. All data is live and on-chain; there is no mock or sample path.
+//
+// Override the backend with PUMPFUN_MCP_URL (e.g. to self-host the handler).
+//
+// Run standalone: npx @three-ws/pumpfun-mcp
+// Inspect: npx -y @modelcontextprotocol/inspector npx @three-ws/pumpfun-mcp
+
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+import {
+ ListToolsRequestSchema,
+ CallToolRequestSchema,
+} from '@modelcontextprotocol/sdk/types.js';
+
+import { FALLBACK_TOOLS } from './tools.js';
+
+const BACKEND_URL = process.env.PUMPFUN_MCP_URL || 'https://three.ws/api/pump-fun-mcp';
+const SERVER_NAME = 'three.ws-pumpfun-mcp';
+const SERVER_VERSION = '0.1.0';
+
+// A monotonically increasing JSON-RPC id for backend calls. Local to this
+// process; the backend is stateless so any unique id works.
+let rpcId = 0;
+
+// Post a JSON-RPC 2.0 request to the canonical backend and return its parsed
+// envelope. Throws on transport-level failure (network, non-2xx, bad JSON) so
+// callers surface a real error rather than a fabricated payload.
+async function callBackend(method, params, timeoutMs = 30_000) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetch(BACKEND_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }),
+ signal: controller.signal,
+ });
+ if (!res.ok) {
+ throw new Error(`backend ${BACKEND_URL} → HTTP ${res.status}`);
+ }
+ return await res.json();
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// Fetch the authoritative tool list from the backend. Falls back to the
+// vendored static surface if the backend is unreachable at startup, so a
+// fresh install still advertises correct tools offline.
+async function loadTools() {
+ try {
+ const env = await callBackend('tools/list', {}, 10_000);
+ const tools = env?.result?.tools;
+ if (Array.isArray(tools) && tools.length > 0) return tools;
+ } catch (err) {
+ process.stderr.write(
+ `[pumpfun-mcp] tools/list unreachable (${err.message}); using bundled tool list\n`,
+ );
+ }
+ return FALLBACK_TOOLS;
+}
+
+async function main() {
+ const tools = await loadTools();
+
+ const server = new Server(
+ { name: SERVER_NAME, version: SERVER_VERSION },
+ {
+ capabilities: { tools: { listChanged: false } },
+ instructions:
+ 'Free, read-only pump.fun + Solana tools from three.ws. Token discovery ' +
+ '(searchTokens, getTrendingTokens, getNewTokens, getGraduatedTokens, ' +
+ 'getKingOfTheHill), on-chain analysis (getBondingCurve, getTokenHolders, ' +
+ 'getTokenDetails, getTokenTrades), creator intelligence (getCreatorProfile, ' +
+ 'pumpfun_list_claims, pumpfun_watch_claims, pumpfun_first_claims), Solana Name ' +
+ 'Service (sns_resolve, sns_reverseLookup), market signals (kol_radar, ' +
+ 'kol_leaderboard, pumpfun_quote_swap, pumpfun_watch_whales), and social ' +
+ 'sentiment (social_cashtag_sentiment, social_x_post_impact). All data is live ' +
+ 'and on-chain; no API keys required.',
+ },
+ );
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
+
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const { name, arguments: args } = request.params;
+ let env;
+ try {
+ env = await callBackend('tools/call', { name, arguments: args || {} });
+ } catch (err) {
+ return {
+ isError: true,
+ content: [{ type: 'text', text: `Backend request failed: ${err.message}` }],
+ };
+ }
+
+ // A JSON-RPC error envelope (unknown tool, invalid arg, indexer
+ // unavailable, on-chain read failure) becomes an MCP tool error so the
+ // client sees the real failure instead of a silent empty result.
+ if (env?.error) {
+ return {
+ isError: true,
+ content: [
+ { type: 'text', text: `[${env.error.code}] ${env.error.message || 'tool error'}` },
+ ],
+ };
+ }
+
+ const result = env?.result;
+ if (result?.content) {
+ // Backend already returns MCP content + structuredContent — pass through.
+ return {
+ content: result.content,
+ ...(result.structuredContent !== undefined
+ ? { structuredContent: result.structuredContent }
+ : {}),
+ };
+ }
+
+ // Defensive: a well-formed-but-shapeless result still gets surfaced as text.
+ return { content: [{ type: 'text', text: JSON.stringify(result ?? null) }] };
+ });
+
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ process.stderr.write(
+ `[pumpfun-mcp] ${SERVER_NAME} v${SERVER_VERSION} ready — ${tools.length} tools via ${BACKEND_URL}\n`,
+ );
+}
+
+main().catch((err) => {
+ process.stderr.write(`[pumpfun-mcp] fatal: ${err?.stack || err}\n`);
+ process.exit(1);
+});
diff --git a/packages/pumpfun-mcp/src/tools.js b/packages/pumpfun-mcp/src/tools.js
new file mode 100644
index 000000000..e0939ee42
--- /dev/null
+++ b/packages/pumpfun-mcp/src/tools.js
@@ -0,0 +1,297 @@
+// Static fallback copy of the pump.fun / Solana MCP tool surface.
+//
+// At runtime the server fetches the authoritative list from the canonical
+// backend (tools/list). This vendored copy is only used when the backend is
+// unreachable at startup, so a freshly-installed client still advertises a
+// correct tool surface offline. Keep in sync with src/pump/mcp-tools.js in the
+// three.ws repo — that file is the source of truth.
+
+export const FALLBACK_TOOLS = [
+ {
+ name: 'searchTokens',
+ description: 'Search pump.fun tokens by name, symbol, or mint address.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
+ },
+ required: ['query'],
+ },
+ },
+ {
+ name: 'getTokenDetails',
+ description: 'Full details for a specific pump.fun token by mint address.',
+ inputSchema: {
+ type: 'object',
+ properties: { mint: { type: 'string' } },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getBondingCurve',
+ description:
+ 'Bonding curve analysis: real reserves, virtual reserves, and graduation progress (on-chain).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getTokenTrades',
+ description: 'Recent buy/sell history for a token.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getTrendingTokens',
+ description: 'Top pump.fun tokens by market cap.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getNewTokens',
+ description: 'Most recently launched pump.fun tokens.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getGraduatedTokens',
+ description: 'Tokens that graduated from the bonding curve to Raydium AMM.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getKingOfTheHill',
+ description: 'Highest-market-cap token still on the bonding curve.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'kol_radar',
+ description:
+ 'gmgn radar signals: early-detection patterns filtered by category, sorted by score desc.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: {
+ type: 'string',
+ enum: ['pump-fun', 'new-mints', 'volume-spike'],
+ default: 'pump-fun',
+ },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
+ },
+ },
+ },
+ {
+ name: 'getCreatorProfile',
+ description: 'All tokens by a creator wallet, with rug-pull risk flags.',
+ inputSchema: {
+ type: 'object',
+ properties: { creator: { type: 'string' } },
+ required: ['creator'],
+ },
+ },
+ {
+ name: 'getTokenHolders',
+ description: 'Top holders of a token with concentration analysis (on-chain).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 20, default: 10 },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'pumpfun_vanity_mint',
+ description:
+ 'Generate a Solana keypair whose address ends/starts with a vanity pattern. Returns publicKey + secretKey (base58). Caller must save the secret key immediately — it is never stored. Hard timeout: 60 s.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ suffix: { type: 'string', description: 'Desired address suffix (case-insensitive by default)' },
+ prefix: { type: 'string', description: 'Desired address prefix (case-insensitive by default)' },
+ caseSensitive: { type: 'boolean', default: false },
+ maxAttempts: { type: 'integer', default: 5000000 },
+ },
+ },
+ },
+ {
+ name: 'pumpfun_watch_whales',
+ description:
+ 'Collect whale trades on a pump.fun token for a short window (max 10 s). Returns all trades whose USD value meets minUsd.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'SPL mint pubkey (base58)' },
+ minUsd: { type: 'number', description: 'Minimum trade value in USD (default 5000)' },
+ durationMs: {
+ type: 'number',
+ description: 'Collection window in ms (default 5000, max 10000)',
+ },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'pumpfun_list_claims',
+ description:
+ 'List recent pump.fun fee-claim events for a creator wallet (on-chain, no indexer needed). Returns signature, mint, lamports, and Unix timestamp for each claim.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ creator: { type: 'string', description: 'Creator wallet address (base58)' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['creator'],
+ },
+ },
+ {
+ name: 'pumpfun_watch_claims',
+ description:
+ 'Return all pump.fun fee-claim events for a creator wallet within a look-back window (durationMs). Useful for batch collection after a delay.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ creator: { type: 'string', description: 'Creator wallet address (base58)' },
+ durationMs: {
+ type: 'number',
+ description: 'Look-back window in ms (default 300000 = 5 min, max 1800000)',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['creator'],
+ },
+ },
+ {
+ name: 'pumpfun_first_claims',
+ description:
+ 'First-ever pump.fun creator fee claims in a time window — a cash-out signal. Returns creators who have never claimed before, with creator wallet, mint, lamports, and timestamp.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ sinceMinutes: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 1440,
+ default: 60,
+ description: 'How far back to look for new claimers (minutes)',
+ },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
+ },
+ },
+ },
+ {
+ name: 'sns_resolve',
+ description: 'Resolve a .sol Solana Name Service domain to its owner wallet address.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: '.sol domain name, e.g. "bonfida.sol"' },
+ },
+ required: ['name'],
+ },
+ },
+ {
+ name: 'sns_reverseLookup',
+ description: 'Reverse-lookup a Solana wallet address to its primary .sol domain name.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ address: { type: 'string', description: 'Base58 Solana wallet address' },
+ },
+ required: ['address'],
+ },
+ },
+ {
+ name: 'social_cashtag_sentiment',
+ description:
+ 'Score social-post sentiment for a cashtag using a deterministic lexicon. Returns score (-1..1), positive/negative/neutral percentages, and example posts.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ posts: {
+ type: 'array',
+ description: 'Array of post objects. Each must have a text field; id, ts, and author are optional.',
+ items: {
+ type: 'object',
+ properties: {
+ id: { type: 'string' },
+ ts: { type: 'string' },
+ text: { type: 'string' },
+ author: { type: 'string' },
+ },
+ required: ['text'],
+ },
+ },
+ },
+ required: ['posts'],
+ },
+ },
+ {
+ name: 'kol_leaderboard',
+ description:
+ 'Top KOL traders ranked by P&L for a given time window. Returns wallet, pnlUsd, winRate, trades, rank.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ window: { type: 'string', enum: ['24h', '7d', '30d'], default: '7d' },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 25 },
+ },
+ },
+ },
+ {
+ name: 'pumpfun_quote_swap',
+ description:
+ 'Read-only price quote for a pump.fun AMM swap. No signing or tx sending. One of inputMint/outputMint must be wSOL (So11111111111111111111111111111111111111112). Returns amountOut, priceImpactBps, route, expiresAtMs.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ inputMint: { type: 'string', description: 'Input token mint (base58).' },
+ outputMint: { type: 'string', description: 'Output token mint (base58).' },
+ amountIn: { type: 'number', description: 'Input amount in raw base units (lamports for SOL).' },
+ slippageBps: { type: 'number', description: 'Slippage tolerance in basis points (default 100 = 1%).' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['inputMint', 'outputMint', 'amountIn'],
+ },
+ },
+ {
+ name: 'social_x_post_impact',
+ description:
+ 'Correlate an X (Twitter) post to a memecoin price impact. Fetches post metadata via oEmbed (no API key) and computes price delta from the pump.fun bonding curve in a ±windowMin window around the post.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ postUrl: { type: 'string', description: 'X post URL (e.g. https://x.com/user/status/123)' },
+ mint: { type: 'string', description: 'Solana token mint address (base58)' },
+ windowMin: {
+ type: 'integer',
+ default: 30,
+ description: '±window in minutes around the post time',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['postUrl', 'mint'],
+ },
+ },
+];
diff --git a/server-3d.json b/server-3d.json
new file mode 100644
index 000000000..da7ca8a72
--- /dev/null
+++ b/server-3d.json
@@ -0,0 +1,16 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/three-ws-3d-studio",
+ "description": "Turn text or an image into an interactive, textured 3D model (GLB). Generate, preview as a live <model-viewer> artifact, inspect, and optimize — powered by three.ws.",
+ "repository": {
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github"
+ },
+ "version": "1.0.0",
+ "remotes": [
+ {
+ "type": "streamable-http",
+ "url": "https://three.ws/api/mcp-3d"
+ }
+ ]
+}
diff --git a/server-bazaar.json b/server-bazaar.json
new file mode 100644
index 000000000..10d2326d7
--- /dev/null
+++ b/server-bazaar.json
@@ -0,0 +1,16 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/three-ws-x402-bazaar",
+ "description": "Discover paid agent services across the live x402 facilitator network: search and browse the bazaar, then get exact prices, payment networks, input schemas, and a ready pay link.",
+ "repository": {
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github"
+ },
+ "version": "1.0.0",
+ "remotes": [
+ {
+ "type": "streamable-http",
+ "url": "https://three.ws/api/mcp-bazaar"
+ }
+ ]
+}
diff --git a/tests/api/mcp-3d.test.js b/tests/api/mcp-3d.test.js
new file mode 100644
index 000000000..13ccf7301
--- /dev/null
+++ b/tests/api/mcp-3d.test.js
@@ -0,0 +1,151 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// ── Env (lazy env.* access in shared helpers) ───────────────────────────────
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+
+// ── Replicate provider (the real GPU backend) ───────────────────────────────
+const providerState = {
+ submit: vi.fn(async () => ({ extJobId: 'pred_123', eta: 45 })),
+ status: vi.fn(async () => ({ status: 'running' })),
+};
+vi.mock('../../api/_providers/replicate.js', () => ({
+ createRegenProvider: vi.fn(() => providerState),
+}));
+
+// ── text → image step ───────────────────────────────────────────────────────
+const t2iState = { fn: vi.fn(async () => ({ imageUrl: 'https://img.test/a.png', model: 'flux' })) };
+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({
+ textToImage: (...a) => t2iState.fn(...a),
+}));
+
+// ── Rate limits ──────────────────────────────────────────────────────────────
+const rlState = {
+ gen: { success: true, reset: Date.now() + 3600000 },
+ status: { success: true, reset: Date.now() + 60000 },
+};
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ mcp3dGenerate: vi.fn(async () => rlState.gen),
+ mcp3dStatus: vi.fn(async () => rlState.status),
+ mcpInspect: vi.fn(async () => ({ success: true })),
+ mcpOptimize: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '203.0.113.9'),
+}));
+
+// ── Usage (no DB in unit tests) ──────────────────────────────────────────────
+vi.mock('../../api/_lib/usage.js', () => ({
+ recordEvent: vi.fn(),
+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
+}));
+
+const { dispatch } = await import('../../api/_mcp3d/dispatch.js');
+
+const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402' };
+const call = (name, args) =>
+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, AUTH);
+
+beforeEach(() => {
+ providerState.submit.mockClear();
+ providerState.status.mockClear();
+ t2iState.fn.mockClear();
+ rlState.gen = { success: true, reset: Date.now() + 3600000 };
+ rlState.status = { success: true, reset: Date.now() + 60000 };
+ providerState.status.mockResolvedValue({ status: 'running' });
+});
+
+describe('3D Studio MCP', () => {
+ it('lists the studio toolset', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, AUTH);
+ const names = r.result.tools.map((t) => t.name);
+ expect(names).toEqual(
+ expect.arrayContaining([
+ 'text_to_3d',
+ 'image_to_3d',
+ 'generation_status',
+ 'preview_3d',
+ 'inspect_model',
+ 'optimize_model',
+ ]),
+ );
+ });
+
+ it('initialize advertises the studio server', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'initialize' }, AUTH);
+ expect(r.result.serverInfo.name).toBe('three-ws-3d-studio');
+ expect(r.result.protocolVersion).toBe('2025-06-18');
+ });
+
+ it('text_to_3d runs text→image then submits a reconstruction job', async () => {
+ const r = await call('text_to_3d', { prompt: 'a low-poly red fox' });
+ expect(t2iState.fn).toHaveBeenCalledWith('a low-poly red fox', { aspectRatio: '1:1' });
+ expect(providerState.submit).toHaveBeenCalledWith({
+ mode: 'reconstruct',
+ params: { image: 'https://img.test/a.png', prompt: 'a low-poly red fox' },
+ });
+ expect(r.result.structuredContent).toMatchObject({
+ job_id: 'pred_123',
+ status: 'queued',
+ preview_image_url: 'https://img.test/a.png',
+ });
+ });
+
+ it('rejects a too-short prompt with invalid params', async () => {
+ const r = await call('text_to_3d', { prompt: 'a' });
+ expect(r.error.code).toBe(-32602);
+ });
+
+ it('image_to_3d requires a public https url', async () => {
+ const bad = await call('image_to_3d', { image_url: 'http://localhost/x.png' });
+ expect(bad.result.isError).toBe(true);
+ expect(providerState.submit).not.toHaveBeenCalled();
+
+ const ok = await call('image_to_3d', { image_url: 'https://img.test/in.png' });
+ expect(ok.result.structuredContent.job_id).toBe('pred_123');
+ expect(providerState.submit).toHaveBeenCalledWith({
+ mode: 'reconstruct',
+ params: { image: 'https://img.test/in.png', prompt: undefined },
+ });
+ });
+
+ it('generation_status returns a GLB + model-viewer artifact when done', async () => {
+ providerState.status.mockResolvedValue({ status: 'done', resultGlbUrl: 'https://cdn.test/m.glb' });
+ const r = await call('generation_status', { job_id: 'pred_123' });
+ expect(r.result.structuredContent).toEqual({
+ job_id: 'pred_123',
+ status: 'done',
+ glb_url: 'https://cdn.test/m.glb',
+ });
+ const resource = r.result.content.find((c) => c.type === 'resource');
+ expect(resource.resource.mimeType).toBe('text/html');
+ expect(resource.resource.text).toContain('model-viewer');
+ expect(resource.resource.text).toContain('https://cdn.test/m.glb');
+ });
+
+ it('generation_status surfaces failures as tool errors', async () => {
+ providerState.status.mockResolvedValue({ status: 'failed', error: 'oom' });
+ const r = await call('generation_status', { job_id: 'pred_123' });
+ expect(r.result.isError).toBe(true);
+ expect(r.result.structuredContent).toEqual({ job_id: 'pred_123', status: 'failed', error: 'oom' });
+ });
+
+ it('generation_status reports in-progress jobs', async () => {
+ const r = await call('generation_status', { job_id: 'pred_123' });
+ expect(r.result.structuredContent).toEqual({ job_id: 'pred_123', status: 'running' });
+ expect(r.result.isError).toBeUndefined();
+ });
+
+ it('enforces the hourly generation rate limit', async () => {
+ rlState.gen = { success: false, reset: Date.now() + 1800000 };
+ const r = await call('text_to_3d', { prompt: 'a teapot' });
+ expect(r.error.code).toBe(-32000);
+ expect(r.error.message).toBe('rate_limited');
+ expect(providerState.submit).not.toHaveBeenCalled();
+ });
+
+ it('preview_3d renders any public GLB as an artifact', async () => {
+ const r = await call('preview_3d', { glb_url: 'https://cdn.test/x.glb' });
+ const resource = r.result.content.find((c) => c.type === 'resource');
+ expect(resource.resource.text).toContain('https://cdn.test/x.glb');
+ });
+});
diff --git a/tests/api/mcp-bazaar.test.js b/tests/api/mcp-bazaar.test.js
new file mode 100644
index 000000000..e25d1c24e
--- /dev/null
+++ b/tests/api/mcp-bazaar.test.js
@@ -0,0 +1,143 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';
+
+// ── Bazaar client (live facilitator network) ─────────────────────────────────
+const bazState = {
+ search: vi.fn(),
+ list: vi.fn(),
+ get: vi.fn(),
+};
+vi.mock('../../api/_lib/x402/bazaar-client.js', async (orig) => {
+ const real = await orig();
+ return {
+ ...real,
+ Bazaar: class {
+ search(...a) {
+ return bazState.search(...a);
+ }
+ list(...a) {
+ return bazState.list(...a);
+ }
+ get(...a) {
+ return bazState.get(...a);
+ }
+ },
+ };
+});
+
+// ── Rate limits ──────────────────────────────────────────────────────────────
+const rlState = { bazaar: { success: true, reset: Date.now() + 60000 } };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { mcpBazaar: vi.fn(async () => rlState.bazaar) },
+ clientIp: vi.fn(() => '203.0.113.7'),
+}));
+
+vi.mock('../../api/_lib/usage.js', () => ({
+ recordEvent: vi.fn(),
+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
+}));
+
+const { dispatch } = await import('../../api/_mcpbazaar/dispatch.js');
+
+const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402' };
+const call = (name, args) =>
+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, AUTH);
+
+// A normalized bazaar item (shape produced by normalizeItem).
+function item(over = {}) {
+ return {
+ type: 'http',
+ resource: 'https://api.weather.test/now',
+ toolName: '',
+ uniqueKey: 'https://api.weather.test/now',
+ serviceName: 'Weather Now',
+ description: 'Current weather by city.',
+ minPriceLabel: '$0.001',
+ minPriceAtomic: 1000,
+ networks: ['eip155:8453'],
+ tags: ['weather'],
+ method: 'GET',
+ accepts: [
+ {
+ network: 'eip155:8453',
+ priceLabel: '$0.001',
+ amountAtomic: 1000,
+ asset: '0xUSDC',
+ payTo: '0xRecipient',
+ scheme: 'exact',
+ },
+ ],
+ input: { type: 'http', method: 'GET' },
+ output: null,
+ facilitator: 'https://facilitator.test',
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ bazState.search.mockReset();
+ bazState.list.mockReset();
+ bazState.get.mockReset();
+ rlState.bazaar = { success: true, reset: Date.now() + 60000 };
+});
+
+describe('x402 Bazaar MCP', () => {
+ it('exposes the discovery toolset', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, AUTH);
+ expect(r.result.tools.map((t) => t.name)).toEqual([
+ 'search_services',
+ 'browse_services',
+ 'get_service',
+ ]);
+ });
+
+ it('search_services returns ranked, slimmed services', async () => {
+ bazState.search.mockResolvedValue({ resources: [item()], sources: [{ ok: true }], errors: [] });
+ const r = await call('search_services', { query: 'weather' });
+ expect(bazState.search).toHaveBeenCalledWith({ query: 'weather', type: 'http' });
+ const svc = r.result.structuredContent.services[0];
+ expect(svc).toMatchObject({ name: 'Weather Now', price: '$0.001', resource: 'https://api.weather.test/now' });
+ expect(svc.raw).toBeUndefined();
+ });
+
+ it('search_services filters by max_price_usdc', async () => {
+ bazState.search.mockResolvedValue({
+ resources: [item(), item({ resource: 'https://pricey.test', uniqueKey: 'https://pricey.test', minPriceAtomic: 5_000_000, minPriceLabel: '$5', accepts: [{ network: 'eip155:8453', priceLabel: '$5', amountAtomic: 5_000_000, asset: '0xUSDC' }] })],
+ sources: [],
+ errors: [],
+ });
+ const r = await call('search_services', { query: 'x', max_price_usdc: 1 });
+ expect(r.result.structuredContent.services).toHaveLength(1);
+ expect(r.result.structuredContent.services[0].resource).toBe('https://api.weather.test/now');
+ });
+
+ it('browse_services lists without a query', async () => {
+ bazState.list.mockResolvedValue({ items: [item()], sources: [], errors: [] });
+ const r = await call('browse_services', {});
+ expect(bazState.list).toHaveBeenCalledWith({ type: 'http' });
+ expect(r.result.structuredContent.count).toBe(1);
+ });
+
+ it('get_service returns payment options and a pay link', async () => {
+ bazState.get.mockResolvedValue(item());
+ const r = await call('get_service', { resource_url: 'https://api.weather.test/now' });
+ const sc = r.result.structuredContent;
+ expect(sc.accepts[0]).toMatchObject({ network: 'eip155:8453', price: '$0.001', pay_to: '0xRecipient' });
+ expect(sc.pay_link).toBe('https://three.ws/pay?resource=https%3A%2F%2Fapi.weather.test%2Fnow');
+ expect(sc.input_schema).toEqual({ type: 'http', method: 'GET' });
+ });
+
+ it('get_service reports a miss as a tool error', async () => {
+ bazState.get.mockResolvedValue(null);
+ const r = await call('get_service', { resource_url: 'https://nope.test' });
+ expect(r.result.isError).toBe(true);
+ });
+
+ it('honors the rate limit', async () => {
+ rlState.bazaar = { success: false, reset: Date.now() + 30000 };
+ const r = await call('search_services', { query: 'weather' });
+ expect(r.error.code).toBe(-32000);
+ expect(bazState.search).not.toHaveBeenCalled();
+ });
+});