-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathindex.ts
More file actions
910 lines (820 loc) · 29.5 KB
/
index.ts
File metadata and controls
910 lines (820 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
#!/usr/bin/env node
/**
* Main CLI entry point for mcpc
* Handles command parsing, routing, and output formatting
*/
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
import { initProxy } from '../lib/proxy.js';
import { Command } from 'commander';
import { setVerbose, setJsonMode, closeFileLogger } from '../lib/index.js';
import { isMcpError, formatHumanError, ClientError } from '../lib/index.js';
import chalk from 'chalk';
import { formatJson, formatJsonError, rainbow } from './output.js';
import * as tools from './commands/tools.js';
import * as resources from './commands/resources.js';
import * as prompts from './commands/prompts.js';
import * as sessions from './commands/sessions.js';
import * as logging from './commands/logging.js';
import * as utilities from './commands/utilities.js';
import * as auth from './commands/auth.js';
import * as tasks from './commands/tasks.js';
import { handleX402Command } from './commands/x402.js';
import { clean } from './commands/clean.js';
import type { OutputMode } from '../lib/index.js';
import {
extractOptions,
getVerboseFromEnv,
getJsonFromEnv,
validateOptions,
validateArgValues,
parseServerArg,
hasSubcommand,
optionTakesValue,
KNOWN_COMMANDS,
KNOWN_SESSION_COMMANDS,
} from './parser.js';
import { createRequire } from 'module';
const { version: mcpcVersion } = createRequire(import.meta.url)('../../package.json') as {
version: string;
};
// Set up HTTP proxy from environment variables (HTTPS_PROXY, HTTP_PROXY, NO_PROXY, and lowercase variants)
// Also handle --insecure flag to disable TLS certificate verification (for self-signed certs)
{
const insecure = process.argv.includes('--insecure');
initProxy({ insecure });
}
/**
* Options passed to command handlers
*/
interface HandlerOptions {
outputMode: OutputMode;
headers?: string[];
timeout?: number;
verbose?: boolean;
profile?: string;
noProfile?: boolean;
x402?: boolean;
insecure?: boolean;
schema?: string;
schemaMode?: 'strict' | 'compatible' | 'ignore';
full?: boolean;
}
/**
* Extract options from Commander's Command object
* Used by command handlers to get parsed options in consistent format
* Environment variables MCPC_VERBOSE and MCPC_JSON are used as defaults
*/
function getOptionsFromCommand(command: Command): HandlerOptions {
const opts = command.optsWithGlobals ? command.optsWithGlobals() : command.opts();
// Check for verbose from flag or environment variable
const verbose = opts.verbose || getVerboseFromEnv();
if (verbose) setVerbose(true);
// Check for JSON mode from flag or environment variable
const json = opts.json || getJsonFromEnv();
if (json) setJsonMode(true);
const options: HandlerOptions = {
outputMode: (json ? 'json' : 'human') as OutputMode,
};
// Only include optional properties if they're present
if (opts.timeout) {
const timeout = parseInt(opts.timeout as string, 10);
if (isNaN(timeout) || timeout <= 0) {
throw new Error(
`Invalid --timeout value: "${opts.timeout as string}". Must be a positive number (seconds).`
);
}
options.timeout = timeout;
}
if (opts.profile === false) {
options.noProfile = true;
} else if (opts.profile) {
options.profile = opts.profile;
}
if (verbose) options.verbose = verbose;
if (opts.x402) options.x402 = true;
if (opts.insecure) options.insecure = true;
if (opts.schema) options.schema = opts.schema;
if (opts.schemaMode) {
const mode = opts.schemaMode as string;
if (mode !== 'strict' && mode !== 'compatible' && mode !== 'ignore') {
throw new Error(
`Invalid --schema-mode value: "${mode}". Valid modes are: strict, compatible, ignore`
);
}
options.schemaMode = mode;
}
if (opts.full) options.full = opts.full;
return options;
}
async function main(): Promise<void> {
const args = process.argv.slice(2);
// Set up cleanup handlers for graceful shutdown
const handleExit = (): void => {
void closeFileLogger().then(() => {
process.exit(0);
});
};
process.on('SIGTERM', handleExit);
process.on('SIGINT', handleExit);
process.on('exit', () => {
// Synchronous cleanup on exit (file logger handles this gracefully)
void closeFileLogger();
});
// Check for version flag - handle JSON output specially
if (args.includes('--version') || args.includes('-v')) {
const options = extractOptions(args);
if (options.json) {
setJsonMode(true);
console.log(formatJson({ version: mcpcVersion }));
} else {
console.log(mcpcVersion);
}
return;
}
// Check for help flag
// x402 has its own Commander program with full subcommand help, so pass --help through
if (args.includes('--help') || args.includes('-h')) {
if (args.includes('x402')) {
const x402Index = args.indexOf('x402');
const x402Args = args.slice(x402Index + 1);
await handleX402Command(x402Args);
await closeFileLogger();
return;
}
const program = createTopLevelProgram();
await program.parseAsync(process.argv);
return;
}
// Validate all options are known (before any processing)
// Argument validation errors are always plain text - --json only applies to command output
try {
validateOptions(args);
validateArgValues(args);
} catch (error) {
console.error(chalk.red(formatHumanError(error as Error, false)));
process.exit(1);
}
// Find the first non-option argument to determine routing
let firstNonOption: string | undefined;
let firstNonOptionIndex = -1;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (!arg) continue;
if (arg.startsWith('-')) {
if (optionTakesValue(arg) && !arg.includes('=') && i + 1 < args.length) {
i++; // skip value
}
continue;
}
firstNonOption = arg;
firstNonOptionIndex = i;
break;
}
// No args → list sessions
if (!firstNonOption) {
const { json } = extractOptions(args);
if (json) setJsonMode(true);
await sessions.listSessionsAndAuthProfiles({ outputMode: json ? 'json' : 'human' });
if (!json) {
console.log('\nRun "mcpc --help" for usage information.\n');
}
await closeFileLogger();
return;
}
// Session command: @name [subcommand]
if (firstNonOption.startsWith('@')) {
const session = firstNonOption;
const modifiedArgs = [
...process.argv.slice(0, 2),
...args.slice(0, firstNonOptionIndex),
...args.slice(firstNonOptionIndex + 1),
];
try {
await handleSessionCommands(session, modifiedArgs);
} catch (error) {
if (isMcpError(error)) {
const opts = extractOptions(args);
const outputMode: OutputMode = opts.json ? 'json' : 'human';
if (outputMode === 'json') {
console.error(formatJsonError(error, error.code));
} else {
console.error(chalk.red(formatHumanError(error, opts.verbose)));
}
process.exit(error.code);
}
throw error;
} finally {
await closeFileLogger();
}
// Flush stdout before exiting
await flushStdout();
process.exit(0);
}
// Top-level commands: login, logout, connect, clean, help, x402
if (KNOWN_COMMANDS.includes(firstNonOption)) {
// Handle x402 separately (legacy standalone handler)
if (firstNonOption === 'x402') {
const x402Args = args.slice(firstNonOptionIndex + 1);
await handleX402Command(x402Args);
await closeFileLogger();
return;
}
try {
const program = createTopLevelProgram();
await program.parseAsync(process.argv);
} catch (error) {
if (isMcpError(error)) {
const opts = extractOptions(args);
const outputMode: OutputMode = opts.json ? 'json' : 'human';
if (outputMode === 'json') {
console.error(formatJsonError(error, error.code));
} else {
console.error(chalk.red(formatHumanError(error, opts.verbose)));
}
process.exit(error.code);
}
throw error;
} finally {
await closeFileLogger();
}
return;
}
// Unknown command — provide helpful error
const opts = extractOptions(args);
const outputMode: OutputMode = opts.json ? 'json' : 'human';
const allCommands = [...KNOWN_COMMANDS, ...KNOWN_SESSION_COMMANDS];
if (allCommands.includes(firstNonOption)) {
// It's a session subcommand used without @session
if (outputMode === 'json') {
console.error(
formatJsonError(new Error(`Missing session target for command: ${firstNonOption}`), 1)
);
} else {
console.error(`Error: Missing session target for command: ${firstNonOption}`);
console.error(`\nDid you mean: mcpc <@session> ${firstNonOption}`);
console.error(`Run "mcpc --help" for usage information.\n`);
}
} else {
if (outputMode === 'json') {
console.error(formatJsonError(new Error(`Unknown command: ${firstNonOption}`), 1));
} else {
console.error(`Error: Unknown command: ${firstNonOption}`);
console.error(`Run "mcpc --help" for usage information.\n`);
}
}
await closeFileLogger();
process.exit(1);
}
/**
* Create the top-level Commander program with global commands
* (login, logout, connect, clean, help)
*/
function createTopLevelProgram(): Command {
const program = new Command();
// Configure help output width to avoid wrapping (default is 80)
program.configureOutput({
outputError: (str, write) => write(str),
getOutHelpWidth: () => 100,
getErrHelpWidth: () => 100,
});
// Strip [options] from the commands list (options are shown per-command via `mcpc help <cmd>`)
program.configureHelp({
subcommandTerm: (cmd) =>
`${cmd.name()} ${cmd.usage()}`.replace(/^\[options\]\s*|\s*\[options\]/g, '').trim(),
styleTitle: (str) => chalk.bold(str),
styleSubcommandText: (str) => chalk.cyan(str),
});
// Use raw Markdown URL for pipes (AI agents), GitHub UI for TTY (humans)
const docsUrl = process.stdout.isTTY
? `https://github.com/apify/mcpc/tree/v${mcpcVersion}`
: `https://raw.githubusercontent.com/apify/mcpc/v${mcpcVersion}/README.md`;
program
.name('mcpc')
.description(
`${rainbow('Universal')} command-line client for the Model Context Protocol (MCP).`
)
.usage('[options] [<@session>] [<command>]')
.option('-j, --json', 'Output in JSON format for scripting')
.option('--verbose', 'Enable debug logging')
.option('--profile <name>', 'OAuth profile for the server ("default" if not provided)')
.option('--schema <file>', 'Validate tool/prompt schema against expected schema')
.option('--schema-mode <mode>', 'Schema validation mode: strict, compatible (default), ignore')
.option('--timeout <seconds>', 'Request timeout in seconds (default: 300)')
.option('--insecure', 'Skip TLS certificate verification (for self-signed certs)')
.version(mcpcVersion, '-v, --version', 'Output the version number')
.helpOption('-h, --help', 'Display help');
program.addHelpText(
'after',
`
${chalk.bold('MCP session commands (after connecting):')}
<@session> Show MCP server info and capabilities
<@session> ${chalk.cyan('tools-list')} List MCP server tools
<@session> ${chalk.cyan('tools-get')} <name> Get tool details and schema
<@session> ${chalk.cyan('tools-call')} <name> [arg:=val ... | <json> | <stdin]
<@session> ${chalk.cyan('prompts-list')}
<@session> ${chalk.cyan('prompts-get')} <name> [arg:=val ... | <json> | <stdin]
<@session> ${chalk.cyan('resources-list')}
<@session> ${chalk.cyan('resources-read')} <uri>
<@session> ${chalk.cyan('resources-subscribe')} <uri>
<@session> ${chalk.cyan('resources-unsubscribe')} <uri>
<@session> ${chalk.cyan('resources-templates-list')}
<@session> ${chalk.cyan('tasks-list')}
<@session> ${chalk.cyan('tasks-get')} <taskId>
<@session> ${chalk.cyan('tasks-cancel')} <taskId>
<@session> ${chalk.cyan('logging-set-level')} <level>
<@session> ${chalk.cyan('ping')}
Run "mcpc" without arguments to show active sessions and OAuth profiles.
Full docs: ${docsUrl}`
);
// connect command: mcpc connect <server> @<name>
program
.command('connect [server] [@session]')
.usage('<server> <@session>')
.description('Connect to an MCP server and start a new named @session')
.option('-H, --header <header>', 'HTTP header (can be repeated)')
.option('--profile <name>', 'OAuth profile to use ("default" if skipped)')
.option('--no-profile', 'Skip OAuth profile (connect anonymously)')
.option('--proxy <[host:]port>', 'Start proxy MCP server for session')
.option('--proxy-bearer-token <token>', 'Require authentication for access to proxy server')
.option('--x402', 'Enable x402 auto-payment using the configured wallet')
.addHelpText(
'after',
`
${chalk.bold('Server formats:')}
mcp.apify.com Remote HTTP server (https:// added automatically)
~/.vscode/mcp.json:puppeteer Config file entry (file:entry)
`
)
.action(async (server, sessionName, opts, command) => {
if (!server) {
throw new ClientError(
'Missing required argument: server\n\nExample: mcpc connect mcp.apify.com @myapp'
);
}
if (!sessionName) {
throw new ClientError(
'Missing required argument: @session\n\nExample: mcpc connect mcp.apify.com @myapp'
);
}
const globalOpts = getOptionsFromCommand(command);
const parsed = parseServerArg(server);
// Extract --header from connect-specific opts
const headers: string[] | undefined = opts.header
? Array.isArray(opts.header)
? (opts.header as string[])
: [opts.header as string]
: undefined;
if (!parsed) {
throw new ClientError(
`Invalid server: "${server}"\n\n` +
`Expected a URL (e.g. mcp.apify.com) or a config file entry (e.g. ~/.vscode/mcp.json:filesystem)`
);
}
if (parsed.type === 'config') {
// Config file entry: pass entry name as target with config file path
await sessions.connectSession(parsed.entry, sessionName, {
...globalOpts,
...(headers && { headers }),
config: parsed.file,
proxy: opts.proxy,
proxyBearerToken: opts.proxyBearerToken,
x402: opts.x402,
...(globalOpts.insecure && { insecure: true }),
});
} else {
await sessions.connectSession(server, sessionName, {
...globalOpts,
...(headers && { headers }),
proxy: opts.proxy,
proxyBearerToken: opts.proxyBearerToken,
x402: opts.x402,
...(globalOpts.insecure && { insecure: true }),
});
}
});
// close command: mcpc close @<session>
program
.command('close [@session]')
.usage('<@session>')
.description('Close a session')
.action(async (sessionName, _opts, command) => {
if (!sessionName) {
throw new ClientError('Missing required argument: @session\n\nExample: mcpc close @myapp');
}
await sessions.closeSession(sessionName, getOptionsFromCommand(command));
});
// restart command: mcpc restart @<session>
program
.command('restart [@session]')
.usage('<@session>')
.description('Restart a session (losing all state)')
.action(async (sessionName, _opts, command) => {
if (!sessionName) {
throw new ClientError(
'Missing required argument: @session\n\nExample: mcpc restart @myapp'
);
}
await sessions.restartSession(sessionName, getOptionsFromCommand(command));
});
// shell command: mcpc shell @<session>
program
.command('shell [@session]')
.usage('<@session>')
.description('Open interactive shell for a session')
.action(async (sessionName) => {
if (!sessionName) {
throw new ClientError('Missing required argument: @session\n\nExample: mcpc shell @myapp');
}
await sessions.openShell(sessionName);
});
// login command: mcpc login <server>
program
.command('login [server]')
.usage('<server>')
.description('Interactively login to a server using OAuth and save profile')
.option('--profile <name>', 'Profile name (default: "default")')
.option(
'--scope <scopes>',
'OAuth scopes to request, quoted and space-separated (e.g. --scope "read write")'
)
.option('--client-id <id>', 'OAuth client ID (for servers without dynamic client registration)')
.option(
'--client-secret <secret>',
'OAuth client secret (for servers without dynamic client registration)'
)
.action(async (server, opts, command) => {
if (!server) {
throw new ClientError(
'Missing required argument: server\n\nExample: mcpc login mcp.apify.com'
);
}
await auth.login(server, {
profile: opts.profile,
scope: opts.scope,
clientId: opts.clientId,
clientSecret: opts.clientSecret,
...getOptionsFromCommand(command),
});
});
// logout command: mcpc logout <server>
program
.command('logout [server]')
.usage('<server>')
.description('Delete an authentication profile for a server')
.option('--profile <name>', 'Profile name (default: "default")')
.action(async (server, opts, command) => {
if (!server) {
throw new ClientError(
'Missing required argument: server\n\nExample: mcpc logout mcp.apify.com'
);
}
await auth.logout(server, {
profile: opts.profile,
...getOptionsFromCommand(command),
});
});
// clean command: mcpc clean [resources...]
program
.command('clean [resources...]')
.description('Clean up mcpc data (sessions, profiles, logs, all)')
.addHelpText(
'after',
`
${chalk.bold('Resources:')}
sessions Remove stale/crashed session records
profiles Remove authentication profiles
logs Remove bridge log files
all Remove all of the above
Without arguments, performs safe cleanup of stale data only.
`
)
.action(async (resources: string[], _opts, command) => {
const globalOpts = getOptionsFromCommand(command);
// Validate clean types
const VALID_CLEAN_TYPES = ['sessions', 'profiles', 'logs', 'all'];
for (const r of resources) {
if (!VALID_CLEAN_TYPES.includes(r)) {
throw new ClientError(
`Invalid clean resource: "${r}". Valid resources are: ${VALID_CLEAN_TYPES.join(', ')}`
);
}
}
await clean({
outputMode: globalOpts.outputMode,
sessions: resources.includes('sessions'),
profiles: resources.includes('profiles'),
logs: resources.includes('logs'),
all: resources.includes('all'),
});
});
// x402 command: mcpc x402 <subcommand>
// Note: x402 is handled before Commander in main() — this registration exists only for help text
program
.command('x402 [subcommand] [args...]')
.description('Configure an x402 payment wallet (EXPERIMENTAL)')
// eslint-disable-next-line @typescript-eslint/no-empty-function
.action(() => {});
// help command: mcpc help [command] (supports "help x402 sign" etc.)
program
.command('help [command] [subcommand]')
.description('Show help for a specific command')
.action(async (cmdName?: string, subcommand?: string) => {
if (!cmdName) {
program.outputHelp();
return;
}
// x402 has its own Commander program with full subcommand help
if (cmdName === 'x402') {
const helpArgs = subcommand ? [subcommand, '--help'] : ['--help'];
await handleX402Command(helpArgs);
return;
}
// Check top-level commands
const topLevelCmd = program.commands.find(
(c) => c.name() === cmdName || c.aliases().includes(cmdName)
);
if (topLevelCmd) {
topLevelCmd.outputHelp();
return;
}
// Check session subcommands
const dummyProgram = new Command();
registerSessionCommands(dummyProgram, '@dummy');
const sessionCmd = dummyProgram.commands.find(
(c) => c.name() === cmdName || c.aliases().includes(cmdName)
);
if (sessionCmd) {
sessionCmd.outputHelp();
return;
}
console.error(`Unknown command: ${cmdName}`);
console.error(`Run "mcpc --help" for usage information.`);
process.exit(1);
});
// Default action (no args) — list sessions
program.action(async () => {
const opts = program.opts();
const json = opts.json || getJsonFromEnv();
if (json) setJsonMode(true);
await sessions.listSessionsAndAuthProfiles({ outputMode: json ? 'json' : 'human' });
if (!json) {
console.log('\nRun "mcpc --help" for usage information.\n');
}
});
return program;
}
/**
* Register all session subcommands on a Commander program
* Extracted so it can be reused for both execution and help lookup
*/
function registerSessionCommands(program: Command, session: string): void {
// Help command
program
.command('help')
.description('Show server instructions and available capabilities')
.action(async (_options, command) => {
await sessions.showHelp(session, getOptionsFromCommand(command));
});
// Shell command
program
.command('shell')
.description('Interactive shell for the session')
.action(async () => {
await sessions.openShell(session);
});
// Close command
program
.command('close', { hidden: true })
.description('Close the session')
.action(async (_options, command) => {
await sessions.closeSession(session, getOptionsFromCommand(command));
});
// Restart command
program
.command('restart')
.description('Restart the session (stop and start the bridge)')
.action(async (_options, command) => {
await sessions.restartSession(session, getOptionsFromCommand(command));
});
// Tools commands
program
.command('tools')
.description('List available tools (shorthand for tools-list)')
.option('--full', 'Show full tool details including complete input schema')
.action(async (_options, command) => {
await tools.listTools(session, getOptionsFromCommand(command));
});
program
.command('tools-list')
.description('List available tools')
.option('--full', 'Show full tool details including complete input schema')
.action(async (_options, command) => {
await tools.listTools(session, getOptionsFromCommand(command));
});
program
.command('tools-get <name>')
.description('Get information about a specific tool')
.action(async (name, _options, command) => {
await tools.getTool(session, name, getOptionsFromCommand(command));
});
program
.command('tools-call <name> [args...]')
.description('Call a tool with arguments (key:=value pairs or JSON)')
.option('--task', 'Use task execution (experimental)')
.option('--detach', 'Start task and return immediately with task ID (implies --task)')
.action(async (name, args, options, command) => {
await tools.callTool(session, name, {
args,
task: options.task,
detach: options.detach,
...getOptionsFromCommand(command),
});
});
// Tasks commands
program
.command('tasks-list')
.description('List active tasks')
.action(async (_options, command) => {
await tasks.listTasks(session, getOptionsFromCommand(command));
});
program
.command('tasks-get <taskId>')
.description('Get status of a specific task')
.action(async (taskId, _options, command) => {
await tasks.getTask(session, taskId, getOptionsFromCommand(command));
});
program
.command('tasks-cancel <taskId>')
.description('Cancel a running task')
.action(async (taskId, _options, command) => {
await tasks.cancelTask(session, taskId, getOptionsFromCommand(command));
});
// Resources commands
program
.command('resources')
.description('List available resources (shorthand for resources-list)')
.action(async (_options, command) => {
await resources.listResources(session, getOptionsFromCommand(command));
});
program
.command('resources-list')
.description('List available resources')
.action(async (_options, command) => {
await resources.listResources(session, getOptionsFromCommand(command));
});
program
.command('resources-read <uri>')
.description('Get a resource by URI')
.option('-o, --output <file>', 'Write resource to file')
.option('--max-size <bytes>', 'Maximum resource size in bytes')
.action(async (uri, options, command) => {
await resources.getResource(session, uri, {
output: options.output,
maxSize: options.maxSize,
...getOptionsFromCommand(command),
});
});
program
.command('resources-subscribe <uri>')
.description('Subscribe to resource updates')
.action(async (uri, _options, command) => {
await resources.subscribeResource(session, uri, getOptionsFromCommand(command));
});
program
.command('resources-unsubscribe <uri>')
.description('Unsubscribe from resource updates')
.action(async (uri, _options, command) => {
await resources.unsubscribeResource(session, uri, getOptionsFromCommand(command));
});
program
.command('resources-templates-list')
.description('List available resource templates')
.action(async (_options, command) => {
await resources.listResourceTemplates(session, getOptionsFromCommand(command));
});
// Prompts commands
program
.command('prompts')
.description('List available prompts (shorthand for prompts-list)')
.action(async (_options, command) => {
await prompts.listPrompts(session, getOptionsFromCommand(command));
});
program
.command('prompts-list')
.description('List available prompts')
.action(async (_options, command) => {
await prompts.listPrompts(session, getOptionsFromCommand(command));
});
program
.command('prompts-get <name> [args...]')
.description('Get a prompt by name with arguments (key:=value pairs or JSON)')
.action(async (name, args, _options, command) => {
await prompts.getPrompt(session, name, {
args,
...getOptionsFromCommand(command),
});
});
// Logging commands
program
.command('logging-set-level <level>')
.description(
'Set server logging level (debug, info, notice, warning, error, critical, alert, emergency)'
)
.action(async (level, _options, command) => {
await logging.setLogLevel(session, level, getOptionsFromCommand(command));
});
// Server commands
program
.command('ping')
.description('Ping the MCP server to check if it is alive')
.action(async (_options, command) => {
await utilities.ping(session, getOptionsFromCommand(command));
});
}
/**
* Create a Commander program for session subcommands
* Separate from top-level program to avoid command name conflicts
*/
function createSessionProgram(): Command {
const program = new Command();
program.configureOutput({
outputError: (str, write) => write(str),
getOutHelpWidth: () => 100,
getErrHelpWidth: () => 100,
});
program
.name('mcpc <@session>')
.helpOption('-h, --help', 'Display help')
.option('-j, --json', 'Output in JSON format for scripting and code mode')
.option('--verbose', 'Enable debug logging')
.option('--profile <name>', 'OAuth profile override')
.option('--schema <file>', 'Validate tool/prompt schema against expected schema')
.option('--schema-mode <mode>', 'Schema validation mode: strict, compatible (default), ignore')
.option('--timeout <seconds>', 'Request timeout in seconds (default: 300)')
.option('--insecure', 'Skip TLS certificate verification (for self-signed certs)');
return program;
}
/**
* Handle commands for a session target (@name)
*/
async function handleSessionCommands(session: string, args: string[]): Promise<void> {
// Check if no subcommand provided - show server info
if (!hasSubcommand(args)) {
const options = extractOptions(args);
if (options.verbose) setVerbose(true);
if (options.json) setJsonMode(true);
await sessions.showServerDetails(session, {
outputMode: options.json ? 'json' : 'human',
...(options.verbose && { verbose: true }),
...(options.timeout !== undefined && { timeout: options.timeout }),
});
return;
}
const program = createSessionProgram();
// Register all session subcommands
registerSessionCommands(program, session);
// Parse and execute
try {
await program.parseAsync(args);
} catch (error) {
const opts = program.opts();
const outputMode: OutputMode = opts.json ? 'json' : 'human';
if (isMcpError(error)) {
if (outputMode === 'json') {
console.error(formatJsonError(error, error.code));
} else {
console.error(chalk.red(formatHumanError(error, opts.verbose)));
}
process.exit(error.code);
}
// Unknown error
console.error(
outputMode === 'json'
? formatJsonError(error as Error, 1)
: chalk.red(formatHumanError(error as Error, opts.verbose))
);
process.exit(1);
}
}
/**
* Flush stdout before exiting to prevent truncation with pipes
*/
async function flushStdout(): Promise<void> {
await new Promise<void>((resolve) => {
if (process.stdout.writableFinished) {
resolve();
} else {
process.stdout.once('finish', resolve);
process.stdout.end();
}
});
}
// Run main function
main().catch(async (error) => {
console.error('Fatal error:', error);
await closeFileLogger();
process.exit(1);
});