Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add ibm-x402-mcp package with Granite tool suite
nirholas02df227e8a52
diff --git a/package.json b/package.jsonindex 5f801291f..174577cb2 100644--- a/package.json+++ b/package.json@@ -36,6 +36,7 @@"packages/viewer-presets","packages/pumpfun-mcp","packages/ibm-watsonx-mcp",+ "packages/ibm-x402-mcp","packages/threews-avatar-mcp"],"main": "src/app.js",diff --git a/packages/ibm-x402-mcp/LICENSE b/packages/ibm-x402-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/ibm-x402-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-x402-mcp/README.md b/packages/ibm-x402-mcp/README.mdnew file mode 100644index 000000000..fd9dba7f8--- /dev/null+++ b/packages/ibm-x402-mcp/README.md@@ -0,0 +1,181 @@+# @three-ws/ibm-x402-mcp++**The world's first x402-enabled MCP server on IBM Cloud.**++An [MCP](https://modelcontextprotocol.io) server that exposes IBM Granite foundation models as pay-per-use tools via the [x402](https://x402.org) payment protocol. End users pay **USDC on Solana** per call — no IBM Cloud account required.++> Built by [three.ws](https://three.ws). Listed on IBM Cloud Partner Center.++---++## How it works++1. An MCP client (Claude Desktop, Claude Code, Cursor, etc.) connects to this server.+2. The client calls a tool — e.g. `ibm_granite_chat`.+3. The server responds with an x402 `PaymentRequired` envelope quoting the USDC price.+4. The client pays (signs a Solana USDC transaction via its x402-capable wallet).+5. The server verifies + settles the payment, calls IBM watsonx.ai, and returns the result.++The server operator supplies IBM credentials (`WATSONX_*`) and a receiving Solana wallet (`MCP_SVM_PAYMENT_ADDRESS`). End users supply only USDC.++---++## Tools++| Tool | What it does | Price |+|---|---|---|+| `ibm_granite_chat` | Conversational AI via IBM Granite 3 8B Instruct | $0.02 USDC |+| `ibm_granite_code` | Code generation, review, refactoring, testing, and documentation | $0.025 USDC |+| `ibm_granite_embed` | Batch text embeddings for RAG, semantic search, and clustering (up to 64 texts) | $0.005 USDC |+| `ibm_granite_analyze` | Structured document analysis: entities, sentiment, risk flags, summary, next steps | $0.04 USDC |+| `ibm_granite_forecast` | Zero-shot time-series forecasting via IBM Granite TTM | $0.05 USDC |++---++## Quickstart (server operator)++```bash+MCP_SVM_PAYMENT_ADDRESS=<your-solana-wallet> \+WATSONX_API_KEY=<ibm-api-key> \+WATSONX_PROJECT_ID=<watsonx-project-id> \+npx @three-ws/ibm-x402-mcp+```++---++## Configuration++### Required++| Env var | Description |+|---|---|+| `MCP_SVM_PAYMENT_ADDRESS` | Solana wallet that receives USDC payments from callers |+| `WATSONX_API_KEY` | IBM Cloud API key — [create one](https://cloud.ibm.com/iam/apikeys) |+| `WATSONX_PROJECT_ID` | watsonx.ai project id (Project → Manage → General → Project ID) |++### Optional++| Env var | Default | Description |+|---|---|---|+| `WATSONX_SPACE_ID` | — | Deployment space id (alternative to `WATSONX_PROJECT_ID`) |+| `WATSONX_URL` | `https://us-south.ml.cloud.ibm.com` | Regional inference host |+| `WATSONX_MODEL_ID` | `ibm/granite-3-8b-instruct` | Default chat/generation model |+| `WATSONX_EMBED_MODEL_ID` | `ibm/granite-embedding-278m-multilingual` | Default embedding model |+| `X402_FEE_PAYER_SOLANA` | three.ws fee payer | Solana account sponsoring tx fees |+| `X402_FACILITATOR_URL` | `https://facilitator.payai.network` | x402 payment facilitator |++Regional hosts: `us-south`, `eu-de`, `eu-gb`, `jp-tok`, `au-syd`, `ca-tor`+→ e.g. `https://eu-de.ml.cloud.ibm.com`++---++## Wire into Claude Desktop / Claude Code / Cursor++```json+{+ "mcpServers": {+ "ibm-x402": {+ "command": "npx",+ "args": ["-y", "@three-ws/ibm-x402-mcp"],+ "env": {+ "MCP_SVM_PAYMENT_ADDRESS": "your-solana-wallet-address",+ "WATSONX_API_KEY": "your-ibm-cloud-api-key",+ "WATSONX_PROJECT_ID": "your-watsonx-project-id"+ }+ }+ }+}+```++---++## Tool examples++### `ibm_granite_chat`+```jsonc+{+ "messages": [+ { "role": "system", "content": "You are an expert data engineer." },+ { "role": "user", "content": "Design a lakehouse schema for IoT sensor telemetry." }+ ],+ "max_new_tokens": 1024,+ "temperature": 0.7+}+```++### `ibm_granite_code`+```jsonc+{+ "task": "review",+ "prompt": "def calculate_roi(revenue, cost): return revenue / cost",+ "language": "Python"+}+```++### `ibm_granite_embed`+```jsonc+{+ "inputs": [+ "enterprise data governance",+ "cloud-native AI pipeline",+ "real-time analytics"+ ]+}+```++### `ibm_granite_analyze`+```jsonc+{+ "document": "This Software License Agreement is entered into between...",+ "analysis_type": "contract"+}+```++### `ibm_granite_forecast`+```jsonc+{+ "timestamps": ["2025-01-01T00:00:00Z", "2025-01-02T00:00:00Z"],+ "values": [12500, 13200],+ "freq": "1D",+ "prediction_length": 14,+ "label": "daily_revenue_usd"+}+```++---++## Payment flow++This server uses the [x402 protocol](https://x402.org) for micropayments:++1. Client calls a tool without payment → receives `402 PaymentRequired` with USDC amount + Solana address.+2. Client builds a signed Solana USDC transfer transaction.+3. Client retries with the signed tx in `_meta["x402/payment"]`.+4. Server verifies via the [PayAI facilitator](https://facilitator.payai.network).+5. Server calls IBM watsonx.ai and settles the payment.+6. Response includes `_meta["x402/payment-response"]` with the settlement receipt.++x402-capable MCP clients handle this flow automatically.++---++## Architecture++```+MCP Client (Claude Desktop / Cursor / agent)+ │ tools/call (with x402 payment in _meta)+ ▼+ibm-x402-mcp (stdio MCP server)+ │ verify + settle USDC on Solana+ ├──► PayAI Facilitator (https://facilitator.payai.network)+ │+ │ inference call with Bearer token+ └──► IBM watsonx.ai (us-south.ml.cloud.ibm.com)+ └── IBM Granite 3 8B Instruct / Embedding / TTM+```++---++## License++Apache-2.0 · Built by [three.ws](https://three.ws)diff --git a/packages/ibm-x402-mcp/package.json b/packages/ibm-x402-mcp/package.jsonnew file mode 100644index 000000000..1d0d14bd0--- /dev/null+++ b/packages/ibm-x402-mcp/package.json@@ -0,0 +1,67 @@+{+ "name": "@three-ws/ibm-x402-mcp",+ "version": "1.0.0",+ "description": "x402 pay-per-use MCP server for IBM Granite AI — chat, code, embeddings, analysis, and time-series forecasting. Pay USDC on Solana per call. No IBM Cloud account required.",+ "type": "module",+ "author": "nirholas",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "mcpName": "io.github.nirholas/ibm-x402-mcp",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws.git",+ "directory": "packages/ibm-x402-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "ibm",+ "watsonx",+ "ibm-granite",+ "granite",+ "x402",+ "usdc",+ "solana",+ "pay-per-use",+ "ai-agent",+ "three.ws",+ "foundation-models",+ "embeddings",+ "time-series"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "ibm-x402-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",+ "@x402/core": "^2.13.0",+ "@x402/extensions": "^2.12.0",+ "@x402/mcp": "^2.13.0",+ "@x402/svm": "^2.13.0",+ "zod": "^3.23.8",+ "zod-to-json-schema": "3.25.2"+ }+}diff --git a/packages/ibm-x402-mcp/server.json b/packages/ibm-x402-mcp/server.jsonnew file mode 100644index 000000000..e11eaaca6--- /dev/null+++ b/packages/ibm-x402-mcp/server.json@@ -0,0 +1,79 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/ibm-x402-mcp",+ "description": "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.",+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/ibm-x402-mcp"+ },+ "version": "1.0.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/ibm-x402-mcp",+ "version": "1.0.0",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "MCP_SVM_PAYMENT_ADDRESS",+ "description": "Solana wallet address that receives USDC payments from tool callers (server operator's receiving wallet). Required to accept x402 payments.",+ "isRequired": true,+ "isSecret": false,+ "format": "string"+ },+ {+ "name": "WATSONX_API_KEY",+ "description": "IBM Cloud API key used by the server to call watsonx.ai on behalf of end users. Create one at https://cloud.ibm.com/iam/apikeys.",+ "isRequired": true,+ "isSecret": true,+ "format": "string"+ },+ {+ "name": "WATSONX_PROJECT_ID",+ "description": "watsonx.ai project id scoping all inference calls. Find it under your 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 watsonx.ai inference host. Defaults to https://us-south.ml.cloud.ibm.com. Other regions: eu-de, eu-gb, jp-tok, au-syd, ca-tor.",+ "isRequired": false,+ "format": "string"+ },+ {+ "name": "WATSONX_MODEL_ID",+ "description": "Default chat/generation Granite 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": "X402_FEE_PAYER_SOLANA",+ "description": "Solana account that sponsors transaction fees for x402 payments. Defaults to the three.ws fee payer.",+ "isRequired": false,+ "format": "string"+ },+ {+ "name": "X402_FACILITATOR_URL",+ "description": "x402 facilitator endpoint for payment verification and settlement. Defaults to https://facilitator.payai.network.",+ "isRequired": false,+ "format": "string"+ }+ ]+ }+ ]+}diff --git a/packages/ibm-x402-mcp/src/index.js b/packages/ibm-x402-mcp/src/index.jsnew file mode 100644index 000000000..1b0386723--- /dev/null+++ b/packages/ibm-x402-mcp/src/index.js@@ -0,0 +1,117 @@+#!/usr/bin/env node+// @three-ws/ibm-x402-mcp — stdio MCP server: IBM Granite AI tools gated by x402 USDC payments.+//+// The world's first x402-enabled MCP server on IBM Cloud.+// End users pay USDC on Solana per call — no IBM Cloud account needed.+// Server operators supply WATSONX_* credentials and MCP_SVM_PAYMENT_ADDRESS.+//+// Run standalone:+// MCP_SVM_PAYMENT_ADDRESS=<your-solana-wallet> WATSONX_API_KEY=... WATSONX_PROJECT_ID=... node src/index.js+//+// Wire into Claude Desktop / Cursor / any MCP host:+// npx @three-ws/ibm-x402-mcp+//+// Inspect tools:+// npx -y @modelcontextprotocol/inspector npx @three-ws/ibm-x402-mcp++import { pathToFileURL } from 'node:url';++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++import { assertPaymentEnv, getResourceServer, getLastFacilitatorInitError } from './payments.js';+import { loadConfig, WatsonxClient } from './watsonx.js';+import { buildGraniteChatTool } from './tools/granite-chat.js';+import { buildGraniteCodeTool } from './tools/granite-code.js';+import { buildGraniteEmbedTool } from './tools/granite-embed.js';+import { buildGraniteAnalyzeTool } from './tools/granite-analyze.js';+import { buildGraniteForecastTool } from './tools/granite-forecast.js';++const SERVER_INSTRUCTIONS =+ 'x402 pay-per-use IBM Granite AI tools from three.ws. Each tool lists its USDC price. ' ++ 'Tool calls without an x402 payment payload in _meta return a PaymentRequired envelope ' ++ '(v2 MCP transport spec). ' ++ 'Tools: ibm_granite_chat ($0.02 — conversational AI), ' ++ 'ibm_granite_code ($0.025 — generate/review/refactor/explain/test/document code), ' ++ 'ibm_granite_embed ($0.005 — batch embeddings for RAG/search), ' ++ 'ibm_granite_analyze ($0.04 — structured document analysis), ' ++ 'ibm_granite_forecast ($0.05 — zero-shot time-series forecasting). ' ++ 'No IBM Cloud account required — pay USDC on Solana. Powered by IBM Granite foundation models.';++/**+ * Build and return a fully-registered McpServer without connecting any transport.+ * Safe to call from tests — no payment env or IBM credentials required at registration time.+ */+export async function buildServer(client) {+ const server = new McpServer(+ { name: 'ibm-x402-mcp', version: '1.0.0' },+ {+ capabilities: { tools: { listChanged: false } },+ instructions: SERVER_INSTRUCTIONS,+ },+ );++ const tools = await Promise.all([+ buildGraniteChatTool(client),+ buildGraniteCodeTool(client),+ buildGraniteEmbedTool(client),+ buildGraniteAnalyzeTool(client),+ buildGraniteForecastTool(client),+ ]);++ for (const t of tools) {+ server.registerTool(+ t.name,+ { title: t.title, description: t.description, inputSchema: t.inputSchema },+ t.handler,+ );+ }++ return server;+}++async function main() {+ // Fail fast on missing payment address — a running server that can't receive+ // USDC payments is useless.+ assertPaymentEnv();++ // Load IBM credentials once at startup. Throws with an actionable message on+ // any missing required env var so the operator sees the problem immediately.+ let config;+ try {+ config = loadConfig();+ } catch (err) {+ console.error(`[ibm-x402-mcp] configuration error: ${err.message}`);+ process.exit(1);+ return;+ }++ const client = new WatsonxClient(config);++ // Warm the shared x402 resource server so the first paid call doesn't pay+ // the /supported fetch cost.+ await getResourceServer();+ const initErr = getLastFacilitatorInitError();+ if (initErr) {+ console.error(`[ibm-x402-mcp] facilitator init warning: ${initErr.message}`);+ }++ const server = await buildServer(client);+ const transport = new StdioServerTransport();+ await server.connect(transport);++ console.error(+ `[ibm-x402-mcp] ready — 5 IBM Granite x402 tools registered over stdio ` ++ `(model: ${config.chatModel} @ ${config.url})`,+ );+}++const isEntryPoint =+ Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;++if (isEntryPoint) {+ main().catch((err) => {+ console.error(`ibm-x402-mcp: ${err?.message || err}`);+ process.exit(1);+ });+}diff --git a/packages/ibm-x402-mcp/src/payments.js b/packages/ibm-x402-mcp/src/payments.jsnew file mode 100644index 000000000..1d3e0c0bc--- /dev/null+++ b/packages/ibm-x402-mcp/src/payments.js@@ -0,0 +1,168 @@+// x402 payment wiring for ibm-x402-mcp — Solana USDC, exact scheme.+//+// Mirrors the pattern from mcp-server/src/payments.js. Builds a single shared+// x402ResourceServer per process that verifies + settles USDC on Solana+// mainnet via PayAI's facilitator. Every paid tool wraps its handler in+// `paid(cfg, fn)`, which returns the McpServer.tool() callback per the @x402/mcp+// transport spec (PaymentRequired in structuredContent, settlement under+// _meta["x402/payment-response"]).+//+// Environment (server operator — NOT the end user):+// MCP_SVM_PAYMENT_ADDRESS — Solana wallet that receives USDC (required)+// X402_PAY_TO_SOLANA — fallback alias+// X402_PAY_TO — fallback alias+// X402_FEE_PAYER_SOLANA — transaction fee payer (optional, defaults to three.ws fee payer)+// X402_FACILITATOR_URL — PayAI facilitator URL (optional)+// X402_FACILITATOR_TOKEN — Bearer token for facilitator (optional)+// X402_ASSET_MINT_SOLANA — USDC mint override (optional)++import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';+import { registerExactSvmScheme } from '@x402/svm/exact/server';+import { createPaymentWrapper, createToolResourceUrl } from '@x402/mcp';+import { declareDiscoveryExtension } from '@x402/extensions/bazaar';++const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const DEFAULT_SOLANA_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++const env = (key, fallback) => {+ const v = process.env[key];+ return v && v.trim() ? v.trim() : fallback;+};++function requireSvmPayTo() {+ const addr = env('MCP_SVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_SOLANA') || env('X402_PAY_TO');+ if (!addr) {+ throw new Error(+ 'ibm-x402-mcp: set MCP_SVM_PAYMENT_ADDRESS to your Solana wallet address to receive USDC payments.',+ );+ }+ return addr;+}++export function assertPaymentEnv() {+ requireSvmPayTo();+}++function svmFeePayer() {+ return env('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');+}++function buildFacilitator() {+ const url = env('X402_FACILITATOR_URL', 'https://facilitator.payai.network');+ const token = env('X402_FACILITATOR_TOKEN');+ return new HTTPFacilitatorClient({+ url,+ createAuthHeaders: token+ ? async () => ({ headers: { Authorization: `Bearer ${token}` } })+ : undefined,+ });+}++let resourceServerPromise = null;+let lastInitError = null;++export function getResourceServer() {+ if (resourceServerPromise) return resourceServerPromise;+ resourceServerPromise = (async () => {+ const server = new x402ResourceServer([buildFacilitator()]);+ registerExactSvmScheme(server, {});+ try {+ await server.initialize();+ } catch (err) {+ lastInitError = err;+ console.error(`[ibm-x402-mcp] facilitator initialize() failed: ${err.message}`);+ }+ return server;+ })();+ return resourceServerPromise;+}++export function getLastFacilitatorInitError() {+ return lastInitError;+}++async function buildAccepts({ resourceServer, priceUsd, resourceUrl }) {+ return resourceServer.buildPaymentRequirementsFromOptions(+ [+ {+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ payTo: requireSvmPayTo(),+ price: priceUsd,+ maxTimeoutSeconds: 60,+ extra: {+ name: 'USDC',+ decimals: 6,+ asset: env('X402_ASSET_MINT_SOLANA', DEFAULT_SOLANA_USDC),+ feePayer: svmFeePayer(),+ },+ },+ ],+ { resourceUrl },+ );+}++/**+ * Wrap a tool handler with Solana USDC x402 payment (exact scheme).+ *+ * Payment wiring is built lazily on first invocation — tool registration stays+ * secret-free so buildServer() can enumerate tools without payment env.+ *+ * @param {object} cfg+ * @param {string} cfg.toolName+ * @param {string} cfg.description+ * @param {string} cfg.priceUsd — e.g. "$0.02"+ * @param {object} cfg.inputSchema — JSON Schema for tool args+ * @param {object} [cfg.example]+ * @param {object} [cfg.outputExample]+ * @param {Function} handler — async (args) → any+ * @returns {Function} MCP tool callback+ */+export function paid(cfg, handler) {+ const { toolName, description, priceUsd, inputSchema, example, outputExample } = cfg;++ if (!toolName) throw new Error('paid(): toolName is required');+ if (!priceUsd) throw new Error('paid(): priceUsd is required');++ let wrapperPromise = null;++ async function getWrapper() {+ if (wrapperPromise) return wrapperPromise;+ wrapperPromise = (async () => {+ const resourceServer = await getResourceServer();+ const resourceUrl = createToolResourceUrl(toolName);+ const accepts = await buildAccepts({ resourceServer, priceUsd, resourceUrl });++ const bazaar = declareDiscoveryExtension({+ toolName,+ description,+ transport: 'stdio',+ inputSchema,+ example,+ output: outputExample ? { example: outputExample } : undefined,+ });++ const wrap = createPaymentWrapper(resourceServer, {+ accepts,+ resource: { url: resourceUrl, description, mimeType: 'application/json' },+ extensions: bazaar,+ });++ return wrap(async (args) => {+ const result = await handler(args);+ const text = typeof result === 'string' ? result : JSON.stringify(result);+ return { content: [{ type: 'text', text }] };+ });+ })();+ return wrapperPromise;+ }++ return async function paidToolCallback(args, context) {+ const wrapped = await getWrapper();+ return wrapped(args, context);+ };+}++export function toolError(code, message, extra) {+ return { ok: false, error: code, message, ...(extra || {}) };+}diff --git a/packages/ibm-x402-mcp/src/tools/_shared.js b/packages/ibm-x402-mcp/src/tools/_shared.jsnew file mode 100644index 000000000..9697a6192--- /dev/null+++ b/packages/ibm-x402-mcp/src/tools/_shared.js@@ -0,0 +1,13 @@+import { z } from 'zod';+import { zodToJsonSchema } from 'zod-to-json-schema';++export { toolError } from '../payments.js';++export function jsonSchemaFromZod(shape) {+ const schema = zodToJsonSchema(z.object(shape).strict(), {+ $refStrategy: 'none',+ target: 'jsonSchema7',+ });+ delete schema.$schema;+ return schema;+}diff --git a/packages/ibm-x402-mcp/src/tools/granite-analyze.js b/packages/ibm-x402-mcp/src/tools/granite-analyze.jsnew file mode 100644index 000000000..da9d72828--- /dev/null+++ b/packages/ibm-x402-mcp/src/tools/granite-analyze.js@@ -0,0 +1,170 @@+// `ibm_granite_analyze` — paid MCP tool: structured document analysis via IBM Granite.+//+// Price: $0.04 USDC (exact, Solana). Applies IBM Granite to extract structured+// insights from any document: key entities, sentiment, risk flags, a summary,+// and actionable next steps — all in one call.++import { z } from 'zod';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';+import { WatsonxError } from '../watsonx.js';++const TOOL_NAME = 'ibm_granite_analyze';+const TOOL_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.';++const ANALYSIS_TYPES = ['general', 'contract', 'financial', 'technical', 'medical', 'sentiment'];++const inputZodShape = {+ document: z+ .string()+ .min(1)+ .max(24_000)+ .describe('The document, report, email, or text to analyze.'),+ analysis_type: z+ .enum(['general', 'contract', 'financial', 'technical', 'medical', 'sentiment'])+ .default('general')+ .describe(+ 'Analysis focus: general (universal), contract (legal terms, obligations), ' ++ 'financial (metrics, risks, forecasts), technical (architecture, issues), ' ++ 'medical (clinical entities, findings), or sentiment (tone, emotions).',+ ),+ language: z+ .string()+ .optional()+ .describe('Document language hint (e.g. "Spanish", "French"). Defaults to auto-detect.'),+};++const inputJsonSchema = jsonSchemaFromZod(inputZodShape);++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.`+ );+}++export async function buildGraniteAnalyzeTool(client) {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ priceUsd: '$0.04',+ inputSchema: inputJsonSchema,+ example: {+ document:+ 'This Services Agreement is entered into between Acme Corp and Vendor Inc effective January 1, 2026...',+ analysis_type: 'contract',+ },+ outputExample: {+ 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' },+ { name: 'Vendor Inc', type: 'organization', relevance: 'party' },+ { name: 'January 1, 2026', type: 'date', relevance: 'effective_date' },+ ],+ sentiment: { overall: 'neutral', score: 0.1 },+ key_findings: ['Auto-renewal clause on 60-day notice', 'Liability capped at 3 months fees'],+ risk_flags: [+ { flag: 'One-sided IP assignment clause', severity: 'high' },+ { flag: 'No SLA penalties defined', severity: 'medium' },+ ],+ next_steps: [+ 'Legal review of IP assignment clause section 8.2',+ 'Negotiate SLA penalties and uptime guarantees',+ 'Add data processing addendum for GDPR compliance',+ ],+ },+ },+ async ({ document, analysis_type = 'general', language }) => {+ try {+ const systemPrompt = buildAnalysisPrompt(analysis_type, language);+ const result = await client.chat(+ [+ { role: 'system', content: systemPrompt },+ { role: 'user', content: document },+ ],+ { parameters: { max_new_tokens: 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 client can decide+ return {+ 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 { ok: true, analysis_type, ...parsed, usage: result.usage, model: result.model };+ } catch (err) {+ if (err instanceof WatsonxError) {+ return toolError('watsonx_error', err.message, { status: err.status });+ }+ return toolError('internal_error', err.message);+ }+ },+ );++ return {+ name: TOOL_NAME,+ title: 'IBM Granite Analyze ($0.04)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/packages/ibm-x402-mcp/src/tools/granite-chat.js b/packages/ibm-x402-mcp/src/tools/granite-chat.jsnew file mode 100644index 000000000..e61e149d3--- /dev/null+++ b/packages/ibm-x402-mcp/src/tools/granite-chat.js@@ -0,0 +1,95 @@+// `ibm_granite_chat` — paid MCP tool: conversational AI via IBM Granite.+//+// Price: $0.02 USDC (exact, Solana). No IBM Cloud account needed — server+// handles credentials; end users pay USDC per call.++import { z } from 'zod';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';+import { WatsonxError } from '../watsonx.js';++const TOOL_NAME = 'ibm_granite_chat';+const TOOL_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 inputZodShape = {+ messages: z+ .array(+ z.object({+ role: z.enum(['system', 'user', 'assistant']).describe('Message role.'),+ content: z.string().min(1).max(32_000).describe('Message text.'),+ }),+ )+ .min(1)+ .max(50)+ .describe('Conversation history. Must include at least one user message.'),+ model: z+ .string()+ .optional()+ .describe(+ 'Override the Granite model id (e.g. ibm/granite-3-2b-instruct). Defaults to ibm/granite-3-8b-instruct.',+ ),+ max_new_tokens: z+ .number()+ .int()+ .min(1)+ .max(4096)+ .optional()+ .describe('Maximum tokens to generate. Defaults to 1024.'),+ temperature: z+ .number()+ .min(0)+ .max(2)+ .optional()+ .describe('Sampling temperature (0 = deterministic). Defaults to 0.7.'),+};++const inputJsonSchema = jsonSchemaFromZod(inputZodShape);++export async function buildGraniteChatTool(client) {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ priceUsd: '$0.02',+ inputSchema: inputJsonSchema,+ example: {+ messages: [{ role: 'user', content: 'Explain quantum entanglement in two sentences.' }],+ },+ outputExample: {+ ok: true,+ text: 'Quantum entanglement is a phenomenon where two particles...',+ finishReason: 'stop',+ usage: { input_tokens: 14, generated_tokens: 38 },+ model: 'ibm/granite-3-8b-instruct',+ },+ },+ async ({ messages, model, max_new_tokens, temperature }) => {+ try {+ const parameters = {};+ if (max_new_tokens !== undefined) parameters.max_new_tokens = max_new_tokens;+ if (temperature !== undefined) parameters.temperature = temperature;+ const result = await client.chat(messages, {+ model,+ parameters: Object.keys(parameters).length ? parameters : undefined,+ });+ return { ok: true, ...result };+ } catch (err) {+ if (err instanceof WatsonxError) {+ return toolError('watsonx_error', err.message, { status: err.status });+ }+ return toolError('internal_error', err.message);+ }+ },+ );++ return {+ name: TOOL_NAME,+ title: 'IBM Granite Chat ($0.02)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/packages/ibm-x402-mcp/src/tools/granite-code.js b/packages/ibm-x402-mcp/src/tools/granite-code.jsnew file mode 100644index 000000000..7d7b6e980--- /dev/null+++ b/packages/ibm-x402-mcp/src/tools/granite-code.js@@ -0,0 +1,117 @@+// `ibm_granite_code` — paid MCP tool: code generation and review via IBM Granite.+//+// Price: $0.025 USDC (exact, Solana). Uses IBM Granite's code-capable instruct+// models for generation, review, refactoring, and explanation tasks.++import { z } from 'zod';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';+import { WatsonxError } from '../watsonx.js';++const TOOL_NAME = 'ibm_granite_code';+const TOOL_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.',+};++const inputZodShape = {+ task: z+ .enum(['generate', 'review', 'refactor', 'explain', 'test', 'document'])+ .describe(+ 'Code task: generate (new code from description), review (bugs/security), refactor (quality), explain (plain language), test (unit tests), or document (add docstrings).',+ ),+ prompt: z+ .string()+ .min(1)+ .max(16_000)+ .describe(+ 'For "generate": describe what to build. For all others: paste the code to process.',+ ),+ language: z+ .string()+ .optional()+ .describe('Target programming language (e.g. "TypeScript", "Python", "Rust"). Optional for explain/review.'),+ context: z+ .string()+ .max(4_000)+ .optional()+ .describe('Additional context: architecture notes, constraints, or example usage.'),+};++const inputJsonSchema = jsonSchemaFromZod(inputZodShape);++function buildSystemPrompt(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;+}++export async function buildGraniteCodeTool(client) {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ priceUsd: '$0.025',+ inputSchema: inputJsonSchema,+ example: {+ task: 'generate',+ prompt: 'A debounce function with TypeScript generics and a cancel method.',+ language: 'TypeScript',+ },+ outputExample: {+ ok: true,+ task: 'generate',+ text: 'function debounce<T extends (...args: unknown[]) => void>(fn: T, delay: number) { ... }',+ usage: { input_tokens: 42, generated_tokens: 190 },+ model: 'ibm/granite-3-8b-instruct',+ },+ },+ async ({ task, prompt, language, context }) => {+ try {+ const systemContent = buildSystemPrompt(task, language);+ const userContent = context ? `${prompt}\n\nContext: ${context}` : prompt;+ const result = await client.chat(+ [+ { role: 'system', content: systemContent },+ { role: 'user', content: userContent },+ ],+ {+ parameters: {+ max_new_tokens: 2048,+ temperature: task === 'generate' ? 0.3 : 0.1,+ },+ },+ );+ return { ok: true, task, ...result };+ } catch (err) {+ if (err instanceof WatsonxError) {+ return toolError('watsonx_error', err.message, { status: err.status });+ }+ return toolError('internal_error', err.message);+ }+ },+ );++ return {+ name: TOOL_NAME,+ title: 'IBM Granite Code ($0.025)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/packages/ibm-x402-mcp/src/tools/granite-embed.js b/packages/ibm-x402-mcp/src/tools/granite-embed.jsnew file mode 100644index 000000000..d7753c184--- /dev/null+++ b/packages/ibm-x402-mcp/src/tools/granite-embed.js@@ -0,0 +1,73 @@+// `ibm_granite_embed` — paid MCP tool: text embeddings via IBM Granite.+//+// Price: $0.005 USDC (exact, Solana). Batch-embeds up to 64 texts per call+// using IBM's multilingual Granite embedding model, returning vectors suitable+// for semantic search, RAG retrieval, clustering, and similarity scoring.++import { z } from 'zod';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';+import { WatsonxError } from '../watsonx.js';++const TOOL_NAME = 'ibm_granite_embed';+const TOOL_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 inputZodShape = {+ inputs: z+ .array(z.string().min(1).max(8_000))+ .min(1)+ .max(64)+ .describe('Texts to embed. 1–64 strings per call, up to 8,000 characters each.'),+ model: z+ .string()+ .optional()+ .describe(+ 'Override the embedding model id (e.g. ibm/granite-embedding-125m-english). Defaults to ibm/granite-embedding-278m-multilingual.',+ ),+};++const inputJsonSchema = jsonSchemaFromZod(inputZodShape);++export async function buildGraniteEmbedTool(client) {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ priceUsd: '$0.005',+ inputSchema: inputJsonSchema,+ example: {+ inputs: ['enterprise AI platform', 'cloud-native machine learning'],+ },+ outputExample: {+ 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 ({ inputs, model }) => {+ try {+ const result = await client.embed(inputs, { model });+ return { ok: true, ...result };+ } catch (err) {+ if (err instanceof WatsonxError) {+ return toolError('watsonx_error', err.message, { status: err.status });+ }+ return toolError('internal_error', err.message);+ }+ },+ );++ return {+ name: TOOL_NAME,+ title: 'IBM Granite Embed ($0.005)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/packages/ibm-x402-mcp/src/tools/granite-forecast.js b/packages/ibm-x402-mcp/src/tools/granite-forecast.jsnew file mode 100644index 000000000..9d86420ae--- /dev/null+++ b/packages/ibm-x402-mcp/src/tools/granite-forecast.js@@ -0,0 +1,130 @@+// `ibm_granite_forecast` — paid MCP tool: time-series forecasting via IBM Granite TTM.+//+// Price: $0.05 USDC (exact, Solana). Uses IBM Granite Time Series (TTM) for+// zero-shot forecasting of numeric series — revenue, traffic, sensor readings,+// stock prices, energy consumption — without model training.++import { z } from 'zod';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';+import { WatsonxError } from '../watsonx.js';++const TOOL_NAME = 'ibm_granite_forecast';+const TOOL_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 inputZodShape = {+ timestamps: z+ .array(z.string().min(1))+ .min(64)+ .max(1024)+ .describe(+ 'ISO-8601 timestamps at a uniform cadence, oldest to newest (e.g. ["2025-01-01T00:00:00Z", ...]).',+ ),+ values: z+ .array(z.number())+ .min(64)+ .max(1024)+ .describe(+ 'Numeric series aligned to timestamps, oldest to newest. Must be the same length as timestamps.',+ ),+ freq: z+ .string()+ .min(1)+ .describe(+ `Cadence of the series as a pandas-style frequency string. Examples: ${FREQ_EXAMPLES}.`,+ ),+ prediction_length: z+ .number()+ .int()+ .min(1)+ .max(96)+ .optional()+ .describe(+ 'Number of steps to forecast ahead. Defaults to the model horizon (typically 96 for 1h data).',+ ),+ label: z+ .string()+ .max(64)+ .optional()+ .describe('Human label for the series (e.g. "daily_revenue_usd"). Returned in output for traceability.'),+};++const inputJsonSchema = jsonSchemaFromZod(inputZodShape);++export async function buildGraniteForecastTool(client) {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ priceUsd: '$0.05',+ inputSchema: inputJsonSchema,+ example: {+ timestamps: ['2025-01-01T00:00:00Z', '2025-01-02T00:00:00Z'],+ values: [1200, 1350],+ freq: '1D',+ prediction_length: 7,+ label: 'daily_revenue_usd',+ },+ outputExample: {+ 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 },+ { timestamp: '2025-06-08T00:00:00Z', value: 1388 },+ ],+ },+ },+ async ({ timestamps, values, freq, prediction_length, label }) => {+ if (timestamps.length !== values.length) {+ return toolError(+ 'invalid_input',+ `timestamps and values must have equal length (got ${timestamps.length} timestamps, ${values.length} values).`,+ );+ }+ try {+ const result = await client.forecast({+ timestamps,+ values,+ freq,+ predictionLength: prediction_length,+ });++ const forecast = result.timestamps.map((ts, i) => ({+ timestamp: ts,+ value: result.values[i] ?? null,+ }));++ return {+ ok: true,+ ...(label ? { label } : {}),+ model: result.model,+ inputWindow: result.inputWindow,+ forecastSteps: forecast.length,+ forecast,+ };+ } catch (err) {+ if (err instanceof WatsonxError) {+ return toolError('watsonx_error', err.message, { status: err.status });+ }+ return toolError('internal_error', err.message);+ }+ },+ );++ return {+ name: TOOL_NAME,+ title: 'IBM Granite Forecast ($0.05)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/packages/ibm-x402-mcp/src/watsonx.js b/packages/ibm-x402-mcp/src/watsonx.jsnew file mode 100644index 000000000..c8280b927--- /dev/null+++ b/packages/ibm-x402-mcp/src/watsonx.js@@ -0,0 +1,265 @@+// IBM watsonx.ai REST client (server-side credentials).+//+// In ibm-x402-mcp the server operator supplies WATSONX_* env vars; end users+// pay USDC and receive results without needing their own IBM Cloud account.+// The client is a thin, dependency-free wrapper over the watsonx.ai REST API:+// IAM token minting from an API key, in-process caching with proactive refresh,+// and typed methods for every inference surface we expose as paid tools.++const IAM_TOKEN_URL = 'https://iam.cloud.ibm.com/identity/token';+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;+ }+}++export function loadConfig(env = process.env) {+ const apiKey = env.WATSONX_API_KEY?.trim();+ if (!apiKey) {+ throw new WatsonxError(+ 'WATSONX_API_KEY is not set. IBM Cloud API key required — create one at https://cloud.ibm.com/iam/apikeys.',+ );+ }+ 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 it under watsonx.ai project → Manage → General → Project ID.',+ );+ }+ return {+ apiKey,+ projectId,+ spaceId,+ 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',+ tsApiVersion: env.WATSONX_TS_API_VERSION?.trim() || '2025-02-11',+ chatModel: env.WATSONX_MODEL_ID?.trim() || 'ibm/granite-3-8b-instruct',+ codeModel: env.WATSONX_CODE_MODEL_ID?.trim() || 'ibm/granite-3-8b-instruct',+ embedModel: env.WATSONX_EMBED_MODEL_ID?.trim() || 'ibm/granite-embedding-278m-multilingual',+ forecastModel: env.WATSONX_FORECAST_MODEL?.trim() || 'ibm/granite-ttm-512-96-r2',+ timeoutMs: Number(env.WATSONX_TIMEOUT_MS) || 90_000,+ };+}++export class WatsonxClient {+ constructor(config) {+ this.config = config;+ this._token = null;+ this._tokenPromise = null;+ }++ _scope() {+ return this.config.projectId+ ? { project_id: this.config.projectId }+ : { space_id: this.config.spaceId };+ }++ 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;+ }+ }++ 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 };+ }+ }++ async _post(path, payload, version) {+ const token = await this._getToken();+ const url = `${this.config.url}${path}?version=${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,+ });+ }++ 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,+ };+ }++ async generate(input, { model, parameters } = {}) {+ const data = await this._post('/ml/v1/text/generation', {+ model_id: model || this.config.codeModel,+ 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.codeModel,+ };+ }++ 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,+ };+ }++ async forecast({ timestamps, values, freq, model, targetColumn = 'value', predictionLength } = {}) {+ if (+ !Array.isArray(timestamps) ||+ !Array.isArray(values) ||+ timestamps.length !== values.length ||+ values.length === 0+ ) {+ throw new WatsonxError(+ 'forecast: timestamps and values must be equal-length, non-empty arrays.',+ );+ }+ const data = await this._post(+ '/ml/v1/time_series/forecast',+ {+ model_id: model || this.config.forecastModel,+ schema: { timestamp_column: 'date', freq, target_columns: [targetColumn] },+ data: { date: timestamps, [targetColumn]: values },+ ...(predictionLength ? { parameters: { prediction_length: predictionLength } } : {}),+ },+ this.config.tsApiVersion,+ );+ const r = data.results?.[0] || {};+ return {+ model: data.model_id || model || this.config.forecastModel,+ timestamps: r.date || [],+ values: r[targetColumn] || [],+ inputWindow: values.length,+ };+ }++ 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,+ };+ }++ 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,+ }));+ }+}