-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
213 lines (203 loc) · 9.06 KB
/
Copy pathserver.js
File metadata and controls
213 lines (203 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env node
// BSV Inference — remote MCP server (zero dependencies).
//
// A thin Model-Context-Protocol client for the HOSTED broker at
// inference.bsvkey.com. Any MCP-capable agent host (Claude Code, Claude Desktop,
// Codex, OpenCode, custom agents) adds this one command and can then buy Claude
// or Grok inference metered PER TOKEN, settled in BSV — every call is billed
// through the hosted gateway, so usage flows to the operator's wallet.
//
// This is NOT the broker. It never holds keys or runs models; it just talks HTTP
// to the public API. Point it at your own deployment with BSVKEY_BASE_URL.
//
// Config (environment):
// BSVKEY_BASE_URL default https://inference.bsvkey.com/v1
// BSVKEY_API_KEY "channelId:channelSecret" for a funded channel (optional —
// can also be passed per call as `apiKey`). Open + fund a
// channel once at the website, then paste the key here.
//
// Run: node server.js (Node >= 18 for global fetch)
const BASE = (process.env.BSVKEY_BASE_URL || 'https://inference.bsvkey.com/v1').replace(/\/+$/, '');
const SITE = BASE.replace(/\/v1$/, '');
const ENV_KEY = process.env.BSVKEY_API_KEY || '';
const PROTOCOL_VERSION = '2024-11-05';
const SERVER_INFO = { name: 'bsvkey-inference', version: '1.0.0' };
// Resolve a channel API key ("channelId:channelSecret") from arg or env.
function keyParts(apiKey) {
const k = String(apiKey || ENV_KEY || '').trim();
const i = k.indexOf(':');
if (i < 0) return null;
return { id: k.slice(0, i), secret: k.slice(i + 1), raw: k };
}
async function http(method, path, { headers = {}, body } = {}) {
const res = await fetch(BASE + path, {
method,
headers: { ...(body ? { 'content-type': 'application/json' } : {}), ...headers },
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json;
try { json = text ? JSON.parse(text) : {}; } catch { json = { _raw: text.slice(0, 500) }; }
return { ok: res.ok, status: res.status, json };
}
export const TOOLS = [
{
name: 'list_models',
description:
'List the models this BSV inference gateway sells, with LIVE retail price (satoshis per 1,000 tokens) at the current BSV/USD rate. No key needed. Call first to choose a model.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'infer',
description:
'Run one metered inference (OpenAI-compatible), paid per token in BSV from your prepaid channel. Returns the completion plus a receipt: satoshis charged, model routed to, and remaining balance. Requires a funded channel key (apiKey or BSVKEY_API_KEY).',
inputSchema: {
type: 'object',
properties: {
prompt: { type: 'string', description: 'The user prompt.' },
model: { type: 'string', description: 'Model id or policy: auto|cheapest|best, claude-*, grok-*.', default: 'auto' },
system: { type: 'string', description: 'Optional system prompt.' },
maxTokens: { type: 'integer', description: 'Max output tokens.', default: 512 },
webSearch: { type: 'boolean', description: 'Let the model search the live web (adds a per-search fee).', default: false },
apiKey: { type: 'string', description: 'channelId:channelSecret for a funded channel. Omit to use BSVKEY_API_KEY.' },
},
required: ['prompt'],
additionalProperties: false,
},
},
{
name: 'channel_balance',
description: 'Check a prepaid channel’s remaining BSV balance, spend, and request count.',
inputSchema: {
type: 'object',
properties: { apiKey: { type: 'string', description: 'channelId:channelSecret. Omit to use BSVKEY_API_KEY.' } },
additionalProperties: false,
},
},
{
name: 'open_channel',
description:
'Explains how to open + fund a prepaid channel. Funding is a real BSV payment signed by a wallet, so it is done once at the website; you then paste the returned channel key here (or set BSVKEY_API_KEY).',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
];
async function callTool(name, args = {}) {
switch (name) {
case 'list_models': {
const r = await http('GET', '/pricebook');
if (!r.ok) throw new Error(`pricebook ${r.status}`);
const pb = r.json;
const models = Object.entries(pb.models || {}).map(([id, m]) => ({
id,
label: m.label,
available: m.available !== false,
provider: m.provider,
retailInputSatsPer1k: m.retailInputSatsPer1k,
retailOutputSatsPer1k: m.retailOutputSatsPer1k,
}));
return { base: BASE, bsvUsd: pb.bsvUsd, rate: pb.rate, models, webSearch: pb.webSearch };
}
case 'infer': {
const k = keyParts(args.apiKey);
if (!k) throw new Error('No channel key. Pass apiKey "channelId:channelSecret" or set BSVKEY_API_KEY. Open one via the open_channel tool.');
const r = await http('POST', '/chat/completions', {
headers: { authorization: `Bearer ${k.raw}` },
body: {
model: args.model || 'auto',
messages: [
...(args.system ? [{ role: 'system', content: args.system }] : []),
{ role: 'user', content: String(args.prompt || '') },
],
max_tokens: args.maxTokens || 512,
web_search: args.webSearch === true,
},
});
if (!r.ok) {
const msg = r.json?.error?.message || r.json?.error || `inference failed (${r.status})`;
throw new Error(typeof msg === 'string' ? msg : JSON.stringify(msg));
}
const x = r.json.x_bsv || {};
return {
model: r.json.model || args.model,
completion: r.json.choices?.[0]?.message?.content ?? '',
charge: x.charge,
routedTo: x.routedTo,
balanceSatsAfter: x.balanceSatsAfter,
truncated: x.truncated || false,
};
}
case 'channel_balance': {
const k = keyParts(args.apiKey);
if (!k) throw new Error('No channel key. Pass apiKey "channelId:channelSecret" or set BSVKEY_API_KEY.');
const r = await http('GET', `/channels/${encodeURIComponent(k.id)}`, { headers: { 'x-bsv-channel-secret': k.secret } });
if (!r.ok) {
const msg = r.json?.error?.message || r.json?.error || `balance check failed (${r.status})`;
throw new Error(typeof msg === 'string' ? msg : JSON.stringify(msg));
}
return r.json;
}
case 'open_channel': {
return {
note: 'Funding a channel is a real BSV payment your wallet must sign, so open one at the website (BRC-100 wallet, or load a key in-page), then paste the channel key here / set BSVKEY_API_KEY.',
fundUrl: SITE,
accountUrl: `${SITE}/account.html`,
steps: [
`Open ${SITE} and use the "Pay with your BSV wallet" widget to fund a channel.`,
'Copy the channel key it returns (format: channelId:channelSecret).',
'Set BSVKEY_API_KEY to that value (or pass apiKey to infer), then call infer freely until the balance runs out.',
],
};
}
default:
throw new Error(`unknown tool: ${name}`);
}
}
// --- MCP JSON-RPC over stdio ------------------------------------------------
function result(id, value) { return { jsonrpc: '2.0', id, result: value }; }
function rpcError(id, code, message) { return { jsonrpc: '2.0', id, error: { code, message } }; }
export async function handleMessage(msg) {
if (!msg || msg.jsonrpc !== '2.0') return rpcError(msg?.id ?? null, -32600, 'invalid request');
const { id, method, params } = msg;
switch (method) {
case 'initialize':
return result(id, { protocolVersion: PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: SERVER_INFO });
case 'notifications/initialized':
case 'initialized':
return null;
case 'ping':
return result(id, {});
case 'tools/list':
return result(id, { tools: TOOLS });
case 'tools/call': {
try {
const value = await callTool(params?.name, params?.arguments || {});
return result(id, { content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] });
} catch (e) {
return result(id, { content: [{ type: 'text', text: `error: ${e.message}` }], isError: true });
}
}
default:
if (id === undefined) return null;
return rpcError(id, -32601, `method not found: ${method}`);
}
}
function runStdio() {
let buffer = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', async (chunk) => {
buffer += chunk;
let nl;
while ((nl = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (!line) continue;
let msg;
try { msg = JSON.parse(line); } catch { process.stdout.write(JSON.stringify(rpcError(null, -32700, 'parse error')) + '\n'); continue; }
const res = await handleMessage(msg);
if (res) process.stdout.write(JSON.stringify(res) + '\n');
}
});
process.stderr.write(`[bsvkey-inference mcp] ready on stdio → ${BASE} (${TOOLS.length} tools)\n`);
}
const invokedDirectly = process.argv[1] && /server\.js$/.test(process.argv[1]);
if (invokedDirectly) runStdio();