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