Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: IBM Granite x402 MCP endpoint (/api/ibm-mcp) with catalog, discovery, pricing
nirholascd0182689461
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.jsindex a568f00f9..9c8f93538 100644--- a/api/_mcp/auth.js+++ b/api/_mcp/auth.js@@ -33,14 +33,18 @@ export function send401(res, msg) {// so x402-aware clients and Bazaar validators can still read the price/accepts// from this same response. (Previously this path returned a bare 402, which// OAuth clients couldn't interpret — the connector probe just spun.)-export function sendAuthChallenge(res, { resourceUrl, requirements }) {+export function sendAuthChallenge(res, { resourceUrl, requirements, challenge }) {const resource = env.MCP_RESOURCE;res.statusCode = 401;res.setHeader('www-authenticate',`Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,);- const body = build402Body({ resourceUrl, accepts: requirements });+ // `challenge` (optional) lets a dedicated MCP endpoint advertise its own+ // service metadata + bazaar discovery in the 402 envelope (e.g. the Granite+ // server at /api/ibm-mcp). Omitted → build402Body's defaults, unchanged for+ // the main /api/mcp and /api/mcp-3d servers.+ const body = build402Body({ resourceUrl, accepts: requirements, ...(challenge || {}) });res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(body), 'utf8').toString('base64'));res.setHeader('content-type', 'application/json; charset=utf-8');res.setHeader('cache-control', 'no-store');@@ -60,7 +64,11 @@ export function sendJsonRpcError(res, id, code, message, data) {// 402 challenge AND in the requirements used to verify the X-PAYMENT, so the// advertised price and the charged price agree. null = use the flat default// (initialize / tools/list / free tools / mixed batches).-export async function authenticateRequest(req, res, { x402Amount } = {}) {+export async function authenticateRequest(+ req,+ res,+ { x402Amount, resourcePath = '/api/mcp', challenge } = {},+) {const bearer = extractBearer(req);const paymentHeader = req.headers['x-payment'];@@ -73,7 +81,7 @@ export async function authenticateRequest(req, res, { x402Amount } = {}) {return { auth, x402Ctx: null };}- const resourceUrl = resolveResourceUrl(req, '/api/mcp');+ const resourceUrl = resolveResourceUrl(req, resourcePath);const requirements = paymentRequirements(resourceUrl,x402Amount != null ? { amount: x402Amount } : {},@@ -120,11 +128,11 @@ export async function authenticateRequest(req, res, { x402Amount } = {}) {}}- sendAuthChallenge(res, { resourceUrl, requirements });+ sendAuthChallenge(res, { resourceUrl, requirements, challenge });return null;}-export async function handleSse(req, res) {+export async function handleSse(req, res, { resourcePath = '/api/mcp', challenge } = {}) {// We don't hold long-lived server→client subscriptions yet; respond politely.const bearer = extractBearer(req);// Unauthenticated callers without an X-PAYMENT header get a 401 +@@ -132,10 +140,11 @@ export async function handleSse(req, res) {// server, with the x402 envelope still attached for x402 clients. Invalid// bearers also get 401 with WWW-Authenticate so they can re-auth correctly.if (!bearer && !req.headers['x-payment']) {- const sseResourceUrl = resolveResourceUrl(req, '/api/mcp');+ const sseResourceUrl = resolveResourceUrl(req, resourcePath);return sendAuthChallenge(res, {resourceUrl: sseResourceUrl,requirements: paymentRequirements(sseResourceUrl),+ challenge,});}const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });diff --git a/api/_mcpibm/catalog.js b/api/_mcpibm/catalog.jsnew file mode 100644index 000000000..95f9d8c1b--- /dev/null+++ b/api/_mcpibm/catalog.js@@ -0,0 +1,63 @@+// Catalog assembly for the hosted IBM Granite MCP server.+//+// TOOL_CATALOG is the tools/list payload: each tool's public schema plus the+// per-call price and a v2 `bazaar` discovery extension, both baked in at module+// load so the shared makeDispatcher can return it verbatim (no per-request+// enrichment, no changes to the shared dispatcher). TOOLS maps tool name →+// { handler, validate } for tools/call.++import Ajv from 'ajv';+import addFormats from 'ajv-formats';++import { declareMcpDiscovery } from '../_lib/x402/bazaar-helpers.js';+import { toolDefs } from './tools.js';+import { priceFor } from './pricing.js';++// `useDefaults` fills schema defaults (e.g. analysis_type → 'general'),+// `coerceTypes` accepts the string-form integers some MCP clients emit. Mirrors+// the main /api/mcp catalog's Ajv configuration.+const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });+addFormats(ajv);++// Public tools/list entries — strip the server-side `handler` and the spec-only+// `example`/`output` (carried into the bazaar extension instead), and attach+// pricing + discovery.+export const TOOL_CATALOG = toolDefs.map((def) => {+ const price = priceFor(def.name);+ const entry = {+ name: def.name,+ title: def.title,+ description: def.description,+ inputSchema: def.inputSchema,+ };+ if (price) {+ entry.pricing = {+ amount_usdc: price.amount_usdc,+ currency: 'USDC',+ description: price.description,+ scheme: 'x402',+ };+ entry.extensions = {+ bazaar: declareMcpDiscovery({+ toolName: def.name,+ description: def.description,+ transport: 'streamable-http',+ inputSchema: def.inputSchema,+ example: def.example,+ output: def.output,+ }),+ };+ }+ return entry;+});++// Handler + compiled validator lookup for tools/call.+export const TOOLS = Object.fromEntries(+ toolDefs.map((def) => [+ def.name,+ {+ handler: def.handler,+ validate: def.inputSchema ? ajv.compile(def.inputSchema) : null,+ },+ ]),+);diff --git a/api/_mcpibm/discovery.js b/api/_mcpibm/discovery.jsnew file mode 100644index 000000000..07d735346--- /dev/null+++ b/api/_mcpibm/discovery.js@@ -0,0 +1,124 @@+// Bazaar discovery + service metadata for the hosted IBM Granite MCP endpoint.+//+// The 402 challenge an unauthenticated/unpaid caller receives carries this+// metadata so x402 facilitators (CDP Bazaar, agentic.market, x402scan) index+// /api/ibm-mcp with a Granite-specific service name, tags, icon, and a v2+// `bazaar` extension describing the JSON-RPC tools/call shape. Mirrors the+// generic bazaarExtension() in api/_lib/x402-spec.js, specialized for Granite.++import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';++export const RESOURCE_DESCRIPTION =+ 'three.ws x402 MCP — Streamable HTTP (MCP 2025-06-18) exposing IBM Granite foundation models as ' ++ 'pay-per-call tools: ibm_granite_chat (conversational AI), ibm_granite_code (generate/review/refactor/' ++ 'explain/test/document), ibm_granite_embed (multilingual embeddings), ibm_granite_analyze (structured ' ++ 'document analysis), and ibm_granite_forecast (zero-shot time-series). Pay per call in USDC on Base or ' ++ 'Solana mainnet — no IBM Cloud account required. Operated by three.ws.';++// Endpoint-level v2 bazaar discovery entry, shaped exactly like the validator+// expects (see api/_lib/x402-spec.js → bazaarExtension). Describes how to POST a+// JSON-RPC 2.0 tools/call and what comes back.+function graniteBazaarExtension() {+ const exampleBody = {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: {+ name: 'ibm_granite_chat',+ arguments: {+ messages: [+ {+ role: 'user',+ content: 'Summarize the IBM Granite model family in one sentence.',+ },+ ],+ },+ },+ };+ const exampleResponse = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ content: [+ { type: 'text', text: 'IBM Granite is a family of open foundation models...' },+ ],+ structuredContent: {+ ok: true,+ text: 'IBM Granite is a family of open foundation models...',+ model: 'ibm/granite-3-8b-instruct',+ },+ },+ };+ const requestBodySchema = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['jsonrpc', 'method'],+ properties: {+ jsonrpc: { type: 'string', const: '2.0' },+ id: { type: ['string', 'number'] },+ method: {+ type: 'string',+ enum: ['initialize', 'tools/list', 'tools/call', 'ping'],+ description: 'MCP JSON-RPC method.',+ },+ params: {+ type: 'object',+ description:+ 'For tools/call: { name, arguments }. Tool names: ibm_granite_chat, ibm_granite_code, ibm_granite_embed, ibm_granite_analyze, ibm_granite_forecast — see tools/list.',+ },+ },+ };+ const responseBodySchema = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ jsonrpc: { type: 'string', const: '2.0' },+ id: { type: ['string', 'number'] },+ result: {+ type: 'object',+ properties: {+ content: {+ type: 'array',+ items: {+ type: 'object',+ required: ['type', 'text'],+ properties: {+ type: { type: 'string', enum: ['text'] },+ text: { type: 'string' },+ },+ },+ },+ },+ },+ error: {+ type: 'object',+ properties: { code: { type: 'number' }, message: { type: 'string' } },+ },+ },+ };+ return {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', body: exampleBody, bodyType: 'json' },+ output: { type: 'json', example: exampleResponse },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: requestBodySchema,+ outputSchema: responseBodySchema,+ }),+ };+}++// The challenge override block threaded into authenticateRequest/handleSse so+// the 402 envelope advertises Granite service metadata + discovery.+export const GRANITE_CHALLENGE = {+ description: RESOURCE_DESCRIPTION,+ bazaar: graniteBazaarExtension(),+ ...withService({+ serviceName: 'three.ws Granite x402',+ tags: ['x402', 'mcp', 'ibm', 'granite', 'ai'],+ }),+};diff --git a/api/_mcpibm/dispatch.js b/api/_mcpibm/dispatch.jsnew file mode 100644index 000000000..c3610da81--- /dev/null+++ b/api/_mcpibm/dispatch.js@@ -0,0 +1,26 @@+// JSON-RPC dispatch for the hosted IBM Granite MCP server — a thin binding of+// the shared payment-free dispatcher (api/_lib/mcp-dispatch.js) to this server's+// Granite catalog. Per-call x402 payment is enforced at the HTTP layer+// (api/ibm-mcp.js) before dispatch, so the dispatcher itself stays payment-free.+import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';+import { TOOL_CATALOG, TOOLS } from './catalog.js';++export { PROTOCOL_VERSION };++const INSTRUCTIONS = [+ 'x402 pay-per-use IBM Granite AI from three.ws — each tool lists its USDC price; pay per call on Base or Solana, no IBM Cloud account required.',+ 'ibm_granite_chat(messages) — conversational AI ($0.02).',+ 'ibm_granite_code(task, prompt) — generate/review/refactor/explain/test/document code ($0.025).',+ 'ibm_granite_embed(inputs) — batch multilingual embeddings for RAG/search ($0.005).',+ 'ibm_granite_analyze(document) — structured entities/sentiment/risk/summary/next-steps JSON ($0.04).',+ 'ibm_granite_forecast(timestamps, values, freq) — zero-shot time-series forecast via Granite TTM ($0.05).',+ 'Powered by IBM Granite foundation models served on IBM watsonx.ai.',+].join(' ');++export const dispatch = makeDispatcher({+ serverInfo: { name: 'ibm-x402-mcp', version: '1.0.0' },+ instructions: INSTRUCTIONS,+ catalog: TOOL_CATALOG,+ tools: TOOLS,+ logName: 'mcpibm',+});diff --git a/api/_mcpibm/pricing.js b/api/_mcpibm/pricing.jsnew file mode 100644index 000000000..8c4eec721--- /dev/null+++ b/api/_mcpibm/pricing.js@@ -0,0 +1,51 @@+// Per-tool x402 pricing for the hosted IBM Granite MCP server (/api/ibm-mcp).+//+// These prices mirror the per-call USDC prices of the @three-ws/ibm-x402-mcp+// npm package (the stdio transport of the same tool suite) so the hosted+// Streamable HTTP endpoint and the local stdio server charge identically. The+// advertised 402 amount and the settled charge are both derived from this map,+// keyed by the tool actually called — see api/ibm-mcp.js.++export const TOOL_PRICING = Object.freeze({+ ibm_granite_chat: {+ amount_usdc: 0.02,+ description: 'Per call — IBM Granite 3 chat completion',+ },+ ibm_granite_code: {+ amount_usdc: 0.025,+ description: 'Per call — code generate/review/refactor/explain/test/document',+ },+ ibm_granite_embed: {+ amount_usdc: 0.005,+ description: 'Per call — batch text embeddings (≤64 inputs)',+ },+ ibm_granite_analyze: {+ amount_usdc: 0.04,+ description: 'Per call — structured document analysis',+ },+ ibm_granite_forecast: {+ amount_usdc: 0.05,+ description: 'Per call — zero-shot time-series forecast',+ },+});++export function priceFor(toolName) {+ return TOOL_PRICING[toolName] || null;+}++// USDC (and the platform's other supported stables) are 6-decimal. The x402 wire+// `amount` is an atomic-unit string; round to the nearest atomic unit so+// fractional-cent prices (e.g. 0.005) map exactly.+const USDC_DECIMALS = 6;+function usdcToAtomicString(amountUsdc) {+ return String(Math.round(Number(amountUsdc) * 10 ** USDC_DECIMALS));+}++// The x402 `amount` (atomic-unit string) to charge for a Granite tools/call.+// Derived from the advertised per-tool price so the 402 challenge and the+// settled charge agree. Returns null for unpriced tools (no charge).+export function graniteX402Amount(toolName) {+ const price = priceFor(toolName);+ if (!price || !(price.amount_usdc > 0)) return null;+ return usdcToAtomicString(price.amount_usdc);+}diff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.jsnew file mode 100644index 000000000..02ecf3ba6--- /dev/null+++ b/api/_mcpibm/tools.js@@ -0,0 +1,525 @@+// IBM Granite MCP tool implementations for the hosted Streamable HTTP server.+//+// These are the same five tools shipped by the @three-ws/ibm-x402-mcp npm+// package (stdio transport) — chat, code, embed, analyze, forecast — re-bound to+// the platform's proven server-side watsonx.ai clients (api/_lib/watsonx.js and+// api/_lib/watsonx-forecast.js). Prompts, input schemas, prices, and output+// shapes are kept identical to the package so the two transports behave the+// same; the package remains the canonical reference for tool semantics.+//+// The server operator supplies WATSONX_* credentials; end users pay USDC per+// call via x402 (gated in api/ibm-mcp.js) and never need an IBM Cloud account.++import { watsonxConfig, watsonxChatComplete, watsonxEmbed } from '../_lib/watsonx.js';+import { watsonxForecast } from '../_lib/watsonx-forecast.js';++function rpcError(code, message, data) {+ const e = new Error(message);+ e.code = code;+ e.data = data;+ return e;+}++// Resolve watsonx config or fail with a clear, secret-free message. The hosted+// endpoint is operator-funded: when credentials are absent the whole server is+// unusable, so we surface that plainly rather than letting an IAM call fail deep+// in a tool handler.+function graniteConfig() {+ const cfg = watsonxConfig();+ if (!cfg.configured) {+ throw new Error(+ 'IBM watsonx.ai credentials are not configured on this server (set WATSONX_API_KEY and WATSONX_PROJECT_ID).',+ );+ }+ return cfg;+}++// MCP tool result helper. structuredContent carries the full machine-readable+// object (the same shape the npm package returns); content[0].text is a concise+// human-readable view for clients that render text.+function toolResult(humanText, structured) {+ return {+ content: [{ type: 'text', text: humanText }],+ structuredContent: structured,+ };+}++// ───────────────────────────────── chat ─────────────────────────────────────++const CHAT_DESCRIPTION =+ 'Chat completion powered by IBM Granite foundation models (default: ibm/granite-3-8b-instruct). ' ++ 'Send a conversation as role/content message pairs and receive the assistant reply with token usage. ' ++ 'No IBM Cloud account required — pay $0.02 USDC per call via x402.';++const chatTool = {+ name: 'ibm_granite_chat',+ title: 'IBM Granite Chat ($0.02)',+ description: CHAT_DESCRIPTION,+ inputSchema: {+ type: 'object',+ properties: {+ messages: {+ type: 'array',+ minItems: 1,+ maxItems: 50,+ description: 'Conversation history. Must include at least one user message.',+ items: {+ type: 'object',+ properties: {+ role: {+ type: 'string',+ enum: ['system', 'user', 'assistant'],+ description: 'Message role.',+ },+ content: {+ type: 'string',+ minLength: 1,+ maxLength: 32_000,+ description: 'Message text.',+ },+ },+ required: ['role', 'content'],+ additionalProperties: false,+ },+ },+ model: {+ type: 'string',+ description:+ 'Override the Granite model id (e.g. ibm/granite-3-2b-instruct). Defaults to ibm/granite-3-8b-instruct.',+ },+ max_new_tokens: {+ type: 'integer',+ minimum: 1,+ maximum: 4096,+ description: 'Maximum tokens to generate. Defaults to 1024.',+ },+ temperature: {+ type: 'number',+ minimum: 0,+ maximum: 2,+ description: 'Sampling temperature (0 = deterministic). Defaults to 0.7.',+ },+ },+ required: ['messages'],+ additionalProperties: false,+ },+ example: {+ messages: [{ role: 'user', content: 'Explain quantum entanglement in two sentences.' }],+ },+ output: {+ example: {+ ok: true,+ text: 'Quantum entanglement is a phenomenon where two particles...',+ finishReason: 'stop',+ usage: { prompt_tokens: 14, completion_tokens: 38 },+ model: 'ibm/granite-3-8b-instruct',+ },+ },+ async handler({ messages, model, max_new_tokens, temperature }) {+ const cfg = graniteConfig();+ const result = await watsonxChatComplete(cfg, {+ messages,+ model,+ maxTokens: max_new_tokens ?? 1024,+ temperature: temperature ?? 0.7,+ });+ return toolResult(result.text, { ok: true, ...result });+ },+};++// ───────────────────────────────── code ─────────────────────────────────────++const CODE_DESCRIPTION =+ 'Code generation, review, refactoring, and explanation via IBM Granite instruct models. ' ++ 'Provide a task type and code/prompt; receive the generated or reviewed code with explanation. ' ++ 'No IBM Cloud account required — pay $0.025 USDC per call via x402.';++const TASK_DESCRIPTIONS = {+ generate: 'Generate new code from the prompt description.',+ review: 'Review the provided code for bugs, security issues, and improvements.',+ refactor: 'Refactor the code for clarity, performance, and best practices.',+ explain: 'Explain what the code does in plain language.',+ test: 'Generate unit tests for the provided code.',+ document: 'Add inline documentation and docstrings to the code.',+};++function buildCodeSystemPrompt(task, language) {+ const lang = language ? ` in ${language}` : '';+ const base = `You are an expert software engineer${lang}. ${TASK_DESCRIPTIONS[task]}`;+ const format =+ task === 'review'+ ? ' Structure your response as: FINDINGS (bulleted issues with severity), then RECOMMENDATIONS.'+ : task === 'explain'+ ? ' Be concise and clear. Use plain language suitable for a code review.'+ : ' Return only the code block, then a brief explanation of key decisions.';+ return base + format;+}++const codeTool = {+ name: 'ibm_granite_code',+ title: 'IBM Granite Code ($0.025)',+ description: CODE_DESCRIPTION,+ inputSchema: {+ type: 'object',+ properties: {+ task: {+ type: 'string',+ enum: ['generate', 'review', 'refactor', 'explain', 'test', 'document'],+ description:+ 'Code task: generate (new code from description), review (bugs/security), refactor (quality), explain (plain language), test (unit tests), or document (add docstrings).',+ },+ prompt: {+ type: 'string',+ minLength: 1,+ maxLength: 16_000,+ description:+ 'For "generate": describe what to build. For all others: paste the code to process.',+ },+ language: {+ type: 'string',+ description:+ 'Target programming language (e.g. "TypeScript", "Python", "Rust"). Optional for explain/review.',+ },+ context: {+ type: 'string',+ maxLength: 4_000,+ description:+ 'Additional context: architecture notes, constraints, or example usage.',+ },+ },+ required: ['task', 'prompt'],+ additionalProperties: false,+ },+ example: {+ task: 'generate',+ prompt: 'A debounce function with TypeScript generics and a cancel method.',+ language: 'TypeScript',+ },+ output: {+ example: {+ ok: true,+ task: 'generate',+ text: 'function debounce<T extends (...args: unknown[]) => void>(fn: T, delay: number) { ... }',+ model: 'ibm/granite-3-8b-instruct',+ },+ },+ async handler({ task, prompt, language, context }) {+ const cfg = graniteConfig();+ const systemContent = buildCodeSystemPrompt(task, language);+ const userContent = context ? `${prompt}\n\nContext: ${context}` : prompt;+ const result = await watsonxChatComplete(cfg, {+ messages: [+ { role: 'system', content: systemContent },+ { role: 'user', content: userContent },+ ],+ maxTokens: 2048,+ temperature: task === 'generate' ? 0.3 : 0.1,+ });+ return toolResult(result.text, { ok: true, task, ...result });+ },+};++// ──────────────────────────────── embed ─────────────────────────────────────++const EMBED_DESCRIPTION =+ 'Generate embedding vectors for one or more texts using IBM Granite ' ++ '(default: ibm/granite-embedding-278m-multilingual). Returns one float array per input, ' ++ 'suitable for semantic search, RAG retrieval, and similarity scoring. ' ++ 'Up to 64 texts per call. No IBM Cloud account required — pay $0.005 USDC per call via x402.';++const embedTool = {+ name: 'ibm_granite_embed',+ title: 'IBM Granite Embed ($0.005)',+ description: EMBED_DESCRIPTION,+ inputSchema: {+ type: 'object',+ properties: {+ inputs: {+ type: 'array',+ minItems: 1,+ maxItems: 64,+ items: { type: 'string', minLength: 1, maxLength: 8_000 },+ description: 'Texts to embed. 1–64 strings per call, up to 8,000 characters each.',+ },+ model: {+ type: 'string',+ description:+ 'Override the embedding model id (e.g. ibm/granite-embedding-125m-english). Defaults to ibm/granite-embedding-278m-multilingual.',+ },+ },+ required: ['inputs'],+ additionalProperties: false,+ },+ example: { inputs: ['enterprise AI platform', 'cloud-native machine learning'] },+ output: {+ example: {+ ok: true,+ model: 'ibm/granite-embedding-278m-multilingual',+ inputCount: 2,+ dimensions: 768,+ vectors: [+ [0.012, -0.034, 0.091],+ [0.008, -0.027, 0.088],+ ],+ },+ },+ async handler({ inputs, model }) {+ const cfg = graniteConfig();+ const result = await watsonxEmbed(cfg, { inputs, model });+ const summary = `Embedded ${result.inputCount} input${result.inputCount === 1 ? '' : 's'} → ${result.inputCount}×${result.dimensions} vectors (${result.model}).`;+ return toolResult(summary, { ok: true, ...result });+ },+};++// ─────────────────────────────── analyze ────────────────────────────────────++const ANALYZE_DESCRIPTION =+ 'Structured document analysis powered by IBM Granite: extract entities, sentiment, risk signals, ' ++ 'a concise summary, and recommended next steps from any text (contracts, reports, emails, code reviews, etc.). ' ++ 'Returns a machine-readable JSON analysis. ' ++ 'No IBM Cloud account required — pay $0.04 USDC per call via x402.';++function buildAnalysisPrompt(analysis_type, language) {+ const langHint = language ? ` The document is written in ${language}.` : '';++ const typeInstructions = {+ general:+ 'Identify key entities (people, organizations, places, dates), overall sentiment (positive/neutral/negative), ' ++ 'main topics, critical risk flags, a 3-sentence summary, and 3 actionable next steps.',+ contract:+ 'Extract: parties involved, effective date, termination clauses, obligations per party, ' ++ 'penalty/liability clauses, renewal terms, risk flags (one-sided terms, missing protections), ' ++ 'a 3-sentence summary, and 3 recommended legal review steps.',+ financial:+ 'Extract: key financial metrics and figures, growth indicators, risk factors, market signals, ' ++ 'forward-looking statements, red flags (inconsistencies, unusual items), ' ++ 'a 3-sentence summary, and 3 investment/operational recommendations.',+ technical:+ 'Extract: technologies mentioned, architecture patterns, identified issues or bugs, ' ++ 'security concerns, performance risks, dependencies, ' ++ 'a 3-sentence technical summary, and 3 engineering recommendations.',+ medical:+ 'Extract: clinical entities (diagnoses, medications, procedures, lab values), ' ++ 'findings and observations, risk factors, contraindications, ' ++ 'a 3-sentence clinical summary, and 3 recommended follow-up actions.',+ sentiment:+ 'Analyze: overall sentiment score (-1.0 to 1.0), emotion breakdown (joy, anger, fear, sadness, surprise, disgust), ' ++ 'sentiment per paragraph or section, strongest positive and negative signals, ' ++ 'a 3-sentence sentiment summary, and 3 communication recommendations.',+ };++ return (+ `You are an expert document analyst specializing in ${analysis_type} analysis.${langHint}\n\n` ++ `Analyze the provided document and return a JSON object with these exact keys:\n` ++ `- "summary": string (3 concise sentences)\n` ++ `- "entities": array of { name, type, relevance } objects\n` ++ `- "sentiment": { overall: string, score: number -1.0 to 1.0 }\n` ++ `- "key_findings": array of strings (top 5 findings)\n` ++ `- "risk_flags": array of { flag: string, severity: "low"|"medium"|"high" }\n` ++ `- "next_steps": array of strings (top 3 actionable recommendations)\n` ++ `- "analysis_type": "${analysis_type}"\n\n` ++ `${typeInstructions[analysis_type]}\n\n` ++ `Return ONLY valid JSON. No markdown code blocks, no prose outside the JSON.`+ );+}++const analyzeTool = {+ name: 'ibm_granite_analyze',+ title: 'IBM Granite Analyze ($0.04)',+ description: ANALYZE_DESCRIPTION,+ inputSchema: {+ type: 'object',+ properties: {+ document: {+ type: 'string',+ minLength: 1,+ maxLength: 24_000,+ description: 'The document, report, email, or text to analyze.',+ },+ analysis_type: {+ type: 'string',+ enum: ['general', 'contract', 'financial', 'technical', 'medical', 'sentiment'],+ default: 'general',+ description:+ 'Analysis focus: general (universal), contract (legal terms, obligations), ' ++ 'financial (metrics, risks, forecasts), technical (architecture, issues), ' ++ 'medical (clinical entities, findings), or sentiment (tone, emotions).',+ },+ language: {+ type: 'string',+ description:+ 'Document language hint (e.g. "Spanish", "French"). Defaults to auto-detect.',+ },+ },+ required: ['document'],+ additionalProperties: false,+ },+ example: {+ document:+ 'This Services Agreement is entered into between Acme Corp and Vendor Inc effective January 1, 2026...',+ analysis_type: 'contract',+ },+ output: {+ example: {+ ok: true,+ analysis_type: 'contract',+ summary:+ 'This agreement establishes a 12-month SaaS subscription between Acme Corp and Vendor Inc...',+ entities: [{ name: 'Acme Corp', type: 'organization', relevance: 'party' }],+ sentiment: { overall: 'neutral', score: 0.1 },+ key_findings: ['Auto-renewal clause on 60-day notice'],+ risk_flags: [{ flag: 'One-sided IP assignment clause', severity: 'high' }],+ next_steps: ['Legal review of IP assignment clause section 8.2'],+ model: 'ibm/granite-3-8b-instruct',+ },+ },+ async handler({ document, analysis_type = 'general', language }) {+ const cfg = graniteConfig();+ const systemPrompt = buildAnalysisPrompt(analysis_type, language);+ const result = await watsonxChatComplete(cfg, {+ messages: [+ { role: 'system', content: systemPrompt },+ { role: 'user', content: document },+ ],+ maxTokens: 2048,+ temperature: 0.1,+ });++ let parsed;+ try {+ const raw = result.text.trim();+ // Strip any accidental markdown code fence.+ const jsonStr = raw.startsWith('```')+ ? raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '')+ : raw;+ parsed = JSON.parse(jsonStr);+ } catch {+ // Granite didn't return clean JSON — surface text so the client can decide.+ const fallback = {+ ok: true,+ analysis_type,+ raw_response: result.text,+ usage: result.usage,+ model: result.model,+ parse_error: 'Model returned non-JSON response; see raw_response.',+ };+ return toolResult(result.text, fallback);+ }++ const structured = {+ ok: true,+ analysis_type,+ ...parsed,+ usage: result.usage,+ model: result.model,+ };+ return toolResult(JSON.stringify(structured, null, 2), structured);+ },+};++// ─────────────────────────────── forecast ───────────────────────────────────++const FORECAST_DESCRIPTION =+ 'Zero-shot time-series forecasting via IBM Granite TTM (Tiny Time Mixer). ' ++ 'Provide a numeric series with ISO-8601 timestamps and a cadence, receive the forecast horizon. ' ++ 'No training required. Suitable for revenue, traffic, sensor, energy, and financial series. ' ++ 'No IBM Cloud account required — pay $0.05 USDC per call via x402.';++const FREQ_EXAMPLES = '1min, 5min, 15min, 30min, 1h, 2h, 4h, 12h, 1D, 1W, 1ME';++const forecastTool = {+ name: 'ibm_granite_forecast',+ title: 'IBM Granite Forecast ($0.05)',+ description: FORECAST_DESCRIPTION,+ inputSchema: {+ type: 'object',+ properties: {+ timestamps: {+ type: 'array',+ minItems: 64,+ maxItems: 1024,+ items: { type: 'string', minLength: 1 },+ description:+ 'ISO-8601 timestamps at a uniform cadence, oldest to newest (e.g. ["2025-01-01T00:00:00Z", ...]).',+ },+ values: {+ type: 'array',+ minItems: 64,+ maxItems: 1024,+ items: { type: 'number' },+ description:+ 'Numeric series aligned to timestamps, oldest to newest. Must be the same length as timestamps.',+ },+ freq: {+ type: 'string',+ minLength: 1,+ description: `Cadence of the series as a pandas-style frequency string. Examples: ${FREQ_EXAMPLES}.`,+ },+ prediction_length: {+ type: 'integer',+ minimum: 1,+ maximum: 96,+ description:+ 'Number of steps to forecast ahead. Defaults to the model horizon (typically 96 for 1h data).',+ },+ label: {+ type: 'string',+ maxLength: 64,+ description:+ 'Human label for the series (e.g. "daily_revenue_usd"). Returned in output for traceability.',+ },+ },+ required: ['timestamps', 'values', 'freq'],+ additionalProperties: false,+ },+ example: {+ timestamps: ['2025-01-01T00:00:00Z', '2025-01-02T00:00:00Z'],+ values: [1200, 1350],+ freq: '1D',+ prediction_length: 7,+ label: 'daily_revenue_usd',+ },+ output: {+ example: {+ ok: true,+ label: 'daily_revenue_usd',+ model: 'ibm/granite-ttm-512-96-r2',+ inputWindow: 512,+ forecastSteps: 7,+ forecast: [{ timestamp: '2025-06-07T00:00:00Z', value: 1420 }],+ },+ },+ async handler({ timestamps, values, freq, prediction_length, label }) {+ if (timestamps.length !== values.length) {+ throw rpcError(+ -32602,+ `timestamps and values must have equal length (got ${timestamps.length} timestamps, ${values.length} values).`,+ );+ }+ const cfg = graniteConfig();+ const result = await watsonxForecast(cfg, {+ timestamps,+ values,+ freq,+ predictionLength: prediction_length,+ });++ const forecast = result.timestamps.map((ts, i) => ({+ timestamp: ts,+ value: result.values[i] ?? null,+ }));++ const structured = {+ ok: true,+ ...(label ? { label } : {}),+ model: result.model,+ inputWindow: result.inputWindow,+ forecastSteps: forecast.length,+ forecast,+ };+ const summary = `Forecast ${forecast.length} step${forecast.length === 1 ? '' : 's'} ahead from ${result.inputWindow} points (${result.model}).`;+ return toolResult(summary, structured);+ },+};++export const toolDefs = [chatTool, codeTool, embedTool, analyzeTool, forecastTool];diff --git a/api/ibm-mcp.js b/api/ibm-mcp.jsnew file mode 100644index 000000000..4bb49c7b0--- /dev/null+++ b/api/ibm-mcp.js@@ -0,0 +1,111 @@+// IBM Granite x402 MCP server — Streamable HTTP transport (MCP 2025-06-18,+// JSON-RPC 2.0). POST /api/ibm-mcp — tool calls GET — SSE DELETE — terminate.+//+// The hosted (remote) transport for the @three-ws/ibm-x402-mcp tool suite: five+// IBM Granite tools (chat, code, embed, analyze, forecast) gated by per-call+// x402 payments. End users pay USDC on Base or Solana per call — no IBM Cloud+// account required; the operator funds watsonx.ai via WATSONX_* env vars.+// Authenticated three.ws principals (Bearer / OAuth) call without per-call+// payment — the operator-funded path for watsonx Orchestrate connections.+// Registered with the MCP Registry as io.github.nirholas/ibm-x402-mcp-remote+// (see server-ibm.json).+import { cors, readJson, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';+import { PROTOCOL_VERSION, dispatch } from './_mcpibm/dispatch.js';+import { graniteX402Amount } from './_mcpibm/pricing.js';+import { GRANITE_CHALLENGE } from './_mcpibm/discovery.js';+import {+ send401,+ sendJsonRpcError,+ authenticateRequest,+ handleSse,+ handleTerminate,+} from './_mcp/auth.js';+import { sendX402Error } from './_mcp/payments.js';++const RESOURCE_PATH = '/api/ibm-mcp';++// Peek the single called tool from a (possibly batched) JSON-RPC body so the+// x402 challenge advertises — and the settle path charges — exactly the per-tool+// price. Only a request calling ONE tool is priced per-tool; mixed batches and+// non-tools/call requests (initialize, tools/list, ping) yield null → no charge.+function peekCalledTool(body) {+ const batch = Array.isArray(body) ? body : [body];+ const calls = batch.filter((m) => m && m.method === 'tools/call');+ if (calls.length === 1) {+ const name = calls[0]?.params?.name;+ return { toolName: typeof name === 'string' ? name : null };+ }+ return { toolName: null };+}++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, { resourcePath: RESOURCE_PATH, challenge: GRANITE_CHALLENGE });+ if (req.method === 'DELETE') return handleTerminate(req, res);+ if (req.method !== 'POST') return send401(res, 'method not supported');++ // Read + parse the body BEFORE the x402 challenge so the 402 is priced by the+ // tool actually being called. Malformed JSON throws (status 400) → wrap().+ const body = await readJson(req, 2_000_000);++ // Per-tool x402 price. A non-tools/call request (initialize, tools/list) or a+ // mixed batch yields null → the flat env default, which the auth-gated+ // discovery path never actually charges.+ const { toolName } = peekCalledTool(body);+ const x402Amount = toolName ? graniteX402Amount(toolName) : null;++ const result = await authenticateRequest(req, res, {+ x402Amount,+ resourcePath: RESOURCE_PATH,+ challenge: GRANITE_CHALLENGE,+ });+ if (!result) return;+ const { auth, x402Ctx } = 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 batch = Array.isArray(body) ? body : [body];+ // Per-request batch cap — each message can trigger an IBM inference call, so+ // an unbounded batch multiplies billable work against the user's budget.+ 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);+ }++ // Settle the x402 payment AFTER the work succeeded — atomic from the caller's+ // perspective: if settle fails, the payer's signed payload is not broadcast+ // and they get an error instead of having paid for nothing.+ if (x402Ctx) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }+ }++ 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/packages/ibm-x402-mcp/CATALOG.md b/packages/ibm-x402-mcp/CATALOG.mdnew file mode 100644index 000000000..9163a2618--- /dev/null+++ b/packages/ibm-x402-mcp/CATALOG.md@@ -0,0 +1,111 @@+# IBM Cloud / watsonx Orchestrate catalog listing++Field values for the **MCP Server** entry: *x402 MCP - Pay-per-Use AI Agent Payments by three.ws*.+Source of truth for the published listing — keep in sync with `server.json`, `README.md`, and the tool sources in `src/tools/`.++| Field | Value |+|---|---|+| Name | `three-ws-x402-mcp` |+| Display name | `x402 MCP - Pay-per-Use AI Agent Payments by three.ws` |+| Short description (tagline) | `Pay-per-call IBM Granite AI over MCP. x402 agentic payments let any AI agent call Granite chat, code, embeddings, document analysis, and time-series forecasting — settled per call in USDC on Solana, no IBM Cloud account required.` |+| Summary | `x402 pay-per-use IBM Granite AI — chat, code, embeddings, document analysis, and time-series forecasting. Pay USDC on Solana per call. No IBM Cloud account required.` |+| Version | `1.0.0` |+| Change log | `Initial release` |+| Domain tags (max 3) | Software development · Data & analytics · Productivity |+| Language support | English (Granite 3 models also process German, Spanish, French, Portuguese, Japanese, Korean, Italian, Dutch, Chinese, Arabic, Czech) |+| Application ID | `three-ws-x402-mcp` |+| Application Name | `three.ws` |+| Application icon | `public/pwa-icon.svg` (square, <200kb) |+| Transport | Streamable HTTP (remote) · stdio (`npx @three-ws/ibm-x402-mcp`) |+| Server end-point URL | `https://three.ws/api/ibm-mcp` (Streamable HTTP, MCP 2025-06-18 — the 5 Granite tools; see note below) |++## Related links++- npm: https://www.npmjs.com/package/@three-ws/ibm-x402-mcp+- Source: https://github.com/nirholas/three.ws/tree/main/packages/ibm-x402-mcp+- MCP registry name: `io.github.nirholas/ibm-x402-mcp`+- Homepage: https://three.ws+- Support: https://three.ws/support+- x402 protocol: https://x402.org++## Description++three.ws x402 MCP turns IBM Granite foundation models into pay-per-use tools any AI agent or MCP client (Claude Desktop, Claude Code, Cursor, watsonx Orchestrate) can call. Every call is settled in USDC on Solana via the open x402 payment protocol — end users need no IBM Cloud account and no subscription. The server operator supplies IBM watsonx.ai credentials and a receiving wallet; callers pay only for what they use. When a tool is called without payment, the server returns an x402 PaymentRequired envelope quoting the exact USDC price; x402-capable clients pay and retry automatically.++Five tools, each independently priced:++1. **ibm_granite_chat — Conversational AI ($0.02/call).** General-purpose chat completion powered by IBM Granite 3 8B Instruct. Send a conversation as an ordered array of role/content messages (system, user, assistant) and receive the assistant reply plus token usage. Parameters: messages (1–50), optional model override, max_new_tokens (1–4096, default 1024), temperature (0–2, default 0.7). Use for Q&A, drafting, reasoning, and instruction following.++2. **ibm_granite_code — Code generation & review ($0.025/call).** Six code tasks via Granite instruct models: generate (new code from a description), review (bugs/security/improvements with severity-ranked findings), refactor (clarity/performance/best practices), explain (plain-language walkthrough), test (unit tests), and document (inline docs/docstrings). Parameters: task (enum), prompt (description or pasted code), optional language hint, optional context. Returns the produced code or review with a brief rationale.++3. **ibm_granite_embed — Text embeddings ($0.005/call).** Batch-embeds 1–64 texts (up to 8,000 chars each) using ibm/granite-embedding-278m-multilingual, returning one dense float vector per input. Parameters: inputs (array), optional model override. Use for semantic search, RAG retrieval, clustering, deduplication, and cross-language similarity scoring.++4. **ibm_granite_analyze — Structured document analysis ($0.04/call).** Extracts a machine-readable JSON analysis from any text — entities, sentiment (label + score), key findings, severity-tagged risk flags, a 3-sentence summary, and 3 actionable next steps. Parameters: document (up to 24,000 chars), analysis_type (general, contract, financial, technical, medical, sentiment), optional language hint. Tailors extraction per type (e.g. contract → parties, obligations, termination/penalty clauses; financial → metrics, red flags, forward-looking statements).++5. **ibm_granite_forecast — Time-series forecasting ($0.05/call).** Zero-shot numeric forecasting via IBM Granite TTM (Tiny Time Mixer) — no training required. Provide 64–1024 ISO-8601 timestamps and aligned numeric values at a uniform cadence; receive a forecast horizon as timestamped points. Parameters: timestamps, values (equal length), freq (pandas-style, e.g. 1h/1D/1W), optional prediction_length (1–96), optional label. Use for revenue, traffic, demand, sensor, energy, and financial series.++Models: IBM Granite 3 8B Instruct (chat/code/analyze), IBM Granite Embedding 278M Multilingual (embed), and IBM Granite TTM (forecast) — all served by IBM watsonx.ai, region-configurable (us-south default; eu-de, eu-gb, jp-tok, au-syd, ca-tor). Open source (Apache-2.0) by three.ws. Independent project integrating IBM Granite via watsonx.ai; not an IBM product. Granite, watsonx, and watsonx.ai are trademarks of IBM.++## Pricing tab++Billing is **out-of-band**: every tool call settles in USDC on Solana via the x402 protocol. IBM Cloud is not the billing channel — end users need no IBM Cloud account and no subscription. The catalog listing itself is therefore **Free to add**; the per-call USDC prices are disclosed in the Description.++| Field | Value |+|---|---|+| Pricing model | `Free` (open-source MCP server; per-call cost settled off-platform via x402) |++If the Partner Center "Add starting price" flow requires a starting-price row (Paid model), use the cheapest tool's per-call floor so the advertised "starting at" figure is honest:++| Field | Value | Notes |+|---|---|---|+| Country | `United States` | Base price row; add other countries as needed |+| Currency | `USD` | x402 settles in USDC; USD is the display peg |+| Quantity Tier | `1` | Tier starts at 1 unit (1 API call) |+| Price | `0.005` | Lowest per-call price (`ibm_granite_embed`) — "starting at $0.005/call" |+| Unit / metric | `per API call` | If the metric field is present |++Per-call prices (source of truth — keep in sync with Description and `src/tools/`): `ibm_granite_embed` $0.005 · `ibm_granite_chat` $0.02 · `ibm_granite_code` $0.025 · `ibm_granite_analyze` $0.04 · `ibm_granite_forecast` $0.05.++## Support tab++| Field | Value |+|---|---|+| Support provider | `Third party` (three.ws — single accountable maintainer with private email + security triage) |+| Statement of support | See below — keep in sync with `SUPPORT.md` |+| Support languages | English |++**Statement of support** (paste verbatim into the required field):++> x402 MCP (three-ws-x402-mcp) is an independent, open-source product built and maintained by three.ws. It integrates IBM Granite via watsonx.ai but is not an IBM product and is not supported by IBM.+>+> Where to get help:+> • GitHub Issues — bugs, crashes, unexpected tool output, feature requests: https://github.com/nirholas/three.ws/issues/new+> • GitHub Discussions — setup and integration "how do I…" questions: https://github.com/nirholas/three.ws/discussions+> • Email — private or account-specific issues: [email protected]+> • Security — report vulnerabilities privately; please do not open a public issue: [email protected]+> • All channels in one place: https://three.ws/support+>+> What we support:+> • Installing, configuring, and running the MCP server.+> • The five ibm_granite_* tools (chat, code, embed, analyze, forecast) and their x402 USDC-on-Solana payment flow.+> • Integration with MCP clients (Claude Desktop, Claude Code, Cursor, and custom agents).+>+> Out of scope — handled by IBM Cloud Support (https://cloud.ibm.com/unifieddeliveryportal): IBM watsonx.ai platform issues, Granite model behavior, and IBM billing. We will help you tell a server problem from an IBM-platform problem.+>+> Response is best-effort, typically within a few business days; security reports are prioritized. Support is provided in English. Please redact all secrets (API keys, private keys, wallet seeds) from any report — a truncated public Solana address is fine.+>+> Granite, watsonx, and watsonx.ai are trademarks of IBM.++## Note on the endpoint URL++The five Granite tools ship over two transports backed by one tool suite:++- **stdio** — the `@three-ws/ibm-x402-mcp` npm package (`npx @three-ws/ibm-x402-mcp`), for local MCP hosts (Claude Desktop, Claude Code, Cursor). Payment: per-call USDC on Solana via the x402 envelope.+- **Streamable HTTP (remote)** — `https://three.ws/api/ibm-mcp` (MCP 2025-06-18), the endpoint the watsonx Orchestrate catalog requires. Source: [`api/ibm-mcp.js`](https://github.com/nirholas/three.ws/blob/main/api/ibm-mcp.js) + [`api/_mcpibm/`](https://github.com/nirholas/three.ws/tree/main/api/_mcpibm). It reuses the platform's server-side watsonx client (`api/_lib/watsonx.js`, `api/_lib/watsonx-forecast.js`) and the standard x402 settlement infra (`api/_lib/x402-spec.js`), and is registered as `io.github.nirholas/ibm-x402-mcp-remote` (see `server-ibm.json`). Tool schemas, prices, and output shapes are kept identical to the npm package.++**Access on the remote endpoint** is dual-mode, which resolves the Orchestrate constraint (watsonx Orchestrate is not x402-capable):++- **Anonymous callers pay per call** in USDC. An unpaid `tools/call` returns a 402 quoting the exact per-tool price (chat $0.02, code $0.025, embed $0.005, analyze $0.04, forecast $0.05), advertised on Base and Solana mainnet; x402-capable clients pay and retry automatically. Settlement runs after the tool succeeds.+- **Authenticated three.ws principals (Bearer / OAuth) call without per-call payment** — the operator-funded path. A watsonx Orchestrate connection supplies a Bearer credential here, so the tools are effectively included-in-connection rather than billed per USDC call.++The operator funds inference by setting `WATSONX_API_KEY` + `WATSONX_PROJECT_ID` (and the platform's `X402_PAY_TO_*` receiving wallets) in the deployment environment; end users still need no IBM Cloud account.diff --git a/server-ibm.json b/server-ibm.jsonnew file mode 100644index 000000000..ed5cbc6ea--- /dev/null+++ b/server-ibm.json@@ -0,0 +1,17 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/ibm-x402-mcp-remote",+ "description": "x402 pay-per-use IBM Granite AI over a hosted MCP endpoint — chat, code, embeddings, document analysis, and time-series forecasting. Pay USDC on Base or Solana per call. No IBM Cloud account required. By three.ws.",+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/ibm-x402-mcp"+ },+ "version": "1.0.0",+ "remotes": [+ {+ "type": "streamable-http",+ "url": "https://three.ws/api/ibm-mcp"+ }+ ]+}diff --git a/tests/api/ibm-mcp.test.js b/tests/api/ibm-mcp.test.jsnew file mode 100644index 000000000..9b8581584--- /dev/null+++ b/tests/api/ibm-mcp.test.js@@ -0,0 +1,237 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// ── Env (lazy env.* access in shared helpers) ───────────────────────────────+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';+process.env.WATSONX_API_KEY ||= 'test-key';+process.env.WATSONX_PROJECT_ID ||= 'proj-123';++// ── watsonx.ai clients (no network, no real credentials) ────────────────────+const wx = {+ chat: vi.fn(async () => ({+ text: 'Granite says hello.',+ finishReason: 'stop',+ usage: { prompt_tokens: 9, completion_tokens: 4 },+ model: 'ibm/granite-3-8b-instruct',+ })),+ embed: vi.fn(async () => ({+ model: 'ibm/granite-embedding-278m-multilingual',+ vectors: [[0.1, 0.2, 0.3]],+ dimensions: 3,+ inputCount: 1,+ })),+};+vi.mock('../../api/_lib/watsonx.js', () => ({+ watsonxConfig: vi.fn(() => ({ configured: true })),+ watsonxChatComplete: (...a) => wx.chat(...a),+ watsonxEmbed: (...a) => wx.embed(...a),+}));++const fc = {+ forecast: vi.fn(async () => ({+ model: 'ibm/granite-ttm-512-96-r2',+ timestamps: ['2025-01-03T00:00:00Z', '2025-01-04T00:00:00Z'],+ values: [123, 130],+ inputWindow: 64,+ })),+};+vi.mock('../../api/_lib/watsonx-forecast.js', () => ({+ watsonxForecast: (...a) => fc.forecast(...a),+}));++// ── Bazaar discovery — stub the @x402-SDK-backed helper ─────────────────────+vi.mock('../../api/_lib/x402/bazaar-helpers.js', () => ({+ declareMcpDiscovery: vi.fn(({ toolName }) => ({ discoverable: true, toolName })),+ withService: vi.fn(() => ({+ serviceName: 'three.ws',+ tags: [],+ iconUrl: 'https://three.ws/favicon.ico',+ })),+}));++// ── Usage (no DB in unit tests) ─────────────────────────────────────────────+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++const { dispatch, PROTOCOL_VERSION } = await import('../../api/_mcpibm/dispatch.js');+const { graniteX402Amount, priceFor } = await import('../../api/_mcpibm/pricing.js');++const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402', x402Paid: true };+const call = (name, args) =>+ dispatch(+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } },+ AUTH,+ );++function makeSeries(n) {+ const timestamps = [];+ const values = [];+ const base = Date.UTC(2025, 0, 1) / 1000;+ for (let i = 0; i < n; i++) {+ timestamps.push(new Date((base + i * 86400) * 1000).toISOString());+ values.push(1000 + i);+ }+ return { timestamps, values };+}++beforeEach(() => {+ wx.chat.mockClear();+ wx.embed.mockClear();+ fc.forecast.mockClear();+});++describe('IBM Granite MCP — dispatch', () => {+ it('lists the five Granite tools with per-call pricing', 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([+ 'ibm_granite_chat',+ 'ibm_granite_code',+ 'ibm_granite_embed',+ 'ibm_granite_analyze',+ 'ibm_granite_forecast',+ ]);+ const chat = r.result.tools.find((t) => t.name === 'ibm_granite_chat');+ expect(chat.pricing).toMatchObject({ amount_usdc: 0.02, currency: 'USDC', scheme: 'x402' });+ expect(chat.extensions.bazaar.discoverable).toBe(true);+ expect(chat.inputSchema.required).toContain('messages');+ });++ it('initialize advertises the ibm-x402-mcp server', async () => {+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'initialize' }, AUTH);+ expect(r.result.serverInfo.name).toBe('ibm-x402-mcp');+ expect(r.result.protocolVersion).toBe(PROTOCOL_VERSION);+ });++ it('ibm_granite_chat returns the assistant reply + usage', async () => {+ const r = await call('ibm_granite_chat', { messages: [{ role: 'user', content: 'hi' }] });+ expect(wx.chat).toHaveBeenCalledWith(+ { configured: true },+ {+ messages: [{ role: 'user', content: 'hi' }],+ model: undefined,+ maxTokens: 1024,+ temperature: 0.7,+ },+ );+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ text: 'Granite says hello.',+ model: 'ibm/granite-3-8b-instruct',+ });+ expect(r.result.content[0].text).toBe('Granite says hello.');+ });++ it('ibm_granite_code maps the task to a system prompt + decoding params', async () => {+ const r = await call('ibm_granite_code', { task: 'review', prompt: 'def f(): return 1/0' });+ const [, opts] = wx.chat.mock.calls[0];+ expect(opts.messages[0].role).toBe('system');+ expect(opts.messages[0].content).toContain('FINDINGS');+ expect(opts.temperature).toBe(0.1); // non-generate → 0.1+ expect(opts.maxTokens).toBe(2048);+ expect(r.result.structuredContent).toMatchObject({ ok: true, task: 'review' });+ });++ it('ibm_granite_embed returns one vector per input', async () => {+ const r = await call('ibm_granite_embed', { inputs: ['hello world'] });+ expect(wx.embed).toHaveBeenCalledWith(+ { configured: true },+ { inputs: ['hello world'], model: undefined },+ );+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ dimensions: 3,+ inputCount: 1,+ });+ expect(r.result.structuredContent.vectors).toHaveLength(1);+ });++ it('ibm_granite_analyze parses Granite JSON into structuredContent', async () => {+ wx.chat.mockResolvedValueOnce({+ text: '{"summary":"ok","entities":[],"sentiment":{"overall":"neutral","score":0},"key_findings":[],"risk_flags":[],"next_steps":[],"analysis_type":"contract"}',+ usage: { prompt_tokens: 50, completion_tokens: 60 },+ model: 'ibm/granite-3-8b-instruct',+ });+ const r = await call('ibm_granite_analyze', {+ document: 'A contract.',+ analysis_type: 'contract',+ });+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ analysis_type: 'contract',+ summary: 'ok',+ sentiment: { overall: 'neutral', score: 0 },+ });+ });++ it('ibm_granite_analyze falls back to raw_response on non-JSON output', async () => {+ wx.chat.mockResolvedValueOnce({+ text: 'not json at all',+ usage: {},+ model: 'ibm/granite-3-8b-instruct',+ });+ const r = await call('ibm_granite_analyze', { document: 'x' });+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ analysis_type: 'general', // schema default applied by Ajv+ raw_response: 'not json at all',+ });+ expect(r.result.structuredContent.parse_error).toBeTruthy();+ });++ it('ibm_granite_forecast returns timestamped forecast points', async () => {+ const { timestamps, values } = makeSeries(64);+ const r = await call('ibm_granite_forecast', {+ timestamps,+ values,+ freq: '1D',+ label: 'rev',+ });+ expect(fc.forecast).toHaveBeenCalledWith(+ { configured: true },+ { timestamps, values, freq: '1D', predictionLength: undefined },+ );+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ label: 'rev',+ model: 'ibm/granite-ttm-512-96-r2',+ forecastSteps: 2,+ });+ expect(r.result.structuredContent.forecast[0]).toEqual({+ timestamp: '2025-01-03T00:00:00Z',+ value: 123,+ });+ });++ it('rejects a chat call with no messages as invalid params', async () => {+ const r = await call('ibm_granite_chat', { messages: [] });+ expect(r.error.code).toBe(-32602);+ expect(wx.chat).not.toHaveBeenCalled();+ });++ it('rejects an unknown tool', async () => {+ const r = await call('ibm_granite_unknown', {});+ expect(r.error.code).toBe(-32602);+ });++ it('surfaces a watsonx upstream failure as a tool error (not an rpc error)', async () => {+ wx.chat.mockRejectedValueOnce(new Error('watsonx 401: invalid api key'));+ const r = await call('ibm_granite_chat', { messages: [{ role: 'user', content: 'hi' }] });+ expect(r.result.isError).toBe(true);+ expect(r.result.content[0].text).toContain('Error:');+ });+});++describe('IBM Granite MCP — pricing', () => {+ it('derives the x402 atomic amount from the per-tool USDC price', () => {+ expect(graniteX402Amount('ibm_granite_chat')).toBe('20000'); // $0.02 → 20000 micro-USDC+ expect(graniteX402Amount('ibm_granite_embed')).toBe('5000'); // $0.005 → 5000+ expect(graniteX402Amount('ibm_granite_forecast')).toBe('50000'); // $0.05 → 50000+ });++ it('returns null for an unpriced / unknown tool', () => {+ expect(graniteX402Amount('nope')).toBeNull();+ expect(priceFor('nope')).toBeNull();+ });+});