@blockrun/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,337 @@
1
+ # @blockrun/mcp
2
+
3
+ **Access 30+ AI models in Claude Code with zero API keys.**
4
+
5
+ One wallet. Pay-per-request. All major AI models.
6
+
7
+ ```bash
8
+ claude mcp add blockrun npx @blockrun/mcp
9
+ ```
10
+
11
+ ## Why BlockRun MCP?
12
+
13
+ | Feature | Other Solutions | BlockRun MCP |
14
+ |---------|-----------------|--------------|
15
+ | **API Keys** | Need 5+ keys (OpenAI, Anthropic, Google...) | **None needed** |
16
+ | **Billing** | Manage 5+ subscriptions | **One wallet, unified balance** |
17
+ | **Setup** | Complex config per provider | **One command, auto-wallet** |
18
+ | **Models** | Usually 1 provider | **30+ models, 6 providers** |
19
+ | **Payment** | Monthly subscriptions | **Pay only what you use** |
20
+ | **Minimum** | $20-100/month per provider | **$0 minimum, start with $5** |
21
+
22
+ ## Quick Start
23
+
24
+ ### 1. Install (30 seconds)
25
+
26
+ ```bash
27
+ # Add to Claude Code
28
+ claude mcp add blockrun npx @blockrun/mcp
29
+ ```
30
+
31
+ That's it! A wallet is automatically created for you.
32
+
33
+ ### 2. Get Your Wallet Address
34
+
35
+ In Claude Code, run:
36
+ ```
37
+ Use blockrun_setup to get my wallet address
38
+ ```
39
+
40
+ Or:
41
+ ```
42
+ Use blockrun_wallet to show my wallet info
43
+ ```
44
+
45
+ ### 3. Fund Your Wallet
46
+
47
+ Send USDC to your wallet address on **Base** network. Even $5 gets you hundreds of requests.
48
+
49
+ **Funding Options:**
50
+
51
+ | Method | Steps |
52
+ |--------|-------|
53
+ | **From Coinbase** | Send → USDC → Select "Base" network → Paste your address |
54
+ | **Bridge** | Visit [bridge.base.org](https://bridge.base.org) → Bridge USDC to Base |
55
+ | **Buy Direct** | Visit [Coinbase Onramp](https://www.coinbase.com/onramp) → Buy USDC on Base |
56
+
57
+ ### 4. Start Using
58
+
59
+ ```
60
+ You: Use blockrun_chat to ask claude-sonnet-4 what is quantum computing
61
+
62
+ Claude: [calls blockrun_chat]
63
+ Quantum computing is a type of computation that harnesses...
64
+ ```
65
+
66
+ ## Available Tools
67
+
68
+ ### `blockrun_chat`
69
+ Chat with any AI model.
70
+
71
+ ```javascript
72
+ blockrun_chat({
73
+ model: "anthropic/claude-sonnet-4", // Required
74
+ message: "Explain quantum computing", // Required
75
+ system: "You are a physics professor", // Optional
76
+ max_tokens: 2000, // Optional (default: 1024)
77
+ temperature: 0.7 // Optional (default: 1)
78
+ })
79
+ ```
80
+
81
+ **Popular Models:**
82
+ - `openai/gpt-5.2` - Most capable OpenAI model
83
+ - `anthropic/claude-opus-4` - Best for complex reasoning
84
+ - `anthropic/claude-sonnet-4` - Fast & capable (recommended)
85
+ - `google/gemini-2.5-pro` - Great for long context (1M tokens)
86
+ - `deepseek/deepseek-chat` - Very affordable
87
+
88
+ ### `blockrun_smart`
89
+ Auto-select the best model for your needs.
90
+
91
+ ```javascript
92
+ blockrun_smart({
93
+ mode: "balanced", // Required: fast | balanced | powerful | cheap | reasoning
94
+ message: "Hello!" // Required
95
+ })
96
+ ```
97
+
98
+ | Mode | Models Used | Best For | Cost |
99
+ |------|-------------|----------|------|
100
+ | `fast` | Gemini Flash, GPT-4o-mini | Quick responses | $ |
101
+ | `balanced` | GPT-4o, Claude Sonnet | Daily tasks | $$ |
102
+ | `powerful` | GPT-5.2, Claude Opus, o3 | Complex work | $$$$ |
103
+ | `cheap` | Gemini Flash, DeepSeek | Budget-conscious | $ |
104
+ | `reasoning` | o3, o1, DeepSeek Reasoner | Logic & math | $$$ |
105
+
106
+ ### `blockrun_models`
107
+ List all available models with pricing.
108
+
109
+ ```javascript
110
+ blockrun_models({
111
+ category: "chat", // Optional: all, chat, reasoning, image, embedding
112
+ provider: "openai" // Optional: filter by provider
113
+ })
114
+ ```
115
+
116
+ ### `blockrun_image`
117
+ Generate images with AI.
118
+
119
+ ```javascript
120
+ blockrun_image({
121
+ prompt: "A sunset over mountains", // Required
122
+ model: "openai/dall-e-3", // Optional
123
+ size: "1024x1024", // Optional: 1024x1024, 1792x1024, 1024x1792
124
+ quality: "hd" // Optional: standard, hd
125
+ })
126
+ ```
127
+
128
+ ### `blockrun_wallet`
129
+ Check your wallet information.
130
+
131
+ ```javascript
132
+ blockrun_wallet({})
133
+ // Returns: address, network, balance link, funding options
134
+ ```
135
+
136
+ ### `blockrun_setup`
137
+ Get detailed setup and funding instructions.
138
+
139
+ ```javascript
140
+ blockrun_setup({})
141
+ // Returns: complete setup guide with step-by-step funding instructions
142
+ ```
143
+
144
+ ## Supported Models & Pricing
145
+
146
+ ### Chat Models
147
+
148
+ | Provider | Models | Input Price | Output Price |
149
+ |----------|--------|-------------|--------------|
150
+ | **OpenAI** | GPT-5.2, GPT-5-mini, GPT-4o, o3, o1 | $0.15 - $21/M | $0.60 - $84/M |
151
+ | **Anthropic** | Claude Opus 4, Sonnet 4, Haiku | $0.25 - $15/M | $1.25 - $75/M |
152
+ | **Google** | Gemini 3 Pro, 2.5 Pro/Flash | Free - $2.50/M | Free - $15/M |
153
+ | **DeepSeek** | V3.2, Reasoner | $0.14 - $0.55/M | $0.28 - $2.19/M |
154
+ | **xAI** | Grok 3, Grok 3 Mini | $3 - $5/M | $15 - $25/M |
155
+
156
+ *M = million tokens. Prices in USD.*
157
+
158
+ ### Image Models
159
+
160
+ | Model | Price per Image |
161
+ |-------|-----------------|
162
+ | DALL-E 3 (Standard) | $0.04 |
163
+ | DALL-E 3 (HD) | $0.08 |
164
+ | Flux Schnell | $0.02 |
165
+
166
+ ### Cost Examples
167
+
168
+ | Task | Model | Approx. Cost |
169
+ |------|-------|--------------|
170
+ | Quick question | Gemini Flash | $0.0001 |
171
+ | Code review | Claude Sonnet | $0.003 |
172
+ | Complex analysis | GPT-4o | $0.005 |
173
+ | Long document | Claude Opus | $0.02 |
174
+ | Image generation | DALL-E 3 | $0.04 |
175
+
176
+ **$5 gets you approximately:**
177
+ - 50,000 Gemini Flash requests, OR
178
+ - 1,600 Claude Sonnet requests, OR
179
+ - 1,000 GPT-4o requests, OR
180
+ - 125 DALL-E 3 images
181
+
182
+ ## Wallet Management
183
+
184
+ ### Auto-Generated Wallet
185
+
186
+ When you first use BlockRun MCP, a wallet is automatically created and saved to:
187
+ ```
188
+ ~/.blockrun/.session
189
+ ```
190
+
191
+ This wallet is:
192
+ - Created locally on your machine
193
+ - Never transmitted to any server
194
+ - Used only for signing payment authorizations
195
+ - Persistent across sessions
196
+
197
+ ### Using Your Own Wallet
198
+
199
+ If you prefer to use an existing wallet:
200
+
201
+ ```bash
202
+ # Option 1: Environment variable
203
+ export BLOCKRUN_WALLET_KEY=0x...
204
+
205
+ # Option 2: Add with Claude Code
206
+ claude mcp add blockrun npx @blockrun/mcp --env BLOCKRUN_WALLET_KEY=0x...
207
+ ```
208
+
209
+ ### Wallet Priority
210
+
211
+ 1. Environment variable `BLOCKRUN_WALLET_KEY`
212
+ 2. Environment variable `BASE_CHAIN_WALLET_KEY`
213
+ 3. File at `~/.blockrun/.session`
214
+ 4. Auto-generate new wallet (saved to file)
215
+
216
+ ## How Payment Works
217
+
218
+ ```
219
+ ┌─────────────────────────────────────────────────────────────┐
220
+ │ 1. You send a request (e.g., chat with GPT-5) │
221
+ │ ↓ │
222
+ │ 2. BlockRun calculates cost based on tokens │
223
+ │ ↓ │
224
+ │ 3. Your wallet signs a payment authorization LOCALLY │
225
+ │ (private key NEVER leaves your machine) │
226
+ │ ↓ │
227
+ │ 4. Payment settles on Base network via USDC │
228
+ │ ↓ │
229
+ │ 5. You receive your AI response │
230
+ └─────────────────────────────────────────────────────────────┘
231
+ ```
232
+
233
+ **Security Guarantees:**
234
+ - Private key is used ONLY for local signing
235
+ - Key is NEVER transmitted to any server
236
+ - Same security model as MetaMask transactions
237
+ - You can verify all transactions on [Basescan](https://basescan.org)
238
+
239
+ ## Comparison with Alternatives
240
+
241
+ ### vs claude-code-proxy
242
+ | | claude-code-proxy | BlockRun MCP |
243
+ |---|---|---|
244
+ | API Keys | Required (bring your own) | **Not needed** |
245
+ | Setup | Configure each provider | **One command** |
246
+ | Billing | Multiple subscriptions | **Unified wallet** |
247
+
248
+ ### vs gemini-mcp
249
+ | | gemini-mcp | BlockRun MCP |
250
+ |---|---|---|
251
+ | Models | Gemini only | **30+ models, 6 providers** |
252
+ | API Key | Required | **Not needed** |
253
+ | Payment | Google billing | **Pay-per-use crypto** |
254
+
255
+ ### vs Direct API Keys
256
+ | | Direct APIs | BlockRun MCP |
257
+ |---|---|---|
258
+ | Accounts | 5+ accounts needed | **One wallet** |
259
+ | Minimums | $20-100/mo per provider | **$0 minimum** |
260
+ | Management | Complex | **Simple** |
261
+
262
+ ## Troubleshooting
263
+
264
+ ### "Payment was rejected"
265
+ Your wallet needs funding. Run `blockrun_setup` to get your address and funding instructions.
266
+
267
+ ### "Wallet key required"
268
+ The MCP couldn't find or create a wallet. Check that `~/.blockrun/` directory is writable.
269
+
270
+ ### Model not responding
271
+ Some models have rate limits. Try `blockrun_smart` with mode `fast` or `cheap` to use alternative models.
272
+
273
+ ### Check wallet balance
274
+ Visit: `https://basescan.org/address/YOUR_ADDRESS`
275
+
276
+ ## Configuration
277
+
278
+ ### Claude Code Setup
279
+
280
+ ```bash
281
+ # Basic (recommended)
282
+ claude mcp add blockrun npx @blockrun/mcp
283
+
284
+ # With explicit wallet
285
+ claude mcp add blockrun npx @blockrun/mcp --env BLOCKRUN_WALLET_KEY=0x...
286
+
287
+ # Project-specific
288
+ claude mcp add blockrun --scope project npx @blockrun/mcp
289
+
290
+ # User-wide (all projects)
291
+ claude mcp add blockrun --scope user npx @blockrun/mcp
292
+ ```
293
+
294
+ ### Environment Variables
295
+
296
+ | Variable | Description |
297
+ |----------|-------------|
298
+ | `BLOCKRUN_WALLET_KEY` | Your wallet private key (hex, starts with 0x) |
299
+ | `BASE_CHAIN_WALLET_KEY` | Alternative name for wallet key |
300
+
301
+ ## Development
302
+
303
+ ```bash
304
+ # Clone
305
+ git clone https://github.com/blockrunai/blockrun-mcp
306
+ cd blockrun-mcp
307
+
308
+ # Install dependencies
309
+ npm install
310
+
311
+ # Development mode (auto-reload)
312
+ npm run dev
313
+
314
+ # Build for production
315
+ npm run build
316
+
317
+ # Test locally
318
+ echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | node dist/index.js
319
+ ```
320
+
321
+ ## Links
322
+
323
+ - **Website:** [blockrun.ai](https://blockrun.ai)
324
+ - **Documentation:** [docs.blockrun.ai](https://docs.blockrun.ai)
325
+ - **Pricing:** [blockrun.ai/pricing](https://blockrun.ai/pricing)
326
+ - **GitHub:** [github.com/blockrunai](https://github.com/blockrunai)
327
+ - **Twitter:** [@blockaborama](https://twitter.com/blockaborama)
328
+
329
+ ## Support
330
+
331
+ - **Issues:** [GitHub Issues](https://github.com/blockrunai/blockrun-mcp/issues)
332
+ - **Discord:** [Join our Discord](https://discord.gg/blockrun)
333
+ - **Email:** hello@blockrun.ai
334
+
335
+ ## License
336
+
337
+ MIT
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/index.js ADDED
@@ -0,0 +1,485 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import {
7
+ CallToolRequestSchema,
8
+ ListToolsRequestSchema
9
+ } from "@modelcontextprotocol/sdk/types.js";
10
+ import { LLMClient } from "@blockrun/llm";
11
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
12
+ import * as fs from "fs";
13
+ import * as path from "path";
14
+ import * as os from "os";
15
+ var WALLET_DIR = path.join(os.homedir(), ".blockrun");
16
+ var WALLET_FILE = path.join(WALLET_DIR, ".session");
17
+ var MODEL_TIERS = {
18
+ fast: ["google/gemini-2.5-flash", "openai/gpt-4o-mini", "deepseek/deepseek-chat"],
19
+ balanced: ["openai/gpt-4o", "anthropic/claude-sonnet-4", "google/gemini-2.5-pro"],
20
+ powerful: ["openai/gpt-5.2", "anthropic/claude-opus-4", "openai/o3"],
21
+ cheap: ["google/gemini-2.5-flash", "deepseek/deepseek-chat", "openai/gpt-4o-mini"],
22
+ reasoning: ["openai/o3", "openai/o1", "deepseek/deepseek-reasoner"]
23
+ };
24
+ var walletWasCreated = false;
25
+ var walletAddress = null;
26
+ var client = null;
27
+ var cachedModels = null;
28
+ function getOrCreateWalletKey() {
29
+ const envKey = process.env.BLOCKRUN_WALLET_KEY || process.env.BASE_CHAIN_WALLET_KEY;
30
+ if (envKey) {
31
+ const account2 = privateKeyToAccount(envKey);
32
+ walletAddress = account2.address;
33
+ return envKey;
34
+ }
35
+ if (fs.existsSync(WALLET_FILE)) {
36
+ try {
37
+ const savedKey = fs.readFileSync(WALLET_FILE, "utf-8").trim();
38
+ if (savedKey.startsWith("0x") && savedKey.length === 66) {
39
+ const account2 = privateKeyToAccount(savedKey);
40
+ walletAddress = account2.address;
41
+ return savedKey;
42
+ }
43
+ } catch {
44
+ }
45
+ }
46
+ const newKey = generatePrivateKey();
47
+ const account = privateKeyToAccount(newKey);
48
+ walletAddress = account.address;
49
+ walletWasCreated = true;
50
+ try {
51
+ if (!fs.existsSync(WALLET_DIR)) {
52
+ fs.mkdirSync(WALLET_DIR, { recursive: true, mode: 448 });
53
+ }
54
+ fs.writeFileSync(WALLET_FILE, newKey, { mode: 384 });
55
+ console.error(`[BlockRun] New wallet created and saved to ${WALLET_FILE}`);
56
+ } catch (err) {
57
+ console.error(`[BlockRun] Warning: Could not save wallet to file: ${err}`);
58
+ }
59
+ return newKey;
60
+ }
61
+ function getClient() {
62
+ if (!client) {
63
+ const privateKey = getOrCreateWalletKey();
64
+ client = new LLMClient({ privateKey });
65
+ }
66
+ return client;
67
+ }
68
+ function getWalletSetupInstructions() {
69
+ if (!walletAddress) {
70
+ getClient();
71
+ }
72
+ return `
73
+ ================================================================================
74
+ BLOCKRUN WALLET SETUP
75
+ ================================================================================
76
+
77
+ Your wallet address: ${walletAddress}
78
+
79
+ To use BlockRun AI models, you need USDC on Base network.
80
+
81
+ HOW TO FUND YOUR WALLET:
82
+ ------------------------
83
+
84
+ Option 1: Transfer from Coinbase
85
+ 1. Open Coinbase app or website
86
+ 2. Go to Send/Receive
87
+ 3. Select USDC
88
+ 4. Choose "Base" network (important!)
89
+ 5. Paste address: ${walletAddress}
90
+ 6. Send any amount ($5 is enough to start)
91
+
92
+ Option 2: Bridge from other chains
93
+ 1. Go to https://bridge.base.org
94
+ 2. Connect your existing wallet
95
+ 3. Bridge USDC to Base
96
+ 4. Send to: ${walletAddress}
97
+
98
+ Option 3: Buy directly
99
+ 1. Go to https://www.coinbase.com/onramp
100
+ 2. Buy USDC on Base network
101
+ 3. Send to: ${walletAddress}
102
+
103
+ VERIFY YOUR BALANCE:
104
+ https://basescan.org/address/${walletAddress}
105
+
106
+ PRICING (pay only for what you use):
107
+ - GPT-4o: ~$0.005 per request
108
+ - Claude Sonnet: ~$0.003 per request
109
+ - Gemini Flash: ~$0.0001 per request
110
+ - Full pricing: https://blockrun.ai/pricing
111
+
112
+ SECURITY NOTE:
113
+ Your private key is stored at: ~/.blockrun/.session
114
+ This key NEVER leaves your machine - only used for signing payments locally.
115
+
116
+ ================================================================================
117
+ `;
118
+ }
119
+ var tools = [
120
+ {
121
+ name: "blockrun_chat",
122
+ description: `Chat with any AI model via BlockRun. Supports 30+ models including GPT-5, Claude Opus 4, Gemini 3, and more.
123
+ Pay-per-request with x402 micropayments - no API keys needed.
124
+
125
+ Popular models:
126
+ - openai/gpt-5.2: Most capable OpenAI model
127
+ - anthropic/claude-opus-4: Best for complex reasoning
128
+ - anthropic/claude-sonnet-4: Fast & capable (recommended)
129
+ - google/gemini-2.5-pro: Great for long context
130
+ - deepseek/deepseek-chat: Very affordable
131
+
132
+ Use blockrun_models to see all available models with pricing.`,
133
+ inputSchema: {
134
+ type: "object",
135
+ properties: {
136
+ model: {
137
+ type: "string",
138
+ description: "Model ID (e.g., 'anthropic/claude-sonnet-4', 'openai/gpt-4o'). Use blockrun_models to list all."
139
+ },
140
+ message: {
141
+ type: "string",
142
+ description: "Your message to the AI"
143
+ },
144
+ system: {
145
+ type: "string",
146
+ description: "Optional system prompt to set context/behavior"
147
+ },
148
+ max_tokens: {
149
+ type: "number",
150
+ description: "Maximum tokens in response (default: 1024)"
151
+ },
152
+ temperature: {
153
+ type: "number",
154
+ description: "Creativity level 0-2 (default: 1)"
155
+ }
156
+ },
157
+ required: ["model", "message"]
158
+ }
159
+ },
160
+ {
161
+ name: "blockrun_smart",
162
+ description: `Smart model routing - automatically picks the best model based on your needs.
163
+
164
+ Modes:
165
+ - fast: Quickest response (Gemini Flash, GPT-4o-mini)
166
+ - balanced: Good quality & speed (GPT-4o, Claude Sonnet)
167
+ - powerful: Best quality (GPT-5.2, Claude Opus 4, o3)
168
+ - cheap: Lowest cost (Gemini Flash, DeepSeek)
169
+ - reasoning: Complex logic (o3, o1, DeepSeek Reasoner)
170
+
171
+ Example: blockrun_smart({ mode: "fast", message: "Hello" })`,
172
+ inputSchema: {
173
+ type: "object",
174
+ properties: {
175
+ mode: {
176
+ type: "string",
177
+ enum: ["fast", "balanced", "powerful", "cheap", "reasoning"],
178
+ description: "Routing mode: fast, balanced, powerful, cheap, or reasoning"
179
+ },
180
+ message: {
181
+ type: "string",
182
+ description: "Your message to the AI"
183
+ },
184
+ system: {
185
+ type: "string",
186
+ description: "Optional system prompt"
187
+ },
188
+ max_tokens: {
189
+ type: "number",
190
+ description: "Maximum tokens in response (default: 1024)"
191
+ }
192
+ },
193
+ required: ["mode", "message"]
194
+ }
195
+ },
196
+ {
197
+ name: "blockrun_models",
198
+ description: "List all available AI models with pricing. Use this to discover models and compare costs.",
199
+ inputSchema: {
200
+ type: "object",
201
+ properties: {
202
+ category: {
203
+ type: "string",
204
+ enum: ["all", "chat", "reasoning", "image", "embedding"],
205
+ description: "Filter by category (default: all)"
206
+ },
207
+ provider: {
208
+ type: "string",
209
+ description: "Filter by provider (e.g., 'openai', 'anthropic', 'google')"
210
+ }
211
+ }
212
+ }
213
+ },
214
+ {
215
+ name: "blockrun_image",
216
+ description: `Generate images using AI models. Supports DALL-E 3, Flux, and Nano Banana.
217
+
218
+ Models:
219
+ - openai/dall-e-3: High quality, creative ($0.04-0.08/image)
220
+ - together/flux-schnell: Fast generation ($0.02/image)
221
+ - google/nano-banana: Experimental Google model`,
222
+ inputSchema: {
223
+ type: "object",
224
+ properties: {
225
+ prompt: {
226
+ type: "string",
227
+ description: "Description of the image to generate"
228
+ },
229
+ model: {
230
+ type: "string",
231
+ description: "Image model (default: openai/dall-e-3)",
232
+ enum: ["openai/dall-e-3", "together/flux-schnell", "google/nano-banana"]
233
+ },
234
+ size: {
235
+ type: "string",
236
+ description: "Image size (default: 1024x1024)",
237
+ enum: ["1024x1024", "1792x1024", "1024x1792"]
238
+ },
239
+ quality: {
240
+ type: "string",
241
+ description: "Quality level for DALL-E 3 (default: standard)",
242
+ enum: ["standard", "hd"]
243
+ }
244
+ },
245
+ required: ["prompt"]
246
+ }
247
+ },
248
+ {
249
+ name: "blockrun_wallet",
250
+ description: "Get information about your BlockRun wallet address. Shows address, network, and quick funding options.",
251
+ inputSchema: {
252
+ type: "object",
253
+ properties: {}
254
+ }
255
+ },
256
+ {
257
+ name: "blockrun_setup",
258
+ description: `Get detailed wallet setup and funding instructions. Use this for first-time setup or if you need help adding funds to your wallet.
259
+
260
+ Returns:
261
+ - Your wallet address
262
+ - Step-by-step funding instructions (Coinbase, bridge, direct purchase)
263
+ - Pricing information
264
+ - Security details`,
265
+ inputSchema: {
266
+ type: "object",
267
+ properties: {}
268
+ }
269
+ }
270
+ ];
271
+ async function handleChat(args) {
272
+ const llm = getClient();
273
+ const response = await llm.chat(args.model, args.message, {
274
+ system: args.system,
275
+ maxTokens: args.max_tokens,
276
+ temperature: args.temperature
277
+ });
278
+ return response;
279
+ }
280
+ async function handleSmartRoute(args) {
281
+ const models = MODEL_TIERS[args.mode];
282
+ if (!models) {
283
+ throw new Error(`Invalid mode: ${args.mode}. Use: fast, balanced, powerful, cheap, or reasoning`);
284
+ }
285
+ let lastError = null;
286
+ for (const model of models) {
287
+ try {
288
+ const response = await handleChat({
289
+ model,
290
+ message: args.message,
291
+ system: args.system,
292
+ max_tokens: args.max_tokens
293
+ });
294
+ return `[Used: ${model}]
295
+
296
+ ${response}`;
297
+ } catch (error) {
298
+ lastError = error;
299
+ continue;
300
+ }
301
+ }
302
+ throw lastError || new Error("All models failed");
303
+ }
304
+ async function handleListModels(args) {
305
+ const llm = getClient();
306
+ if (!cachedModels) {
307
+ cachedModels = await llm.listModels();
308
+ setTimeout(() => {
309
+ cachedModels = null;
310
+ }, 5 * 60 * 1e3);
311
+ }
312
+ let models = cachedModels;
313
+ if (args.provider) {
314
+ const provider = args.provider.toLowerCase();
315
+ models = models.filter((m) => m.id.toLowerCase().startsWith(provider + "/"));
316
+ }
317
+ if (args.category && args.category !== "all") {
318
+ const category = args.category.toLowerCase();
319
+ if (category === "image") {
320
+ models = models.filter(
321
+ (m) => m.id.includes("dall-e") || m.id.includes("flux") || m.id.includes("banana")
322
+ );
323
+ } else if (category === "reasoning") {
324
+ models = models.filter(
325
+ (m) => m.id.includes("/o1") || m.id.includes("/o3") || m.id.includes("reasoner")
326
+ );
327
+ } else if (category === "embedding") {
328
+ models = models.filter((m) => m.id.includes("embed"));
329
+ }
330
+ }
331
+ const lines = models.map((m) => {
332
+ const input = m.inputPrice ? `$${m.inputPrice}/M in` : "";
333
+ const output = m.outputPrice ? `$${m.outputPrice}/M out` : "";
334
+ const pricing = [input, output].filter(Boolean).join(", ");
335
+ return `- ${m.id}: ${m.name || ""} ${pricing ? `(${pricing})` : ""}`;
336
+ });
337
+ return `Available models (${models.length}):
338
+
339
+ ${lines.join("\n")}`;
340
+ }
341
+ async function handleImageGeneration(args) {
342
+ const model = args.model || "openai/dall-e-3";
343
+ const llm = getClient();
344
+ const apiUrl = "https://blockrun.ai/api/v1/images/generations";
345
+ const body = {
346
+ model,
347
+ prompt: args.prompt,
348
+ size: args.size || "1024x1024",
349
+ quality: args.quality || "standard",
350
+ n: 1
351
+ };
352
+ const response = await fetch(apiUrl, {
353
+ method: "POST",
354
+ headers: {
355
+ "Content-Type": "application/json"
356
+ },
357
+ body: JSON.stringify(body)
358
+ });
359
+ if (response.status === 402) {
360
+ return `Image generation requires payment. Please ensure your wallet has USDC on Base.
361
+
362
+ To generate "${args.prompt}" with ${model}, the approximate cost is $0.04-0.08 per image.`;
363
+ }
364
+ if (!response.ok) {
365
+ throw new Error(`Image generation failed: ${response.status}`);
366
+ }
367
+ const data = await response.json();
368
+ const imageUrl = data.data?.[0]?.url;
369
+ if (!imageUrl) {
370
+ throw new Error("No image URL in response");
371
+ }
372
+ return `Image generated successfully!
373
+
374
+ URL: ${imageUrl}
375
+
376
+ Prompt: ${args.prompt}
377
+ Model: ${model}`;
378
+ }
379
+ function handleWalletInfo() {
380
+ const llm = getClient();
381
+ const address = llm.getWalletAddress();
382
+ const isNewWallet = walletWasCreated;
383
+ let response = `BlockRun Wallet Information
384
+ ============================
385
+
386
+ Address: ${address}
387
+ Network: Base (Chain ID: 8453)
388
+ Currency: USDC
389
+
390
+ View on Basescan: https://basescan.org/address/${address}
391
+ `;
392
+ if (isNewWallet) {
393
+ response += `
394
+ STATUS: NEW WALLET - NEEDS FUNDING
395
+ ${getWalletSetupInstructions()}`;
396
+ } else {
397
+ response += `
398
+ HOW TO ADD FUNDS:
399
+ -----------------
400
+ Send USDC to the address above on Base network.
401
+
402
+ Quick options:
403
+ 1. From Coinbase: Send USDC, select "Base" network
404
+ 2. Bridge: https://bridge.base.org
405
+ 3. Buy: https://www.coinbase.com/onramp
406
+
407
+ Full instructions: Run blockrun_setup tool
408
+ `;
409
+ }
410
+ return response;
411
+ }
412
+ function handleSetup() {
413
+ getClient();
414
+ return getWalletSetupInstructions();
415
+ }
416
+ var server = new Server(
417
+ {
418
+ name: "blockrun-mcp",
419
+ version: "0.1.0"
420
+ },
421
+ {
422
+ capabilities: {
423
+ tools: {}
424
+ }
425
+ }
426
+ );
427
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
428
+ tools
429
+ }));
430
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
431
+ const { name, arguments: args } = request.params;
432
+ try {
433
+ let result;
434
+ switch (name) {
435
+ case "blockrun_chat":
436
+ result = await handleChat(args);
437
+ break;
438
+ case "blockrun_smart":
439
+ result = await handleSmartRoute(args);
440
+ break;
441
+ case "blockrun_models":
442
+ result = await handleListModels(args);
443
+ break;
444
+ case "blockrun_image":
445
+ result = await handleImageGeneration(args);
446
+ break;
447
+ case "blockrun_wallet":
448
+ result = handleWalletInfo();
449
+ break;
450
+ case "blockrun_setup":
451
+ result = handleSetup();
452
+ break;
453
+ default:
454
+ throw new Error(`Unknown tool: ${name}`);
455
+ }
456
+ return {
457
+ content: [{ type: "text", text: result }]
458
+ };
459
+ } catch (error) {
460
+ const message = error instanceof Error ? error.message : String(error);
461
+ const isPaymentError = message.toLowerCase().includes("payment") || message.toLowerCase().includes("402") || message.toLowerCase().includes("balance") || message.toLowerCase().includes("insufficient");
462
+ let errorText = `Error: ${message}`;
463
+ if (isPaymentError) {
464
+ errorText += `
465
+
466
+ This error usually means your wallet needs funding.
467
+ Run the blockrun_setup tool to get your wallet address and funding instructions.
468
+
469
+ Quick fix: Send USDC to your wallet on Base network.`;
470
+ }
471
+ return {
472
+ content: [{ type: "text", text: errorText }],
473
+ isError: true
474
+ };
475
+ }
476
+ });
477
+ async function main() {
478
+ const transport = new StdioServerTransport();
479
+ await server.connect(transport);
480
+ console.error("BlockRun MCP Server started");
481
+ }
482
+ main().catch((error) => {
483
+ console.error("Fatal error:", error);
484
+ process.exit(1);
485
+ });
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@blockrun/mcp",
3
+ "version": "0.1.0",
4
+ "description": "BlockRun MCP Server - Access 30+ AI models via x402 micropayments. No API keys needed.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "bin": {
9
+ "blockrun-mcp": "./dist/index.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsup src/index.ts --format esm --dts --clean",
17
+ "dev": "tsx watch src/index.ts",
18
+ "start": "node dist/index.js",
19
+ "typecheck": "tsc --noEmit",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "keywords": [
23
+ "mcp",
24
+ "claude",
25
+ "llm",
26
+ "ai",
27
+ "x402",
28
+ "micropayments",
29
+ "openai",
30
+ "anthropic",
31
+ "gemini",
32
+ "blockrun",
33
+ "model-context-protocol"
34
+ ],
35
+ "author": "BlockRun <hello@blockrun.ai>",
36
+ "license": "MIT",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/blockrunai/blockrun-mcp"
40
+ },
41
+ "homepage": "https://blockrun.ai",
42
+ "bugs": {
43
+ "url": "https://github.com/blockrunai/blockrun-mcp/issues"
44
+ },
45
+ "dependencies": {
46
+ "@modelcontextprotocol/sdk": "^1.0.0",
47
+ "@blockrun/llm": "^0.1.1",
48
+ "viem": "^2.21.0"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^20.0.0",
52
+ "tsup": "^8.0.0",
53
+ "tsx": "^4.0.0",
54
+ "typescript": "^5.0.0"
55
+ },
56
+ "engines": {
57
+ "node": ">=18"
58
+ }
59
+ }