@paytaca/opencode-plugin 0.1.16 → 0.2.1
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 +67 -0
- package/dist/bundled/mcp.d.ts +2 -0
- package/dist/bundled/mcp.d.ts.map +1 -0
- package/dist/bundled/mcp.js +615 -0
- package/dist/bundled/mcp.js.map +1 -0
- package/dist/bundled/proxy.d.ts +1 -1
- package/dist/bundled/proxy.d.ts.map +1 -1
- package/dist/bundled/proxy.js +132 -21
- package/dist/bundled/proxy.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +7 -2
- package/dist/config.js.map +1 -1
- package/dist/context.d.ts +4 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +99 -0
- package/dist/context.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +60 -0
- package/dist/index.js.map +1 -1
- package/dist/proxy.d.ts +1 -0
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +1 -0
- package/dist/proxy.js.map +1 -1
- package/dist/selfheal.d.ts +13 -0
- package/dist/selfheal.d.ts.map +1 -0
- package/dist/selfheal.js +229 -0
- package/dist/selfheal.js.map +1 -0
- package/package.json +1 -1
- package/scripts/postinstall.js +148 -9
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// This file contains the bundled MCP server script as a string
|
|
3
|
+
// It gets written to ~/.opencode-paytaca/mcp-server.js at runtime
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.MCP_SERVER_CONTENT = void 0;
|
|
6
|
+
exports.MCP_SERVER_CONTENT = `#!/usr/bin/env node
|
|
7
|
+
/**
|
|
8
|
+
* Paytaca MCP Server
|
|
9
|
+
*
|
|
10
|
+
* Registers Paytaca tools with opencode so the assistant can work with real
|
|
11
|
+
* data instead of guessing. Two groups:
|
|
12
|
+
* - Paytaca AI account (backend): credits, models, plan pricing
|
|
13
|
+
* - Paytaca wallet (paytaca CLI): balance, transactions, receiving address,
|
|
14
|
+
* token holdings, and sending funds
|
|
15
|
+
*
|
|
16
|
+
* The send tool moves real funds — opencode is configured (via the plugin's
|
|
17
|
+
* config hook) to require explicit user approval before it runs.
|
|
18
|
+
*
|
|
19
|
+
* Loaded automatically via the plugin's config hook (cfg.mcp['paytaca']).
|
|
20
|
+
* Uses only Node.js built-in modules.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const http = require('http');
|
|
24
|
+
const https = require('https');
|
|
25
|
+
const { spawn } = require('child_process');
|
|
26
|
+
const fs = require('fs');
|
|
27
|
+
const path = require('path');
|
|
28
|
+
const os = require('os');
|
|
29
|
+
|
|
30
|
+
const CONFIG_DIR = process.env.PAYTACA_CONFIG_DIR || path.join(os.homedir(), '.opencode-paytaca');
|
|
31
|
+
const PAYTACA_CMD = process.env.PAYTACA_CMD || 'paytaca';
|
|
32
|
+
const DEFAULT_BACKEND = process.env.PAYTACA_BACKEND_URL || 'https://api.paytaca.ai';
|
|
33
|
+
|
|
34
|
+
const PROTOCOL_VERSION = '2025-06-18';
|
|
35
|
+
|
|
36
|
+
// Logging setup
|
|
37
|
+
const LOG_FILE = path.join(CONFIG_DIR, 'mcp.log');
|
|
38
|
+
const logStream = fs.createWriteStream(LOG_FILE, { flags: 'a' });
|
|
39
|
+
function log(message) {
|
|
40
|
+
const timestamp = new Date().toISOString();
|
|
41
|
+
logStream.write(timestamp + ' [MCP] ' + message + '\\n');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Load fresh config on every call so walletHash/backendUrl never go stale
|
|
45
|
+
function loadConfig() {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, 'config.json'), 'utf8'));
|
|
48
|
+
} catch (e) {
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let BACKEND_URL = DEFAULT_BACKEND;
|
|
54
|
+
let WALLET_HASH = '';
|
|
55
|
+
function refreshConfig() {
|
|
56
|
+
const cfg = loadConfig();
|
|
57
|
+
BACKEND_URL = process.env.PAYTACA_BACKEND_URL || cfg.backendUrl || DEFAULT_BACKEND;
|
|
58
|
+
WALLET_HASH = cfg.walletHash || '';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Fetch a JSON payload over HTTP(S)
|
|
62
|
+
function getJson(url, headers) {
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
let u;
|
|
65
|
+
try {
|
|
66
|
+
u = new URL(url);
|
|
67
|
+
} catch (e) {
|
|
68
|
+
return reject(new Error('Invalid URL: ' + url));
|
|
69
|
+
}
|
|
70
|
+
const requester = u.protocol === 'https:' ? https : http;
|
|
71
|
+
const req = requester.get({
|
|
72
|
+
hostname: u.hostname,
|
|
73
|
+
port: u.port || (u.protocol === 'https:' ? 443 : 80),
|
|
74
|
+
path: u.pathname + u.search,
|
|
75
|
+
headers: headers || {},
|
|
76
|
+
}, (res) => {
|
|
77
|
+
let data = '';
|
|
78
|
+
res.on('data', (chunk) => { data += chunk; });
|
|
79
|
+
res.on('end', () => {
|
|
80
|
+
if (res.statusCode >= 400) {
|
|
81
|
+
reject(new Error('HTTP ' + res.statusCode + ': ' + data.substring(0, 200)));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
resolve(JSON.parse(data));
|
|
86
|
+
} catch (e) {
|
|
87
|
+
reject(new Error('Invalid JSON response'));
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
req.on('error', reject);
|
|
92
|
+
req.setTimeout(15000, () => {
|
|
93
|
+
req.destroy();
|
|
94
|
+
reject(new Error('Request timed out'));
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Run a shell command with a timeout
|
|
100
|
+
function runCommand(cmd, args, timeoutMs) {
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
const child = spawn(cmd, args, { shell: false });
|
|
103
|
+
let stdout = '';
|
|
104
|
+
let stderr = '';
|
|
105
|
+
let settled = false;
|
|
106
|
+
const timer = setTimeout(() => {
|
|
107
|
+
if (settled) return;
|
|
108
|
+
settled = true;
|
|
109
|
+
try { child.kill(); } catch (e) {}
|
|
110
|
+
reject(new Error('Command timed out'));
|
|
111
|
+
}, timeoutMs || 15000);
|
|
112
|
+
child.stdout.on('data', (d) => { stdout += d.toString(); });
|
|
113
|
+
child.stderr.on('data', (d) => { stderr += d.toString(); });
|
|
114
|
+
child.on('close', (code) => {
|
|
115
|
+
if (settled) return;
|
|
116
|
+
settled = true;
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
if (code === 0) resolve(stdout.trim());
|
|
119
|
+
else reject(new Error(stderr.trim() || 'Command exited with code ' + code));
|
|
120
|
+
});
|
|
121
|
+
child.on('error', (err) => {
|
|
122
|
+
if (settled) return;
|
|
123
|
+
settled = true;
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
reject(err);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Format seconds as MM:SS or HH:MM:SS
|
|
131
|
+
function formatDuration(totalSeconds) {
|
|
132
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
133
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
134
|
+
const secs = totalSeconds % 60;
|
|
135
|
+
if (hours > 0) {
|
|
136
|
+
return hours + ':' + String(minutes).padStart(2, '0') + ':' + String(secs).padStart(2, '0');
|
|
137
|
+
}
|
|
138
|
+
return minutes + ':' + String(secs).padStart(2, '0');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Remaining time credits per model session
|
|
142
|
+
async function getCredits() {
|
|
143
|
+
const data = await getJson(BACKEND_URL + '/v1/wallet/status', { 'X-Wallet-Hash': WALLET_HASH });
|
|
144
|
+
const sessions = Array.isArray(data.sessions) ? data.sessions : [];
|
|
145
|
+
const active = sessions.filter((s) => s.time_remaining_seconds > 0 && s.model_active);
|
|
146
|
+
const inactive = sessions.filter((s) => s.time_remaining_seconds > 0 && !s.model_active);
|
|
147
|
+
const parts = [];
|
|
148
|
+
if (active.length > 0) {
|
|
149
|
+
parts.push('Active time credits:');
|
|
150
|
+
for (const s of active) {
|
|
151
|
+
const total = formatDuration(s.time_credits_seconds);
|
|
152
|
+
const remaining = formatDuration(s.time_remaining_seconds);
|
|
153
|
+
const used = formatDuration(s.time_used_seconds);
|
|
154
|
+
parts.push('- ' + (s.display_name || s.ai_model) + ': ' + remaining + ' remaining of ' + total + ' (' + used + ' used)');
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (inactive.length > 0) {
|
|
158
|
+
parts.push('');
|
|
159
|
+
parts.push('Inactive models (credits but session not active):');
|
|
160
|
+
for (const s of inactive) {
|
|
161
|
+
parts.push('- ' + (s.display_name || s.ai_model) + ': ' + formatDuration(s.time_remaining_seconds) + ' remaining');
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (parts.length === 0) {
|
|
165
|
+
return 'No active time credits.';
|
|
166
|
+
}
|
|
167
|
+
return parts.join('\\n');
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Wallet BCH balance via the paytaca CLI
|
|
171
|
+
async function getBalance() {
|
|
172
|
+
const out = await runCommand(PAYTACA_CMD, ['wallet', 'info']);
|
|
173
|
+
const match = out.match(/Balance:\\s*([\\d.]+)\\s*BCH/i);
|
|
174
|
+
if (match) {
|
|
175
|
+
return 'Wallet balance: ' + match[1] + ' BCH.';
|
|
176
|
+
}
|
|
177
|
+
return 'Could not parse balance. Raw output:\\n' + out.split('\\n').slice(0, 5).join('\\n');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// List all available models
|
|
181
|
+
async function getModels() {
|
|
182
|
+
const data = await getJson(BACKEND_URL + '/v1/config', {});
|
|
183
|
+
const models = Array.isArray(data.models) ? data.models : [];
|
|
184
|
+
const lines = ['Available models:'];
|
|
185
|
+
for (const m of models) {
|
|
186
|
+
let line = m.id || 'unknown';
|
|
187
|
+
if (m.display_name && m.display_name !== m.id) line += ' (' + m.display_name + ')';
|
|
188
|
+
if (m.tier) line += ' [' + m.tier + ']';
|
|
189
|
+
lines.push('- ' + line);
|
|
190
|
+
}
|
|
191
|
+
return lines.join('\\n');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Plan pricing grouped by tier, optionally filtered to one model
|
|
195
|
+
async function getPlans(filterModel) {
|
|
196
|
+
const data = await getJson(BACKEND_URL + '/v1/config', {});
|
|
197
|
+
let models = Array.isArray(data.models) ? data.models : [];
|
|
198
|
+
if (filterModel) {
|
|
199
|
+
const f = String(filterModel).toLowerCase();
|
|
200
|
+
models = models.filter((m) => {
|
|
201
|
+
const id = String(m.id || '').toLowerCase();
|
|
202
|
+
const name = String(m.display_name || '').toLowerCase();
|
|
203
|
+
return id.indexOf(f) !== -1 || name.indexOf(f) !== -1;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const groups = { budget: [], premium: [], frontier: [], other: [] };
|
|
207
|
+
for (const m of models) {
|
|
208
|
+
const key = String(m.tier || '').toLowerCase();
|
|
209
|
+
const groupKey = (key === 'budget' || key === 'premium' || key === 'frontier') ? key : 'other';
|
|
210
|
+
groups[groupKey].push(m);
|
|
211
|
+
}
|
|
212
|
+
const lines = ['Paytaca AI — Model Pricing'];
|
|
213
|
+
const order = [
|
|
214
|
+
{ key: 'budget', label: 'Budget' },
|
|
215
|
+
{ key: 'premium', label: 'Premium' },
|
|
216
|
+
{ key: 'frontier', label: 'Frontier' },
|
|
217
|
+
{ key: 'other', label: 'Other' },
|
|
218
|
+
];
|
|
219
|
+
let any = false;
|
|
220
|
+
for (const g of order) {
|
|
221
|
+
const group = groups[g.key];
|
|
222
|
+
if (group.length === 0) continue;
|
|
223
|
+
any = true;
|
|
224
|
+
lines.push('');
|
|
225
|
+
lines.push(g.label);
|
|
226
|
+
for (const m of group) {
|
|
227
|
+
lines.push('');
|
|
228
|
+
const tiers = Array.isArray(m.price_tiers) ? m.price_tiers : [];
|
|
229
|
+
if (tiers.length === 0) {
|
|
230
|
+
lines.push('- ' + (m.display_name || m.id) + ': no pricing configured');
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const sorted = tiers.slice().sort((a, b) => (a.minutes || 0) - (b.minutes || 0));
|
|
234
|
+
lines.push((m.display_name || m.id) + ':');
|
|
235
|
+
for (const t of sorted) {
|
|
236
|
+
const sats = typeof t.price_sats === 'number' ? t.price_sats : 0;
|
|
237
|
+
const bch = (sats / 100000000).toFixed(8);
|
|
238
|
+
const usd = typeof t.price_usd === 'number' ? t.price_usd.toFixed(4) : '?.??';
|
|
239
|
+
lines.push(' ' + (t.minutes || 0) + ' minutes — USD ' + usd + ' (' + bch + ' BCH)');
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (!any) {
|
|
244
|
+
lines.push('No models available.');
|
|
245
|
+
}
|
|
246
|
+
return lines.join('\\n');
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Resolve a model (by id or display name) and its price tier by minutes.
|
|
250
|
+
// Uses the same /v1/config data as get_plans.
|
|
251
|
+
async function resolvePlan(modelFilter, minutes) {
|
|
252
|
+
const data = await getJson(BACKEND_URL + '/v1/config', {});
|
|
253
|
+
const models = Array.isArray(data.models) ? data.models : [];
|
|
254
|
+
const f = String(modelFilter || '').toLowerCase();
|
|
255
|
+
const matches = models.filter((m) => {
|
|
256
|
+
const id = String(m.id || '').toLowerCase();
|
|
257
|
+
const name = String(m.display_name || '').toLowerCase();
|
|
258
|
+
return id.indexOf(f) !== -1 || name.indexOf(f) !== -1;
|
|
259
|
+
});
|
|
260
|
+
if (matches.length === 0) {
|
|
261
|
+
const ids = models.map((m) => m.id).join(', ');
|
|
262
|
+
throw new Error('Model not found: ' + modelFilter + '. Available models: ' + ids);
|
|
263
|
+
}
|
|
264
|
+
const model = matches[0];
|
|
265
|
+
const tiers = Array.isArray(model.price_tiers) ? model.price_tiers : [];
|
|
266
|
+
const want = Number(minutes);
|
|
267
|
+
const tier = tiers.find((t) => Number(t.minutes) === want);
|
|
268
|
+
if (!tier) {
|
|
269
|
+
const avail = tiers.map((t) => t.minutes).join(', ');
|
|
270
|
+
throw new Error('No ' + minutes + '-minute plan for ' + (model.display_name || model.id) + '. Available minutes: ' + avail);
|
|
271
|
+
}
|
|
272
|
+
return { model, tier };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Wallet balance in sats (mirrors the proxy's pre-payment check)
|
|
276
|
+
async function getBalanceSats() {
|
|
277
|
+
const out = await runCommand(PAYTACA_CMD, ['wallet', 'info'], 20000);
|
|
278
|
+
const match = out.match(/Balance:\\s*([\\d.]+)\\s*BCH/i);
|
|
279
|
+
if (!match) return null;
|
|
280
|
+
return Math.floor(parseFloat(match[1]) * 100000000);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Purchase time credits for a specific model and plan duration. Reuses the
|
|
284
|
+
// same payment wrapper the proxy runs on a 402 (x402 payment + retry with the
|
|
285
|
+
// PAYMENT-SIGNATURE header), but works for ANY model/tier the user picks —
|
|
286
|
+
// not just the model active in the current session. Spends real BCH.
|
|
287
|
+
async function buyPlan(args) {
|
|
288
|
+
const modelFilter = String(args.model || '').trim();
|
|
289
|
+
const minutes = Number(args.minutes);
|
|
290
|
+
if (!modelFilter) {
|
|
291
|
+
throw new Error('Missing model. Pass the model id or display name (e.g. deepseek/deepseek-v4-flash).');
|
|
292
|
+
}
|
|
293
|
+
if (isNaN(minutes) || minutes <= 0) {
|
|
294
|
+
throw new Error('Missing or invalid minutes. Pass the plan duration, e.g. 30 for the 30-minute plan.');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const { model, tier } = await resolvePlan(modelFilter, minutes);
|
|
298
|
+
const priceSats = Number(tier.price_sats) || 0;
|
|
299
|
+
|
|
300
|
+
// Fail fast on insufficient balance instead of sending a txn that cannot
|
|
301
|
+
// fund the plan (mirrors the proxy's 402 flow).
|
|
302
|
+
const balanceSats = await getBalanceSats();
|
|
303
|
+
if (balanceSats !== null && balanceSats < priceSats) {
|
|
304
|
+
const addr = await getReceivingAddress({});
|
|
305
|
+
const shortfall = (priceSats - balanceSats) / 100000000;
|
|
306
|
+
throw new Error('Insufficient balance: ' + (balanceSats / 100000000).toFixed(8) + ' BCH available but the ' + minutes + '-minute plan costs ' + (priceSats / 100000000).toFixed(8) + ' BCH. Top up at least ' + shortfall.toFixed(8) + ' BCH to: ' + addr);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const wrapper = path.join(CONFIG_DIR, 'paytaca-pay-wrapper.mjs');
|
|
310
|
+
if (!fs.existsSync(wrapper)) {
|
|
311
|
+
throw new Error('Payment wrapper not found at ' + wrapper + '. Restart opencode so the plugin writes it.');
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Minimal chat request for the target model; the payment flow only needs a
|
|
315
|
+
// valid request that triggers the x402 PaymentRequired for that model.
|
|
316
|
+
const body = JSON.stringify({
|
|
317
|
+
model: model.id,
|
|
318
|
+
messages: [{ role: 'user', content: 'Purchase plan' }],
|
|
319
|
+
stream: false,
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
const url = BACKEND_URL + '/v1/chat/completions?wallet_hash=' + encodeURIComponent(WALLET_HASH || '');
|
|
323
|
+
const extraHeaders = {
|
|
324
|
+
'X-Model-Id': model.id,
|
|
325
|
+
'X-Duration-Minutes': String(tier.minutes),
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'paytaca-buy-plan-'));
|
|
329
|
+
const bodyFile = path.join(tmpDir, 'body.json');
|
|
330
|
+
const configFile = path.join(tmpDir, 'config.json');
|
|
331
|
+
try {
|
|
332
|
+
fs.writeFileSync(bodyFile, body, 'utf8');
|
|
333
|
+
fs.writeFileSync(configFile, JSON.stringify({
|
|
334
|
+
url: url,
|
|
335
|
+
method: 'POST',
|
|
336
|
+
headers: Object.assign({ 'Content-Type': 'application/json' }, extraHeaders),
|
|
337
|
+
bodyFile: bodyFile,
|
|
338
|
+
confirmed: true,
|
|
339
|
+
}), 'utf8');
|
|
340
|
+
} catch (e) {
|
|
341
|
+
try { fs.rmdirSync(tmpDir); } catch (e2) {}
|
|
342
|
+
throw new Error('Failed to write payment files: ' + e.message);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
log('Buy plan requested: ' + model.id + ' ' + tier.minutes + ' min');
|
|
346
|
+
let stdout;
|
|
347
|
+
try {
|
|
348
|
+
stdout = await runCommand('node', [wrapper, configFile], 250000);
|
|
349
|
+
} finally {
|
|
350
|
+
try { fs.unlinkSync(bodyFile); } catch (e2) {}
|
|
351
|
+
try { fs.unlinkSync(configFile); } catch (e2) {}
|
|
352
|
+
try { fs.rmdirSync(tmpDir); } catch (e2) {}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
let result;
|
|
356
|
+
try {
|
|
357
|
+
result = JSON.parse(stdout);
|
|
358
|
+
} catch (e) {
|
|
359
|
+
throw new Error('Could not parse payment result: ' + stdout.substring(0, 200));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (result.timeout) {
|
|
363
|
+
return 'Payment was processed but the response timed out. Check your credits with get_credits.';
|
|
364
|
+
}
|
|
365
|
+
if (!result.success) {
|
|
366
|
+
throw new Error(result.error || 'Payment failed (status ' + result.status + ').');
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const lines = ['Plan purchased for ' + (model.display_name || model.id) + ': ' + tier.minutes + ' minutes.'];
|
|
370
|
+
if (result.payment && result.payment.txid) {
|
|
371
|
+
lines.push('Transaction: ' + result.payment.txid);
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
const status = await getJson(BACKEND_URL + '/v1/wallet/status', { 'X-Wallet-Hash': WALLET_HASH });
|
|
375
|
+
const sessions = Array.isArray(status.sessions) ? status.sessions : [];
|
|
376
|
+
const found = sessions.find((s) => s.ai_model === model.id);
|
|
377
|
+
if (found && found.time_remaining_seconds > 0) {
|
|
378
|
+
lines.push('Credits: ' + formatDuration(found.time_remaining_seconds) + ' remaining.');
|
|
379
|
+
}
|
|
380
|
+
} catch (e) {}
|
|
381
|
+
return lines.join('\\n');
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// Recent wallet transactions via the paytaca CLI
|
|
385
|
+
async function getTransactions(args) {
|
|
386
|
+
const cmdArgs = ['history'];
|
|
387
|
+
if (args.type === 'incoming' || args.type === 'outgoing') {
|
|
388
|
+
cmdArgs.push('--type', args.type);
|
|
389
|
+
}
|
|
390
|
+
const page = parseInt(args.page, 10);
|
|
391
|
+
if (!isNaN(page) && page > 0) {
|
|
392
|
+
cmdArgs.push('--page', String(page));
|
|
393
|
+
}
|
|
394
|
+
const out = await runCommand(PAYTACA_CMD, cmdArgs, 30000);
|
|
395
|
+
return out || 'No transactions found.';
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Receiving address via the paytaca CLI (QR art suppressed)
|
|
399
|
+
async function getReceivingAddress(args) {
|
|
400
|
+
const cmdArgs = ['receive', '--no-qr'];
|
|
401
|
+
const amount = parseFloat(args.amount);
|
|
402
|
+
if (!isNaN(amount) && amount > 0) {
|
|
403
|
+
cmdArgs.push('--amount', String(amount));
|
|
404
|
+
}
|
|
405
|
+
const out = await runCommand(PAYTACA_CMD, cmdArgs, 30000);
|
|
406
|
+
return out.trim() || 'Could not get receiving address.';
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// CashToken holdings via the paytaca CLI (all tokens, or one category)
|
|
410
|
+
async function getTokens(args) {
|
|
411
|
+
const category = args.category ? String(args.category).trim() : '';
|
|
412
|
+
const cmdArgs = category ? ['token', 'info', category] : ['token', 'list'];
|
|
413
|
+
const out = await runCommand(PAYTACA_CMD, cmdArgs, 30000);
|
|
414
|
+
return out.trim() || (category ? 'Token not found: ' + category : 'No tokens found.');
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Send BCH or CashTokens. This spends real funds — opencode requires manual
|
|
418
|
+
// user approval for this tool (permission 'paytaca_send' set to 'ask' by the
|
|
419
|
+
// plugin's config hook), so it must never be called without the user asking
|
|
420
|
+
// for the send.
|
|
421
|
+
async function sendFunds(args) {
|
|
422
|
+
const address = String(args.address || '').trim();
|
|
423
|
+
const amount = String(args.amount || '').trim();
|
|
424
|
+
const unit = args.unit === 'sats' ? 'sats' : 'bch';
|
|
425
|
+
const tokenCategory = args.token_category ? String(args.token_category).trim() : '';
|
|
426
|
+
if (!address) {
|
|
427
|
+
throw new Error('Missing recipient address.');
|
|
428
|
+
}
|
|
429
|
+
if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) {
|
|
430
|
+
throw new Error('Missing or invalid amount.');
|
|
431
|
+
}
|
|
432
|
+
const cmdArgs = tokenCategory
|
|
433
|
+
? ['token', 'send', address, amount, '--token', tokenCategory]
|
|
434
|
+
: ['send', address, amount];
|
|
435
|
+
if (!tokenCategory && unit === 'sats') {
|
|
436
|
+
cmdArgs.push('--unit', 'sats');
|
|
437
|
+
}
|
|
438
|
+
log('Send requested: ' + cmdArgs.join(' '));
|
|
439
|
+
const out = await runCommand(PAYTACA_CMD, cmdArgs, 90000);
|
|
440
|
+
log('Send completed');
|
|
441
|
+
return 'Transaction sent.\\n\\n' + out;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Tool schemas (concise descriptions so MCP tool context stays small)
|
|
445
|
+
const TOOLS = [
|
|
446
|
+
{
|
|
447
|
+
name: 'get_credits',
|
|
448
|
+
description: 'Get remaining Paytaca AI time credits (active model sessions, time left). Use when the user asks about credits, remaining time, session status, or how much usage they have left.',
|
|
449
|
+
inputSchema: { type: 'object', properties: {} },
|
|
450
|
+
},
|
|
451
|
+
{
|
|
452
|
+
name: 'get_balance',
|
|
453
|
+
description: 'Get the BCH balance of the user\\'s Paytaca wallet. Use when the user asks about wallet balance or funds.',
|
|
454
|
+
inputSchema: { type: 'object', properties: {} },
|
|
455
|
+
},
|
|
456
|
+
{
|
|
457
|
+
name: 'get_models',
|
|
458
|
+
description: 'List the AI models available on Paytaca AI (id, display name, tier). Use when the user asks which models are available.',
|
|
459
|
+
inputSchema: { type: 'object', properties: {} },
|
|
460
|
+
},
|
|
461
|
+
{
|
|
462
|
+
name: 'get_plans',
|
|
463
|
+
description: 'Get Paytaca AI plan pricing: time tiers in minutes with USD and BCH prices, grouped by tier. Optionally pass a model id/name to filter one model. Use when the user asks about plans, pricing, costs, or how much a model costs.',
|
|
464
|
+
inputSchema: {
|
|
465
|
+
type: 'object',
|
|
466
|
+
properties: {
|
|
467
|
+
model: { type: 'string', description: 'Optional model id or display name to filter pricing to a single model.' },
|
|
468
|
+
},
|
|
469
|
+
},
|
|
470
|
+
},
|
|
471
|
+
{
|
|
472
|
+
name: 'buy_plan',
|
|
473
|
+
description: 'Purchase Paytaca AI time credits for a specific model and plan duration. SPENDS BCH FROM THE WALLET — only call when the user explicitly asks to buy, purchase, or pay for a plan; opencode prompts the user for approval. Show pricing with get_plans first, then call with the model and minutes the user picked. Works for any model, even one not active in the current session.',
|
|
474
|
+
inputSchema: {
|
|
475
|
+
type: 'object',
|
|
476
|
+
required: ['model', 'minutes'],
|
|
477
|
+
properties: {
|
|
478
|
+
model: { type: 'string', description: 'Model id or display name, e.g. deepseek/deepseek-v4-flash or DeepSeek V4 Flash.' },
|
|
479
|
+
minutes: { type: 'number', description: 'Plan duration in minutes, e.g. 30 for the 30-minute tier.' },
|
|
480
|
+
},
|
|
481
|
+
},
|
|
482
|
+
},
|
|
483
|
+
{
|
|
484
|
+
name: 'get_transactions',
|
|
485
|
+
description: 'Get recent Paytaca wallet transactions (sent/received BCH). Use when the user asks about transaction history or latest transactions.',
|
|
486
|
+
inputSchema: {
|
|
487
|
+
type: 'object',
|
|
488
|
+
properties: {
|
|
489
|
+
type: { type: 'string', enum: ['incoming', 'outgoing'], description: 'Optional direction filter.' },
|
|
490
|
+
page: { type: 'number', description: 'Optional 1-based page number for older history.' },
|
|
491
|
+
},
|
|
492
|
+
},
|
|
493
|
+
},
|
|
494
|
+
{
|
|
495
|
+
name: 'get_receiving_address',
|
|
496
|
+
description: 'Get a Paytaca wallet receiving address for depositing BCH, optionally as a BIP21 URI with an amount. Use when the user wants to fund the wallet or needs their address.',
|
|
497
|
+
inputSchema: {
|
|
498
|
+
type: 'object',
|
|
499
|
+
properties: {
|
|
500
|
+
amount: { type: 'number', description: 'Optional BCH amount to embed in a BIP21 payment URI.' },
|
|
501
|
+
},
|
|
502
|
+
},
|
|
503
|
+
},
|
|
504
|
+
{
|
|
505
|
+
name: 'get_tokens',
|
|
506
|
+
description: 'List CashToken holdings of the Paytaca wallet, or get details (name, symbol, balance, NFTs) for one token category. Use when the user asks about tokens or NFTs.',
|
|
507
|
+
inputSchema: {
|
|
508
|
+
type: 'object',
|
|
509
|
+
properties: {
|
|
510
|
+
category: { type: 'string', description: 'Optional token category id for details of a single token.' },
|
|
511
|
+
},
|
|
512
|
+
},
|
|
513
|
+
},
|
|
514
|
+
{
|
|
515
|
+
name: 'send',
|
|
516
|
+
description: 'Send BCH or CashTokens from the Paytaca wallet to an address. SPENDS REAL FUNDS — only call when the user explicitly asks to send; opencode will prompt the user for approval and that prompt must never be bypassed. Token amounts are in base units; recipients of tokens should use token-aware (z-prefix) addresses.',
|
|
517
|
+
inputSchema: {
|
|
518
|
+
type: 'object',
|
|
519
|
+
required: ['address', 'amount'],
|
|
520
|
+
properties: {
|
|
521
|
+
address: { type: 'string', description: 'Recipient CashAddr (e.g. bitcoincash:qp...).' },
|
|
522
|
+
amount: { type: 'string', description: 'Amount to send.' },
|
|
523
|
+
unit: { type: 'string', enum: ['bch', 'sats'], description: 'Amount unit, default bch. Ignored for token sends.' },
|
|
524
|
+
token_category: { type: 'string', description: 'Token category id to send CashTokens instead of BCH.' },
|
|
525
|
+
},
|
|
526
|
+
},
|
|
527
|
+
},
|
|
528
|
+
];
|
|
529
|
+
|
|
530
|
+
// JSON-RPC over stdio (newline-delimited)
|
|
531
|
+
let buffer = '';
|
|
532
|
+
function handleMessage(msg) {
|
|
533
|
+
if (msg.method === 'initialize') {
|
|
534
|
+
const requestedVersion = msg.params && msg.params.protocolVersion;
|
|
535
|
+
send(msg.id, {
|
|
536
|
+
protocolVersion: requestedVersion || PROTOCOL_VERSION,
|
|
537
|
+
capabilities: { tools: {} },
|
|
538
|
+
serverInfo: { name: 'paytaca', version: '1.2.0' },
|
|
539
|
+
});
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (msg.method === 'notifications/initialized') {
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (msg.method === 'ping') {
|
|
546
|
+
send(msg.id, {});
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
if (msg.method === 'tools/list') {
|
|
550
|
+
send(msg.id, { tools: TOOLS });
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (msg.method === 'tools/call') {
|
|
554
|
+
const name = msg.params && msg.params.name;
|
|
555
|
+
const args = (msg.params && msg.params.arguments) || {};
|
|
556
|
+
refreshConfig();
|
|
557
|
+
(async () => {
|
|
558
|
+
let text;
|
|
559
|
+
try {
|
|
560
|
+
switch (name) {
|
|
561
|
+
case 'get_credits': text = await getCredits(); break;
|
|
562
|
+
case 'get_balance': text = await getBalance(); break;
|
|
563
|
+
case 'get_models': text = await getModels(); break;
|
|
564
|
+
case 'get_plans': text = await getPlans(args.model); break;
|
|
565
|
+
case 'buy_plan': text = await buyPlan(args); break;
|
|
566
|
+
case 'get_transactions': text = await getTransactions(args); break;
|
|
567
|
+
case 'get_receiving_address': text = await getReceivingAddress(args); break;
|
|
568
|
+
case 'get_tokens': text = await getTokens(args); break;
|
|
569
|
+
case 'send': text = await sendFunds(args); break;
|
|
570
|
+
default: throw new Error('Unknown tool: ' + name);
|
|
571
|
+
}
|
|
572
|
+
send(msg.id, { content: [{ type: 'text', text: text }] });
|
|
573
|
+
} catch (e) {
|
|
574
|
+
log('Tool ' + name + ' failed: ' + e.message);
|
|
575
|
+
send(msg.id, { content: [{ type: 'text', text: 'Error: ' + e.message }], isError: true });
|
|
576
|
+
}
|
|
577
|
+
})();
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
// Unknown request — respond with an empty result so the client never hangs
|
|
581
|
+
if (typeof msg.id !== 'undefined' && msg.id !== null) {
|
|
582
|
+
send(msg.id, {});
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function send(id, result) {
|
|
587
|
+
const payload = { jsonrpc: '2.0', id, result };
|
|
588
|
+
process.stdout.write(JSON.stringify(payload) + '\\n');
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
process.stdin.on('data', (chunk) => {
|
|
592
|
+
buffer += chunk.toString();
|
|
593
|
+
let idx;
|
|
594
|
+
while ((idx = buffer.indexOf('\\n')) !== -1) {
|
|
595
|
+
const line = buffer.substring(0, idx).trim();
|
|
596
|
+
buffer = buffer.substring(idx + 1);
|
|
597
|
+
if (!line) continue;
|
|
598
|
+
let msg;
|
|
599
|
+
try {
|
|
600
|
+
msg = JSON.parse(line);
|
|
601
|
+
} catch (e) {
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
handleMessage(msg);
|
|
606
|
+
} catch (e) {
|
|
607
|
+
log('handleMessage error: ' + e.message);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
refreshConfig();
|
|
613
|
+
log('MCP server started (backend=' + BACKEND_URL + ')');
|
|
614
|
+
`;
|
|
615
|
+
//# sourceMappingURL=mcp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../src/bundled/mcp.ts"],"names":[],"mappings":";AAAA,+DAA+D;AAC/D,kEAAkE;;;AAErD,QAAA,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgmBjC,CAAC"}
|