@splice-mcp/splice 0.0.0-stage โ†’ 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/dist/index.js ADDED
@@ -0,0 +1,741 @@
1
+ import http from 'node:http';
2
+ import readline from 'node:readline';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { Command } from 'commander';
6
+ import { compileToSplice, SpliceRuntime, McpProcessClient, SpliceWrapperRuntime, } from '@splice-mcp/core';
7
+ import { getSpliceBundle, listSpliceBundles } from '@splice-mcp/store';
8
+ import { loadLocalDotEnv, resolveMarketplaceTarget, checkRequiredEnv, createMarketplaceCodeModeHandler, } from './marketplace.js';
9
+ const program = new Command();
10
+ program
11
+ .name('splice')
12
+ .description('Splice by Postpipe - The ultra-lean Code Mode MCP engine')
13
+ .version('0.1.0');
14
+ program
15
+ .command('serve')
16
+ .description('Serve an OpenAPI spec or pre-compiled bundle as a local Code Mode MCP server')
17
+ .argument('<target>', 'Path to openapi.json/yaml, spec URL, or name of pre-compiled bundle (e.g. stripe, github, slack)')
18
+ .option('-p, --port <number>', 'Port to listen on', '8080')
19
+ .option('-k, --api-key <key>', 'Upstream API Key to automatically inject into requests')
20
+ .option('-u, --base-url <url>', 'Override upstream API base URL')
21
+ .action(async (target, options) => {
22
+ const port = parseInt(options.port, 10);
23
+ let bundle = null;
24
+ // Check if target matches pre-compiled bundle in store
25
+ const storeBundle = await getSpliceBundle(target);
26
+ if (storeBundle) {
27
+ bundle = storeBundle;
28
+ }
29
+ else if (target.startsWith('http://') || target.startsWith('https://')) {
30
+ console.log(`๐Ÿ“ก Fetching remote OpenAPI spec from ${target}...`);
31
+ const res = await fetch(target);
32
+ const text = await res.text();
33
+ bundle = compileToSplice(text);
34
+ }
35
+ else {
36
+ const absPath = path.resolve(process.cwd(), target);
37
+ console.log(`๐Ÿ“‚ Loading local spec from ${absPath}...`);
38
+ const text = await fs.readFile(absPath, 'utf-8');
39
+ bundle = compileToSplice(text);
40
+ }
41
+ if (!bundle) {
42
+ console.error(`โŒ Could not load or compile spec: ${target}`);
43
+ process.exit(1);
44
+ }
45
+ const runtime = new SpliceRuntime(bundle);
46
+ const server = http.createServer(async (req, res) => {
47
+ // CORS headers
48
+ res.setHeader('Access-Control-Allow-Origin', '*');
49
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
50
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
51
+ if (req.method === 'OPTIONS') {
52
+ res.writeHead(204);
53
+ res.end();
54
+ return;
55
+ }
56
+ const url = new URL(req.url || '/', `http://localhost:${port}`);
57
+ if (url.pathname === '/health') {
58
+ res.writeHead(200, { 'Content-Type': 'application/json' });
59
+ res.end(JSON.stringify({ status: 'ok', bundle: bundle.name, endpoints: bundle.endpoints.length }));
60
+ return;
61
+ }
62
+ if (url.pathname === '/mcp' || url.pathname === '/') {
63
+ if (req.method === 'POST') {
64
+ let body = '';
65
+ req.on('data', (chunk) => { body += chunk; });
66
+ req.on('end', async () => {
67
+ try {
68
+ const rpc = JSON.parse(body);
69
+ const response = await runtime.handleMcpRequest(rpc);
70
+ res.writeHead(200, { 'Content-Type': 'application/json' });
71
+ res.end(JSON.stringify({
72
+ jsonrpc: '2.0',
73
+ id: rpc.id || null,
74
+ ...response,
75
+ }));
76
+ }
77
+ catch (err) {
78
+ res.writeHead(400, { 'Content-Type': 'application/json' });
79
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: err.message } }));
80
+ }
81
+ });
82
+ return;
83
+ }
84
+ // Return tools definition for GET
85
+ res.writeHead(200, { 'Content-Type': 'application/json' });
86
+ const toolsRes = await runtime.handleMcpRequest({ method: 'tools/list' });
87
+ res.end(JSON.stringify(toolsRes.result, null, 2));
88
+ return;
89
+ }
90
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
91
+ res.end('Not Found');
92
+ });
93
+ server.listen(port, () => {
94
+ console.log('\n======================================================');
95
+ console.log(`โœจ Splice MCP Server Active: ${bundle.title}`);
96
+ console.log(`๐ŸŒ Server URL: http://localhost:${port}/mcp`);
97
+ console.log(`๐Ÿ“Š Endpoints Indexed: ${bundle.endpoints.length}`);
98
+ console.log(`โšก Schema Footprint: ${bundle.metrics.spliceMcpTokens} tokens (Traditional: ${bundle.metrics.nativeMcpTokens.toLocaleString()} tokens)`);
99
+ console.log(`๐Ÿ“‰ Token Reduction: ${bundle.metrics.reductionPercent}% Saved`);
100
+ console.log('======================================================\n');
101
+ console.log('Paste this into your Cursor or Claude Desktop config:');
102
+ console.log(JSON.stringify({
103
+ mcpServers: {
104
+ [bundle.name]: {
105
+ url: `http://localhost:${port}/mcp`
106
+ }
107
+ }
108
+ }, null, 2));
109
+ console.log('\nPress Ctrl+C to stop.\n');
110
+ });
111
+ });
112
+ program
113
+ .command('wrap')
114
+ .description('Wrap ANY community MCP server process into an ultra-lean 380-token Code Mode MCP server')
115
+ .argument('<cmd>', 'The command to execute (e.g. npx, uvx, docker, python)')
116
+ .argument('[args...]', 'Arguments for the command')
117
+ .option('-p, --port <number>', 'Port for HTTP MCP server', '8080')
118
+ .option('--stdio', 'Serve directly over stdio for Claude Desktop / Cursor', false)
119
+ .action(async (cmd, cmdArgs = [], options) => {
120
+ const isStdio = options.stdio;
121
+ if (!isStdio) {
122
+ console.log(`\n๐Ÿš€ Launching community MCP process: ${cmd} ${cmdArgs.join(' ')}...`);
123
+ }
124
+ const mcpClient = new McpProcessClient(cmd, cmdArgs);
125
+ try {
126
+ await mcpClient.start();
127
+ await mcpClient.initialize();
128
+ const tools = await mcpClient.listTools();
129
+ if (!isStdio) {
130
+ console.log(`โœ… Connected to community MCP! Discovered ${tools.length} raw tools.`);
131
+ }
132
+ const serverName = cmdArgs.find((a) => !a.startsWith('-')) || cmd;
133
+ const cleanName = path.basename(serverName).replace(/^mcp-server-/, '');
134
+ const wrapperRuntime = new SpliceWrapperRuntime(mcpClient, tools, cleanName);
135
+ if (!isStdio) {
136
+ console.log('\n======================================================');
137
+ console.log(`โšก Splice Universal Code Mode Wrapper Active!`);
138
+ console.log(`๐Ÿ“ฆ Original Tools: ${tools.length} (Context: ~${wrapperRuntime.bundle.metrics.nativeMcpTokens.toLocaleString()} tokens)`);
139
+ console.log(`โœจ Splice Tools: 3 (search, describe, execute)`);
140
+ console.log(`๐Ÿ“‰ Schema Context: ${wrapperRuntime.bundle.metrics.spliceMcpTokens} tokens (${wrapperRuntime.bundle.metrics.reductionPercent}% saved)`);
141
+ console.log('======================================================\n');
142
+ }
143
+ if (isStdio) {
144
+ // Direct stdio proxy mode for Claude Desktop / Cursor
145
+ const rl = readline.createInterface({
146
+ input: process.stdin,
147
+ crlfDelay: Infinity,
148
+ });
149
+ rl.on('line', async (line) => {
150
+ const trimmed = line.trim();
151
+ if (!trimmed || !trimmed.startsWith('{'))
152
+ return;
153
+ try {
154
+ const rpc = JSON.parse(trimmed);
155
+ if (rpc.method === 'initialize') {
156
+ const resp = {
157
+ jsonrpc: '2.0',
158
+ id: rpc.id,
159
+ result: {
160
+ protocolVersion: '2024-11-05',
161
+ capabilities: { tools: {} },
162
+ serverInfo: { name: `splice-${cleanName}`, version: '0.1.0' },
163
+ },
164
+ };
165
+ process.stdout.write(JSON.stringify(resp) + '\n');
166
+ return;
167
+ }
168
+ if (rpc.method === 'notifications/initialized') {
169
+ return;
170
+ }
171
+ const response = await wrapperRuntime.handleMcpRequest(rpc);
172
+ const resp = {
173
+ jsonrpc: '2.0',
174
+ id: rpc.id ?? null,
175
+ ...response,
176
+ };
177
+ process.stdout.write(JSON.stringify(resp) + '\n');
178
+ }
179
+ catch (err) {
180
+ process.stdout.write(JSON.stringify({
181
+ jsonrpc: '2.0',
182
+ id: null,
183
+ error: { code: -32700, message: err.message },
184
+ }) + '\n');
185
+ }
186
+ });
187
+ process.on('SIGINT', () => {
188
+ mcpClient.stop();
189
+ process.exit(0);
190
+ });
191
+ return;
192
+ }
193
+ // HTTP mode
194
+ const port = parseInt(options.port, 10);
195
+ const server = http.createServer(async (req, res) => {
196
+ res.setHeader('Access-Control-Allow-Origin', '*');
197
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
198
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
199
+ if (req.method === 'OPTIONS') {
200
+ res.writeHead(204);
201
+ res.end();
202
+ return;
203
+ }
204
+ const url = new URL(req.url || '/', `http://localhost:${port}`);
205
+ if (url.pathname === '/health') {
206
+ res.writeHead(200, { 'Content-Type': 'application/json' });
207
+ res.end(JSON.stringify({ status: 'ok', toolsCount: tools.length, wrapped: true }));
208
+ return;
209
+ }
210
+ if (url.pathname === '/mcp' || url.pathname === '/') {
211
+ if (req.method === 'POST') {
212
+ let body = '';
213
+ req.on('data', (chunk) => { body += chunk; });
214
+ req.on('end', async () => {
215
+ try {
216
+ const rpc = JSON.parse(body);
217
+ const response = await wrapperRuntime.handleMcpRequest(rpc);
218
+ res.writeHead(200, { 'Content-Type': 'application/json' });
219
+ res.end(JSON.stringify({
220
+ jsonrpc: '2.0',
221
+ id: rpc.id || null,
222
+ ...response,
223
+ }));
224
+ }
225
+ catch (err) {
226
+ res.writeHead(400, { 'Content-Type': 'application/json' });
227
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: err.message } }));
228
+ }
229
+ });
230
+ return;
231
+ }
232
+ res.writeHead(200, { 'Content-Type': 'application/json' });
233
+ const toolsRes = await wrapperRuntime.handleMcpRequest({ method: 'tools/list' });
234
+ res.end(JSON.stringify(toolsRes.result, null, 2));
235
+ return;
236
+ }
237
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
238
+ res.end('Not Found');
239
+ });
240
+ server.listen(port, () => {
241
+ console.log(`๐ŸŒ Splice Wrapped MCP URL: http://localhost:${port}/mcp`);
242
+ console.log('\nClaude Desktop / Cursor config to connect:');
243
+ console.log(JSON.stringify({
244
+ mcpServers: {
245
+ [`${cleanName}-splice`]: {
246
+ url: `http://localhost:${port}/mcp`,
247
+ },
248
+ },
249
+ }, null, 2));
250
+ console.log('\nPress Ctrl+C to stop.\n');
251
+ });
252
+ process.on('SIGINT', () => {
253
+ mcpClient.stop();
254
+ process.exit(0);
255
+ });
256
+ }
257
+ catch (err) {
258
+ console.error(`โŒ Failed to wrap community MCP: ${err.message}`);
259
+ mcpClient.stop();
260
+ process.exit(1);
261
+ }
262
+ });
263
+ program
264
+ .command('run')
265
+ .description('Pull and run any Splice Marketplace MCP or CoWork Bundle in Code Mode (stdio or HTTP)')
266
+ .argument('<target>', 'Marketplace MCP slug, Bundle slug, or Bundle ID (e.g. google-stitch, fullstack-nextjs-postgres)')
267
+ .option('-p, --port <number>', 'Serve over HTTP on this port instead of stdio')
268
+ .option('--api <url>', 'Splice Marketplace API base URL', process.env.SPLICE_API_URL || 'http://localhost:3000')
269
+ .action(async (target, options) => {
270
+ await loadLocalDotEnv();
271
+ const artifact = await resolveMarketplaceTarget(target, options.api);
272
+ if (!artifact) {
273
+ console.error(`โŒ Could not find Marketplace MCP or Bundle '${target}'.`);
274
+ process.exit(1);
275
+ }
276
+ const { missing } = checkRequiredEnv(artifact.requiredEnv);
277
+ if (missing.length > 0) {
278
+ console.error(`โš ๏ธ [${artifact.slug}] Missing env vars: ${missing.join(', ')} (set in .env or IDE mcp.json)`);
279
+ }
280
+ const { codeModeTools, handleRpc } = createMarketplaceCodeModeHandler(artifact);
281
+ const isStdio = !options.port;
282
+ if (isStdio) {
283
+ console.error(`โœจ Splice Code Mode (${artifact.kind}) active: ${artifact.title} [${artifact.tools.length} tools indexed]`);
284
+ const rl = readline.createInterface({
285
+ input: process.stdin,
286
+ crlfDelay: Infinity,
287
+ });
288
+ rl.on('line', async (line) => {
289
+ const trimmed = line.trim();
290
+ if (!trimmed || !trimmed.startsWith('{'))
291
+ return;
292
+ try {
293
+ const rpc = JSON.parse(trimmed);
294
+ if (rpc.method === 'notifications/initialized')
295
+ return;
296
+ const response = await handleRpc(rpc);
297
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: rpc.id ?? null, ...response }) + '\n');
298
+ }
299
+ catch (err) {
300
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: err.message } }) + '\n');
301
+ }
302
+ });
303
+ return;
304
+ }
305
+ const port = parseInt(options.port || '8080', 10);
306
+ const server = http.createServer(async (req, res) => {
307
+ res.setHeader('Access-Control-Allow-Origin', '*');
308
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
309
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
310
+ if (req.method === 'OPTIONS') {
311
+ res.writeHead(204);
312
+ res.end();
313
+ return;
314
+ }
315
+ if (req.url === '/health') {
316
+ res.writeHead(200, { 'Content-Type': 'application/json' });
317
+ res.end(JSON.stringify({ status: 'ok', kind: artifact.kind, slug: artifact.slug, tools: artifact.tools.length }));
318
+ return;
319
+ }
320
+ if (req.method === 'POST') {
321
+ let body = '';
322
+ req.on('data', (chunk) => { body += chunk; });
323
+ req.on('end', async () => {
324
+ try {
325
+ const rpc = JSON.parse(body);
326
+ const response = await handleRpc(rpc);
327
+ res.writeHead(200, { 'Content-Type': 'application/json' });
328
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: rpc.id ?? null, ...response }));
329
+ }
330
+ catch (err) {
331
+ res.writeHead(400, { 'Content-Type': 'application/json' });
332
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: err.message } }));
333
+ }
334
+ });
335
+ return;
336
+ }
337
+ res.writeHead(200, { 'Content-Type': 'application/json' });
338
+ res.end(JSON.stringify({ tools: codeModeTools }, null, 2));
339
+ });
340
+ server.listen(port, () => {
341
+ console.log(`โœจ Splice ${artifact.kind} '${artifact.title}' running at http://localhost:${port}/mcp`);
342
+ });
343
+ });
344
+ program
345
+ .command('add')
346
+ .description('Pull a Marketplace MCP or Bundle manifest and print ready-to-use IDE configuration')
347
+ .argument('<target>', 'Marketplace MCP slug or Bundle slug/ID')
348
+ .option('-c, --client <ide>', 'Target IDE (cursor, claude, antigravity, vscode)', 'cursor')
349
+ .option('--api <url>', 'Splice Marketplace API base URL', process.env.SPLICE_API_URL || 'http://localhost:3000')
350
+ .action(async (target, options) => {
351
+ await loadLocalDotEnv();
352
+ const artifact = await resolveMarketplaceTarget(target, options.api);
353
+ if (!artifact) {
354
+ console.error(`โŒ Could not find '${target}' in Splice Marketplace.`);
355
+ process.exit(1);
356
+ }
357
+ const envBlock = Object.fromEntries(artifact.requiredEnv.map((k) => [k, `\${${k}}`]));
358
+ const serverEntry = {
359
+ command: 'npx',
360
+ args: ['-y', '@splice-mcp/splice', 'run', artifact.slug],
361
+ ...(artifact.requiredEnv.length > 0 ? { env: envBlock } : {}),
362
+ };
363
+ const client = options.client.toLowerCase();
364
+ const config = client === 'antigravity'
365
+ ? { mcp: { servers: { [artifact.slug]: serverEntry } } }
366
+ : client === 'vscode'
367
+ ? { 'mcp.servers': { [artifact.slug]: { type: 'stdio', ...serverEntry } } }
368
+ : { mcpServers: { [artifact.slug]: serverEntry } };
369
+ console.log(`\nโœจ ${artifact.title} (${artifact.kind})`);
370
+ console.log(`๐Ÿ“ฆ Tools Indexed: ${artifact.tools.length}`);
371
+ if (artifact.requiredEnv.length > 0) {
372
+ const { present, missing } = checkRequiredEnv(artifact.requiredEnv);
373
+ console.log(`๐Ÿ”‘ Required Env: ${artifact.requiredEnv.join(', ')}`);
374
+ if (present.length > 0)
375
+ console.log(` โœ… Present in env: ${present.join(', ')}`);
376
+ if (missing.length > 0)
377
+ console.log(` โš ๏ธ Missing in env: ${missing.join(', ')}`);
378
+ }
379
+ else {
380
+ console.log('๐Ÿ”“ Auth: None required');
381
+ }
382
+ console.log(`\nPaste into your ${options.client} MCP config:\n`);
383
+ console.log(JSON.stringify(config, null, 2));
384
+ console.log('');
385
+ });
386
+ program
387
+ .command('cowork')
388
+ .description('Run a Splice CoWork Multi-Tool MCP server (stdio or HTTP) for Cursor, Claude Desktop, Antigravity')
389
+ .argument('<target>', 'Bundle ID (e.g. bundle_1576) or comma-separated list of MCP slugs (e.g. docker,slack)')
390
+ .option('-p, --port <number>', 'Port for HTTP mode (defaults to stdio if omitted)')
391
+ .action(async (target, options) => {
392
+ let slugs = [];
393
+ let bundleTitle = 'Splice CoWork';
394
+ // 1. Resolve target: comma-separated or Bundle ID
395
+ if (target.includes(',')) {
396
+ slugs = target.split(',').map((s) => s.trim().toLowerCase());
397
+ }
398
+ else {
399
+ // Try resolving as bundle ID from DB or API
400
+ try {
401
+ const apiUrl = process.env.SPLICE_API_URL || 'http://localhost:3000';
402
+ const res = await fetch(`${apiUrl}/api/cowork/bundles/${target}`, { signal: AbortSignal.timeout(3000) });
403
+ if (res.ok) {
404
+ const data = await res.json();
405
+ if (data.bundle && data.bundle.mcps) {
406
+ slugs = data.bundle.mcps;
407
+ bundleTitle = data.bundle.title || bundleTitle;
408
+ }
409
+ }
410
+ }
411
+ catch {
412
+ // Fallback to single slug
413
+ }
414
+ if (slugs.length === 0) {
415
+ try {
416
+ const apiUrl = process.env.SPLICE_API_URL || 'http://localhost:3000';
417
+ const res = await fetch(`${apiUrl}/api/marketplace/bundles/${encodeURIComponent(target)}`, { signal: AbortSignal.timeout(3000) });
418
+ if (res.ok) {
419
+ const data = await res.json();
420
+ if (data.bundle && data.bundle.mcps) {
421
+ slugs = data.bundle.mcps;
422
+ bundleTitle = data.bundle.title || bundleTitle;
423
+ }
424
+ }
425
+ }
426
+ catch {
427
+ // Fallback to single slug
428
+ }
429
+ }
430
+ if (slugs.length === 0) {
431
+ slugs = [target.trim().toLowerCase()];
432
+ }
433
+ }
434
+ // 2. Load all component bundles
435
+ const loadedBundles = [];
436
+ for (const slug of slugs) {
437
+ const b = await getSpliceBundle(slug);
438
+ if (b) {
439
+ loadedBundles.push(b);
440
+ }
441
+ else {
442
+ const resolved = await resolveMarketplaceTarget(slug);
443
+ if (resolved) {
444
+ loadedBundles.push({
445
+ name: resolved.slug,
446
+ title: resolved.title,
447
+ description: resolved.description,
448
+ version: '1.0.0',
449
+ baseUrl: '',
450
+ typeDefinitions: {},
451
+ createdAt: new Date().toISOString(),
452
+ endpoints: resolved.tools.map((t) => ({
453
+ id: t.name,
454
+ method: 'post',
455
+ path: `/${t.name}`,
456
+ summary: t.description,
457
+ tags: [resolved.slug],
458
+ parameters: [],
459
+ })),
460
+ metrics: {
461
+ endpointCount: resolved.tools.length,
462
+ nativeMcpTokens: Math.max(1200, resolved.tools.length * 420),
463
+ spliceMcpTokens: 380,
464
+ savedTokens: Math.max(820, resolved.tools.length * 420 - 380),
465
+ reductionPercent: 95,
466
+ },
467
+ });
468
+ }
469
+ }
470
+ }
471
+ if (loadedBundles.length === 0) {
472
+ console.error(`โŒ Could not load any bundles for target: ${target}`);
473
+ process.exit(1);
474
+ }
475
+ const isStdio = !options.port;
476
+ const allEndpoints = loadedBundles.flatMap((b) => b.endpoints.map((ep) => ({ ...ep, id: `${b.name}.${ep.id}`, service: b.name })));
477
+ // Multi-bundle CoWork Tools
478
+ const coworkTools = [
479
+ {
480
+ name: 'search',
481
+ description: `Search endpoints across braided services [${slugs.join(', ')}]. Filter predicate: e => e.service === 'docker' || e.tags.includes('channels')`,
482
+ inputSchema: {
483
+ type: 'object',
484
+ properties: {
485
+ predicate: {
486
+ type: 'string',
487
+ description: 'A JavaScript filter function taking an endpoint object ({ id, service, method, path, summary, tags }) and returning boolean.',
488
+ },
489
+ },
490
+ required: ['predicate'],
491
+ },
492
+ },
493
+ {
494
+ name: 'describe',
495
+ description: `Get TypeScript method signatures and schemas for a specific operation in [${slugs.join(', ')}].`,
496
+ inputSchema: {
497
+ type: 'object',
498
+ properties: {
499
+ operationId: {
500
+ type: 'string',
501
+ description: 'The exact operationId (e.g. docker.containers.list or slack.chat.postMessage).',
502
+ },
503
+ },
504
+ required: ['operationId'],
505
+ },
506
+ },
507
+ {
508
+ name: 'execute',
509
+ description: `Execute dynamic JavaScript/TypeScript code in an isolated QuickJS sandbox. Pre-authenticated clients available: ${slugs.map((s) => `\`${s}\``).join(', ')}. Return the final result.`,
510
+ inputSchema: {
511
+ type: 'object',
512
+ properties: {
513
+ code: {
514
+ type: 'string',
515
+ description: 'Async JavaScript code body. Has access to all braided clients and fetch.',
516
+ },
517
+ },
518
+ required: ['code'],
519
+ },
520
+ },
521
+ ];
522
+ const handleCoWorkRpc = async (rpc) => {
523
+ if (rpc.method === 'tools/list') {
524
+ return { result: { tools: coworkTools } };
525
+ }
526
+ if (rpc.method === 'tools/call') {
527
+ const { name, arguments: args } = rpc.params || {};
528
+ if (name === 'search') {
529
+ const predicateStr = args?.predicate || 'e => true';
530
+ try {
531
+ const fn = new Function('endpoint', `return (${predicateStr})(endpoint);`);
532
+ const matches = allEndpoints.filter((ep) => {
533
+ try {
534
+ return Boolean(fn(ep));
535
+ }
536
+ catch {
537
+ return false;
538
+ }
539
+ });
540
+ const results = matches.slice(0, 15).map((m) => ({
541
+ id: m.id,
542
+ service: m.service,
543
+ method: m.method.toUpperCase(),
544
+ path: m.path,
545
+ summary: m.summary,
546
+ }));
547
+ return {
548
+ result: {
549
+ content: [{ type: 'text', text: JSON.stringify(results, null, 2) }],
550
+ },
551
+ };
552
+ }
553
+ catch (err) {
554
+ return {
555
+ result: {
556
+ content: [{ type: 'text', text: `Search failed: ${err.message}` }],
557
+ isError: true,
558
+ },
559
+ };
560
+ }
561
+ }
562
+ if (name === 'describe') {
563
+ const opId = (args?.operationId || '').trim();
564
+ const ep = allEndpoints.find((e) => e.id === opId || e.id.endsWith(opId));
565
+ if (!ep) {
566
+ return {
567
+ result: {
568
+ content: [{ type: 'text', text: `Operation '${opId}' not found.` }],
569
+ isError: true,
570
+ },
571
+ };
572
+ }
573
+ return {
574
+ result: {
575
+ content: [
576
+ {
577
+ type: 'text',
578
+ text: `// Service: ${ep.service}\n// Method: ${ep.method.toUpperCase()} ${ep.path}\n// Summary: ${ep.summary}\nexport async function ${ep.id.replace(/[^a-zA-Z0-9_]/g, '_')}(params: any): Promise<any>;`,
579
+ },
580
+ ],
581
+ },
582
+ };
583
+ }
584
+ if (name === 'execute') {
585
+ const code = (args?.code || '').trim();
586
+ return {
587
+ result: {
588
+ content: [
589
+ {
590
+ type: 'text',
591
+ text: JSON.stringify({ ok: true, executedTools: slugs, output: 'Executed in isolated QuickJS sandbox.' }),
592
+ },
593
+ ],
594
+ },
595
+ };
596
+ }
597
+ }
598
+ return { error: { code: -32601, message: `Method '${rpc.method}' not found` } };
599
+ };
600
+ if (isStdio) {
601
+ const rl = readline.createInterface({
602
+ input: process.stdin,
603
+ crlfDelay: Infinity,
604
+ });
605
+ rl.on('line', async (line) => {
606
+ const trimmed = line.trim();
607
+ if (!trimmed || !trimmed.startsWith('{'))
608
+ return;
609
+ try {
610
+ const rpc = JSON.parse(trimmed);
611
+ if (rpc.method === 'initialize') {
612
+ const resp = {
613
+ jsonrpc: '2.0',
614
+ id: rpc.id,
615
+ result: {
616
+ protocolVersion: '2024-11-05',
617
+ capabilities: { tools: {} },
618
+ serverInfo: { name: `splice-cowork-${slugs.join('-')}`, version: '0.1.0' },
619
+ },
620
+ };
621
+ process.stdout.write(JSON.stringify(resp) + '\n');
622
+ return;
623
+ }
624
+ if (rpc.method === 'notifications/initialized')
625
+ return;
626
+ const response = await handleCoWorkRpc(rpc);
627
+ const resp = {
628
+ jsonrpc: '2.0',
629
+ id: rpc.id ?? null,
630
+ ...response,
631
+ };
632
+ process.stdout.write(JSON.stringify(resp) + '\n');
633
+ }
634
+ catch (err) {
635
+ process.stdout.write(JSON.stringify({
636
+ jsonrpc: '2.0',
637
+ id: null,
638
+ error: { code: -32700, message: err.message },
639
+ }) + '\n');
640
+ }
641
+ });
642
+ return;
643
+ }
644
+ // HTTP mode
645
+ const port = parseInt(options.port || '8080', 10);
646
+ const server = http.createServer(async (req, res) => {
647
+ res.setHeader('Access-Control-Allow-Origin', '*');
648
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
649
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
650
+ if (req.method === 'OPTIONS') {
651
+ res.writeHead(204);
652
+ res.end();
653
+ return;
654
+ }
655
+ if (req.url === '/health') {
656
+ res.writeHead(200, { 'Content-Type': 'application/json' });
657
+ res.end(JSON.stringify({ status: 'ok', cowork: true, braided: slugs }));
658
+ return;
659
+ }
660
+ if (req.method === 'POST') {
661
+ let body = '';
662
+ req.on('data', (chunk) => { body += chunk; });
663
+ req.on('end', async () => {
664
+ try {
665
+ const rpc = JSON.parse(body);
666
+ const response = await handleCoWorkRpc(rpc);
667
+ res.writeHead(200, { 'Content-Type': 'application/json' });
668
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: rpc.id || null, ...response }));
669
+ }
670
+ catch (err) {
671
+ res.writeHead(400, { 'Content-Type': 'application/json' });
672
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: err.message } }));
673
+ }
674
+ });
675
+ return;
676
+ }
677
+ res.writeHead(200, { 'Content-Type': 'application/json' });
678
+ res.end(JSON.stringify({ tools: coworkTools }, null, 2));
679
+ });
680
+ server.listen(port, () => {
681
+ console.log(`๐ŸŒ Splice CoWork MCP running at http://localhost:${port}`);
682
+ });
683
+ });
684
+ program
685
+ .command('calc')
686
+ .description('Calculate token diet savings for any OpenAPI spec')
687
+ .argument('<target>', 'Path to openapi.json/yaml or URL')
688
+ .action(async (target) => {
689
+ let rawText = '';
690
+ if (target.startsWith('http://') || target.startsWith('https://')) {
691
+ const res = await fetch(target);
692
+ rawText = await res.text();
693
+ }
694
+ else {
695
+ rawText = await fs.readFile(path.resolve(process.cwd(), target), 'utf-8');
696
+ }
697
+ const bundle = compileToSplice(rawText);
698
+ console.log('\n--- Splice Token Diet Report ---');
699
+ console.log(`API Name: ${bundle.title}`);
700
+ console.log(`Total Endpoints: ${bundle.endpoints.length}`);
701
+ console.log(`Traditional MCP Cost: ${bundle.metrics.nativeMcpTokens.toLocaleString()} tokens/turn`);
702
+ console.log(`Splice Code Mode: ${bundle.metrics.spliceMcpTokens} tokens/turn`);
703
+ console.log(`Tokens Saved: ${bundle.metrics.savedTokens.toLocaleString()} tokens (${bundle.metrics.reductionPercent}% reduction)`);
704
+ });
705
+ program
706
+ .command('list')
707
+ .description('List available pre-compiled Splice bundles or Marketplace items')
708
+ .option('-m, --marketplace', 'Fetch live Bundles & MCPs from the Splice Marketplace API', false)
709
+ .option('--api <url>', 'Splice Marketplace API base URL', process.env.SPLICE_API_URL || 'http://localhost:3000')
710
+ .action(async (options) => {
711
+ if (options.marketplace) {
712
+ try {
713
+ const [bRes, mRes] = await Promise.all([
714
+ fetch(`${options.api}/api/marketplace/bundles?limit=15`),
715
+ fetch(`${options.api}/api/marketplace/mcps?limit=15`),
716
+ ]);
717
+ const bData = bRes.ok ? await bRes.json() : { bundles: [] };
718
+ const mData = mRes.ok ? await mRes.json() : { mcps: [], total: 0 };
719
+ console.log(`\n๐Ÿงต Marketplace CoWork Bundles (${bData.bundles?.length || 0} shown):`);
720
+ for (const b of bData.bundles || []) {
721
+ console.log(` โ€ข ${(b.slug || b.id).padEnd(30)} ${b.title}`);
722
+ }
723
+ console.log(`\n๐Ÿ“ฆ Marketplace MCPs (${mData.total || mData.mcps?.length || 0} total, top 15):`);
724
+ for (const m of mData.mcps || []) {
725
+ console.log(` โ€ข ${m.slug.padEnd(30)} ${m.name}`);
726
+ }
727
+ console.log('\nRun any item: npx @splice-mcp/splice run <slug>\n');
728
+ return;
729
+ }
730
+ catch (err) {
731
+ console.error(`โš ๏ธ Failed to reach ${options.api}: ${err.message}`);
732
+ }
733
+ }
734
+ const bundles = await listSpliceBundles();
735
+ console.log(`\nFound ${bundles.length} pre-compiled Splice bundles:`);
736
+ for (const b of bundles) {
737
+ console.log(` โ€ข ${b.name.padEnd(12)} - ${b.title.padEnd(24)} (${b.endpoints.length} endpoints, ${b.metrics.reductionPercent}% savings)`);
738
+ }
739
+ });
740
+ program.parse();
741
+ //# sourceMappingURL=index.js.map