-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathindex.ts
More file actions
1718 lines (1582 loc) · 65.3 KB
/
Copy pathindex.ts
File metadata and controls
1718 lines (1582 loc) · 65.3 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Main CLI entry point for mcpc
* Handles command parsing, routing, and output formatting
*/
import { initProxy } from '../lib/proxy.js';
import { Command, CommanderError, Help } 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, jsonHelp, rainbow, theme } from './output.js';
import {
SCHEMA_BASE,
LEGACY_SCHEMA_BASE,
SESSION_DETAILS_HELP,
outputHelp,
serverDetailsJsonHelp,
} from './help-text.js';
import * as tools from './commands/tools.js';
import * as resources from './commands/resources.js';
import * as skills from './commands/skills.js';
import * as help from './commands/help.js';
import * as prompts from './commands/prompts.js';
import * as sessions from './commands/sessions.js';
import * as connect from './commands/connect.js';
import * as logging from './commands/logging.js';
import * as utilities from './commands/utilities.js';
import * as logs from './commands/logs.js';
import * as auth from './commands/auth.js';
import * as tasks from './commands/tasks.js';
import * as grepCmd from './commands/grep.js';
import { clean } from './commands/clean.js';
import { MCPC_OAUTH_CALLBACK_HOSTS, MCPC_OAUTH_CALLBACK_PORTS } from '../lib/auth/oauth-utils.js';
import type { OutputMode, X402SchemePreference } from '../lib/index.js';
import { X402_SCHEME_PREFERENCES } from '../lib/index.js';
import {
extractOptions,
preProcessX402Argv,
getVerboseFromEnv,
getJsonFromEnv,
validateOptions,
validateArgValues,
parseServerArg,
hasSubcommand,
optionTakesValue,
suggestCommand,
normalizeSlashCommand,
normalizeSlashCommandArgs,
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');
await initProxy({ insecure });
}
/**
* The x402 command module pulls in the bundled viem (~1 MB of crypto code),
* so load it only when an x402 command actually runs — every other command
* would otherwise pay the import cost at startup.
*/
async function handleX402Command(args: string[]): Promise<void> {
const { handleX402Command: run } = await import('./commands/x402.js');
await run(args);
}
/**
* Options passed to command handlers
*/
interface HandlerOptions {
outputMode: OutputMode;
headers?: string[];
timeoutSecs?: number; // Per-request timeout in seconds (from --timeout)
verbose?: boolean;
profile?: string;
noProfile?: boolean;
/**
* x402 scheme preference. Presence enables x402 for the run; value is the preference.
* `--x402` (no value) resolves to `'auto'` (prefer upto, fall back to exact).
*/
x402?: X402SchemePreference;
insecure?: boolean;
schema?: string;
schemaMode?: 'strict' | 'compatible' | 'ignore';
full?: boolean;
maxChars?: number;
}
/**
* 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',
};
// Only include optional properties if they're present
if (opts.timeout) {
const timeoutSecs = parseInt(opts.timeout as string, 10);
if (isNaN(timeoutSecs) || timeoutSecs <= 0) {
throw new ClientError(
`Invalid --timeout value: "${opts.timeout as string}". Must be a positive number (seconds).`
);
}
options.timeoutSecs = timeoutSecs;
}
if (opts.profile === false) {
options.noProfile = true;
} else if (opts.profile) {
options.profile = opts.profile;
}
if (verbose) options.verbose = verbose;
// Commander returns `true` for `--x402` (no value) and a string for `--x402 <scheme>`.
// Normalise to the canonical scheme preference; reject other strings loudly so
// commander's greedy [optional] arg parser can't silently eat a positional like a URL.
if (opts.x402 === true) {
options.x402 = 'auto';
} else if (typeof opts.x402 === 'string') {
if (!(X402_SCHEME_PREFERENCES as readonly string[]).includes(opts.x402)) {
throw new ClientError(
`Invalid --x402 value: "${opts.x402}". Expected one of ${X402_SCHEME_PREFERENCES.join(', ')}, or pass --x402 with no value for the default.`
);
}
options.x402 = opts.x402 as X402SchemePreference;
}
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 ClientError(
`Invalid --schema-mode value: "${mode}". Valid modes are: strict, compatible, ignore`
);
}
options.schemaMode = mode;
}
if (opts.full) options.full = opts.full;
if (opts.maxChars) {
const maxChars = parseInt(opts.maxChars as string, 10);
if (isNaN(maxChars) || maxChars <= 0) {
throw new ClientError(
`Invalid --max-chars value: "${opts.maxChars as string}". Must be a positive number (characters).`
);
}
options.maxChars = maxChars;
}
return options;
}
async function main(): Promise<void> {
// Disambiguate `--x402 <non-scheme>` (URL, @session, etc.) so Commander's
// greedy [optional] arg parser doesn't eat the next positional as the value.
process.argv = preProcessX402Argv(process.argv);
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
// Session commands (@name ...) also handle --help via their own Commander program
if (args.includes('--help') || args.includes('-h')) {
// Check if this is a session command — let it fall through to session handling
const hasSessionArg = args.some((a) => a.startsWith('@') && !a.startsWith('--'));
if (hasSessionArg) {
// Fall through — handleSessionCommands will parse --help via Commander
} else if (args.includes('x402')) {
const x402Index = args.indexOf('x402');
const x402Args = args.slice(x402Index + 1);
await handleX402Command(x402Args);
await closeFileLogger();
return;
} else {
// Check if the user is asking for help on a session subcommand (e.g. mcpc resources-list --help)
const helpTarget = args.find(
(a) => a !== '--help' && a !== '-h' && !a.startsWith('-') && !a.startsWith('@')
);
if (helpTarget && KNOWN_SESSION_COMMANDS.includes(helpTarget)) {
showSessionCommandHelp(helpTarget);
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(theme.red(formatHumanError(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);
const { hasSessions } = await sessions.listSessionsAndAuthProfiles({
outputMode: json ? 'json' : 'human',
});
if (!json) {
console.log('');
if (hasSessions) {
console.log('To view server capabilities and tools, run: mcpc @session');
}
console.log('For usage and the agent guide, run: mcpc help [--skill]');
console.log('');
}
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(theme.red(formatHumanError(error, opts.verbose)));
}
process.exit(error.code);
}
throw error;
} finally {
await closeFileLogger();
}
// Flush stdout before exiting. Honor any exit code set by the command
// handler (e.g. tools-call sets 2 when the tool result has isError).
await flushStdout();
process.exit(process.exitCode ?? 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(theme.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];
// Accept MCP JSON-RPC-style method names (e.g. "tools/list") silently, in case
// this is a session subcommand typed without a session target — undocumented,
// never advertised in the message itself.
const normalizedFirstNonOption = normalizeSlashCommand(firstNonOption);
if (allCommands.includes(normalizedFirstNonOption)) {
// 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> ${normalizedFirstNonOption}`);
console.error(`Run "mcpc --help" for usage information.\n`);
}
} else {
// Try to suggest the closest matching command
const suggestion = suggestCommand(normalizedFirstNonOption, allCommands);
if (outputMode === 'json') {
console.error(formatJsonError(new Error(`Unknown command: ${firstNonOption}`), 1));
} else {
console.error(`Error: Unknown command: ${firstNonOption}`);
if (suggestion) {
if (KNOWN_SESSION_COMMANDS.includes(suggestion)) {
console.error(`\nDid you mean: mcpc <@session> ${suggestion}`);
} else {
console.error(`\nDid you mean: mcpc ${suggestion}`);
}
}
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>`)
// Show Commands before Options in top-level help for better discoverability
program.configureHelp({
subcommandTerm: (cmd) =>
`${cmd.name()} ${cmd.usage()}`.replace(/^\[options\]\s*|\s*\[options\]/g, '').trim(),
styleTitle: (str) => chalk.bold(str),
styleSubcommandText: (str) => theme.cyan(str),
formatHelp: (cmd, helper) => {
const output = Help.prototype.formatHelp.call(helper, cmd, helper);
// Swap Options and Commands sections (separated by blank lines)
const sections = output.split('\n\n');
const optIdx = sections.findIndex((s: string) => s.includes('Options:'));
const cmdIdx = sections.findIndex((s: string) => s.includes('Commands:'));
if (optIdx >= 0 && cmdIdx >= 0 && optIdx < cmdIdx) {
const tmp = sections[optIdx] as string;
sections[optIdx] = sections[cmdIdx] as string;
sections[cmdIdx] = tmp;
}
return (
sections
.map((s: string) => s.trimEnd())
.filter((s: string) => s !== '')
.join('\n\n') + '\n'
);
},
});
const docsUrl = `https://github.com/apify/mcpc/raw/refs/tags/v${mcpcVersion}/README.md`;
program
.name('mcpc')
.description(
`${rainbow('Universal')} command-line client for the Model Context Protocol (MCP).`
)
.usage('[<@session>] [<command>] [options]')
.option('--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('--timeout <seconds>', 'Request timeout in seconds (default: 60)')
.option('--max-chars <n>', 'Truncate output to n characters (ignored in --json mode)')
.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, capabilities, and tools overview
<@session> ${theme.cyan('grep')} <pattern> Search tools and instructions
<@session> ${theme.cyan('tools-list')} List all server tools
<@session> ${theme.cyan('tools-get')} <name> Get tool details and schema
<@session> ${theme.cyan('tools-call')} <name> [arg:=val ... | <json> | <stdin]
<@session> ${theme.cyan('tasks-list')}
<@session> ${theme.cyan('tasks-get')} <taskId>
<@session> ${theme.cyan('tasks-result')} <taskId>
<@session> ${theme.cyan('tasks-cancel')} <taskId>
<@session> ${theme.cyan('prompts-list')}
<@session> ${theme.cyan('prompts-get')} <name> [arg:=val ... | <json> | <stdin]
<@session> ${theme.cyan('resources-list')}
<@session> ${theme.cyan('resources-read')} <uri> [-o <file> | --raw]
<@session> ${theme.cyan('resources-subscribe')} <uri> <file>
<@session> ${theme.cyan('resources-unsubscribe')} <uri>
<@session> ${theme.cyan('resources-templates-list')}
<@session> ${theme.cyan('skills-list')}
<@session> ${theme.cyan('skills-get')} <name> [--raw]
<@session> ${theme.cyan('logging-set-level')} <level>
<@session> ${theme.cyan('ping')}
<@session> ${theme.cyan('server-discover')}
<@session> ${theme.cyan('logs')} [-n N] [--follow] [--since 1h]
Run "mcpc" without arguments to show active sessions and OAuth profiles.
Run "mcpc --json" to get the same data as \`{ sessions: [...], profiles: [...] }\`.
Agent guide: mcpc help --skill
Full docs: ${docsUrl}`
);
// connect command: mcpc connect [<server>] [@session] (server optional — omit to auto-discover)
program
.command('connect [server] [@session]')
.usage('[<server>] [@session] [options]')
.description('Connect to an MCP server and start a new named @session') // keep this short
.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('--stdio', 'Launch all local stdio servers from selected config files')
.option('--protocol-version <version>', 'Pin the MCP protocol version (see below)')
.option('--x402 [scheme]', 'Enable x402 auto-payment (see below)')
.addHelpText(
'after',
`
${chalk.bold('Server formats:')}
mcp.apify.com Remote HTTP server (https:// auto-added)
~/.vscode/mcp.json:puppeteer Config file entry (file:entry)
~/.vscode/mcp.json Config file — connect every entry
${chalk.dim('(no server)'.padEnd(28))} Auto-discover configs and connect everything
${chalk.bold('Auto-discovery (no server arg):')}
Scans ./ and ~ for .mcp.json, mcp.json, mcp_config.json, .cursor/mcp.json,
.vscode/mcp.json, .kiro/settings/mcp.json, ~/.claude.json,
~/.codeium/windsurf/mcp_config.json, plus VS Code & Claude Desktop configs.
${chalk.bold('Session name:')}
Omit @session to auto-generate from the server (mcp.apify.com → @apify)
or config entry. Matching sessions (same server, profile, header keys)
are reused. Bulk connects don't accept @session.
${chalk.bold('Stdio servers (command-based, run locally):')}
Config entries spawn the command on connect, even if the handshake
later fails — only connect to configs you trust. Bulk connects skip
stdio by default; pass --stdio to include them.
${chalk.bold('Protocol version:')}
mcpc negotiates the newest MCP version both sides support, from
2026-07-28 down to 2024-10-07. Pass --protocol-version to pin one exact
version instead — the connection fails if the server does not offer it.
Run mcpc @session to see the negotiated version.
${chalk.bold('x402 payments (experimental):')}
--x402 pays for paid tool calls from the wallet set up with mcpc x402.
Schemes: auto (default, prefers upto), upto, exact.
${outputHelp([
'For a single server, shows session, server info, capabilities, and tools.',
'Bulk connects list every session with its state, then a summary.',
])}${serverDetailsJsonHelp('array')}`
)
.action(async (server, sessionName, opts, command) => {
const globalOpts = getOptionsFromCommand(command);
// 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;
// No server argument — discover standard MCP config files and connect all
if (!server) {
if (sessionName) {
throw new ClientError(
`Cannot specify @session name when discovering and connecting all servers.\n` +
`To connect a specific server, pass a URL or config entry: mcpc connect <server> ${sessionName}`
);
}
await connect.connectAllFromStandardConfigs({
...globalOpts,
...(headers && { headers }),
...(opts.proxy && { proxy: opts.proxy as string }),
...(opts.proxyBearerToken && { proxyBearerToken: opts.proxyBearerToken as string }),
...(opts.stdio && { stdio: true }),
...(opts.protocolVersion && { protocolVersion: opts.protocolVersion as string }),
...(globalOpts.x402 && { x402: globalOpts.x402 }),
...(globalOpts.insecure && { insecure: true }),
});
// Trailing blank line to match the spacing of other commands (human mode only).
if (globalOpts.outputMode === 'human') console.log('');
return;
}
const parsed = parseServerArg(server);
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)`
);
}
// Config file without :entry — connect all servers from the file
if (parsed.type === 'config-file') {
if (sessionName) {
throw new ClientError(
`Cannot specify @session name when connecting all servers from a config file.\n` +
`To connect a specific entry, use: mcpc connect ${server}:<entry> ${sessionName}`
);
}
await connect.connectAllFromConfig(parsed.file, {
...globalOpts,
...(headers && { headers }),
...(opts.proxy && { proxy: opts.proxy as string }),
...(opts.proxyBearerToken && { proxyBearerToken: opts.proxyBearerToken as string }),
...(opts.stdio && { stdio: true }),
...(opts.protocolVersion && { protocolVersion: opts.protocolVersion as string }),
...(globalOpts.x402 && { x402: globalOpts.x402 }),
...(globalOpts.insecure && { insecure: true }),
});
return;
}
// Auto-generate session name if not provided
if (!sessionName) {
sessionName = await connect.resolveSessionName(parsed, {
outputMode: globalOpts.outputMode,
...(globalOpts.profile && { profile: globalOpts.profile }),
...(headers && { headers }),
...(globalOpts.noProfile && { noProfile: globalOpts.noProfile }),
});
}
if (parsed.type === 'config') {
// Config file entry: pass entry name as target with config file path
await connect.connectSession(parsed.entry, sessionName, {
...globalOpts,
...(headers && { headers }),
config: parsed.file,
proxy: opts.proxy,
proxyBearerToken: opts.proxyBearerToken,
...(opts.protocolVersion && { protocolVersion: opts.protocolVersion as string }),
...(globalOpts.x402 && { x402: globalOpts.x402 }),
...(globalOpts.insecure && { insecure: true }),
});
} else {
await connect.connectSession(server, sessionName, {
...globalOpts,
...(headers && { headers }),
proxy: opts.proxy,
proxyBearerToken: opts.proxyBearerToken,
...(opts.protocolVersion && { protocolVersion: opts.protocolVersion as string }),
...(globalOpts.x402 && { x402: globalOpts.x402 }),
...(globalOpts.insecure && { insecure: true }),
});
}
});
// close command: mcpc close @<session>
program
.command('close [@session]')
.usage('<@session> [options]')
.description('Close a session')
.addHelpText('after', jsonHelp('`{ sessionName, closed: true }`'))
.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> [options]')
.description('Restart a session (losing all state)')
.addHelpText(
'after',
outputHelp('After restarting, shows session, server info, capabilities, and tools.') +
serverDetailsJsonHelp('object')
)
.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));
});
// login command: mcpc login <server>
program
.command('login [server]')
.usage('<server> [options]')
.description('Log in to a server and save an OAuth profile')
.option('--profile <name>', 'Profile name (default: "default")')
.option('--scope <scopes>', 'OAuth scopes to request (e.g. --scope "read write")')
.option('--grant <type>', 'Grant: authorization-code (default), client-credentials, id-jag')
.option('--client-id <id>', 'Pre-registered OAuth client ID (skips CIMD and DCR)')
.option('--client-secret <secret>', 'Pre-registered OAuth client secret (requires --client-id)')
.option(
'--client-key <pem-or-path>',
'Private key (PEM path or literal) for private_key_jwt auth'
)
.option('--client-key-alg <alg>', 'JWT signing algorithm for --client-key (default: RS256)')
.option(
'--token-endpoint <url>',
'OAuth token endpoint (client-credentials only, auto-discovered)'
)
.option('--idp <url>', 'Enterprise IdP issuer URL (id-jag only)')
.option('--idp-client-id <id>', 'Client ID pre-registered at the enterprise IdP (id-jag only)')
.option('--idp-client-secret <secret>', 'Client secret for the enterprise IdP (id-jag only)')
.option('--idp-scope <scopes>', 'OIDC scopes for the IdP SSO (id-jag only, see below)')
.option('--client-metadata-url <url>', 'HTTPS URL of an OAuth CIMD (default: mcpc CIMD)')
.option('--no-client-metadata-url', 'Disable CIMD; force DCR on CIMD-capable servers')
.option(
'--callback-port <port>',
`Loopback port for OAuth callback (default: ${MCPC_OAUTH_CALLBACK_PORTS.join('/')})`
)
.option('--callback-host <host>', 'OAuth callback host: 127.0.0.1 (default) or localhost')
.addHelpText(
'after',
`
${chalk.bold('Interactive login:')}
By default, the command opens your browser to authorize the server,
then saves the credentials as a reusable profile any session can use:
default profile: mcpc login mcp.apify.com
named profile: mcpc login mcp.apify.com --profile work
then connect: mcpc connect mcp.apify.com @app --profile work
${chalk.bold('Client registration (how mcpc identifies itself to the server):')}
1. Client ID Metadata Documents (CIMD): the default. mcpc's hosted CIMD at
https://apify.github.io/mcpc/client-metadata.json identifies all mcpc
installs as one client. Override with --client-metadata-url <url>, or
disable with --no-client-metadata-url.
2. Pre-registration: pass --client-id (and --client-secret if issued). If the
client's redirect URI uses localhost (e.g. localhost:3118), match it with
--callback-host localhost --callback-port 3118.
3. Dynamic Client Registration (DCR): fallback when CIMD is unsupported or
disabled and the server exposes a registration_endpoint.
See https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization
${chalk.bold('Machine-to-machine authentication (for CI/CD and daemons):')}
Pass --grant client-credentials, --client-id, and one credential:
mcpc login mcp.example.com --grant client-credentials \\
--client-id my-svc --client-secret s3cr3t --scope "read write"
mcpc login mcp.example.com --grant client-credentials \\
--client-id my-svc --client-key ./key.pem
--client-secret uses client_secret_basic; --client-key signs a private_key_jwt
assertion (RFC 7523). The token endpoint is auto-discovered; pin it with
--token-endpoint <url> for servers without discoverable metadata.
See https://modelcontextprotocol.io/extensions/auth/oauth-client-credentials
${chalk.bold("Enterprise-managed authorization (SSO via your organization's IdP):")}
Pass --grant id-jag when your organization controls MCP server access
centrally through its identity provider (e.g. Okta). You sign in once with
your corporate SSO; mcpc then obtains MCP tokens via identity assertion
grants (ID-JAG) without any per-server consent screens:
mcpc login mcp.example.com --grant id-jag \\
--idp https://acme.okta.com --idp-client-id <idp-client> \\
--client-id <mcp-as-client> --client-secret <secret>
Both clients are pre-registered by your IT team: --idp-client-id at the
enterprise IdP (add --idp-client-secret if it is a confidential client),
--client-id/--client-secret at the MCP server's authorization server.
--scope requests MCP-server scopes; --idp-scope overrides the OIDC scopes
used for the SSO itself (default: "openid profile email offline_access").
See https://modelcontextprotocol.io/extensions/auth/enterprise-managed-authorization
${jsonHelp('Interactive prompts go to stderr; stdout is a clean JSON object', '`{ profile, serverUrl, scopes }`')}`
)
.action(async (server, opts, command) => {
if (!server) {
throw new ClientError(
'Missing required argument: server\n\nExample: mcpc login mcp.apify.com'
);
}
let callbackPort: number | undefined;
if (opts.callbackPort) {
const parsed = parseInt(opts.callbackPort as string, 10);
if (isNaN(parsed) || parsed < 1 || parsed > 65535) {
throw new ClientError(
`Invalid --callback-port value: "${opts.callbackPort as string}". Must be an integer between 1 and 65535.`
);
}
callbackPort = parsed;
}
let callbackHost: string | undefined;
if (opts.callbackHost) {
// URI hosts are case-insensitive (RFC 3986 §3.2.2), but redirect_uri
// matching at the authorization server is an exact string comparison,
// so normalize to lowercase rather than passing the casing through.
callbackHost = (opts.callbackHost as string).toLowerCase();
if (!MCPC_OAUTH_CALLBACK_HOSTS.includes(callbackHost)) {
throw new ClientError(
`Invalid --callback-host value: "${opts.callbackHost as string}". ` +
`Must be one of: ${MCPC_OAUTH_CALLBACK_HOSTS.join(', ')} ` +
'(loopback only — a non-loopback host would send the OAuth callback off this machine).'
);
}
}
await auth.login(server, {
profile: opts.profile,
scope: opts.scope,
grant: opts.grant,
clientId: opts.clientId,
clientSecret: opts.clientSecret,
clientKey: opts.clientKey,
clientKeyAlg: opts.clientKeyAlg,
tokenEndpoint: opts.tokenEndpoint,
clientMetadataUrl: opts.clientMetadataUrl,
idp: opts.idp,
idpClientId: opts.idpClientId,
idpClientSecret: opts.idpClientSecret,
idpScope: opts.idpScope,
...(callbackPort !== undefined ? { callbackPort } : {}),
...(callbackHost ? { callbackHost } : {}),
...getOptionsFromCommand(command),
});
});
// logout command: mcpc logout <server>
program
.command('logout [server]')
.usage('<server> [options]')
.description('Delete an OAuth profile for a server')
.option('--profile <name>', 'Profile name (default: "default")')
.addHelpText('after', jsonHelp('`{ profile, serverUrl, deleted: true, affectedSessions }`'))
.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.
${jsonHelp('`{ crashedBridges, expiredSessions, orphanedBridgeLogs, sessions, profiles, logs }`')}`
)
.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'),
});
});
// grep command: mcpc grep <pattern>
program
.command('grep [pattern]')
.usage('<pattern> [options]')
.description('Search tools and instructions across all active sessions')
.option('--tools', 'Search tools')
.option('--resources', 'Search resources')
.option('--prompts', 'Search prompts')
.option('--instructions', 'Search server instructions')
.option('-E, --regex', 'Treat pattern as a regular expression')
.option('-s, --case-sensitive', 'Case-sensitive matching')
.option('-m, --max-results <n>', 'Limit the number of results')
.addHelpText(
'after',
`
${chalk.bold('Type filters:')}
By default, tools and instructions are searched. Use --resources or --prompts
to search those instead. Combine flags to search multiple types (e.g. --tools --resources).
${chalk.bold('Examples:')}
mcpc grep "search" Search tools and instructions in all sessions
mcpc grep "search" --resources Search resources only
mcpc grep "search" --tools --prompts Search tools and prompts
mcpc grep "search|find" -E Regex search across tools and instructions
mcpc @apify grep "actor" Search within a single session
mcpc grep "file" --json JSON output for scripting
mcpc grep "actor" -m 5 Show at most 5 results
${chalk.bold('Exit codes:')}
0 = matches found, 1 = no matches (grep convention)
${jsonHelp('`[{ sessionName, tools?: Tool[], resources?: Resource[], prompts?: Prompt[], instructions?: string[] }]`')}`
)
.action(async (pattern, opts, command) => {
if (!pattern) {
throw new ClientError(
'Missing required argument: pattern\n\nUsage: mcpc grep <pattern>\n\nExample: mcpc grep "search"'
);
}
const globalOpts = getOptionsFromCommand(command);
const maxResults = opts.maxResults ? parseInt(opts.maxResults as string, 10) : undefined;
const exitCode = await grepCmd.grepAllSessions(pattern, {
tools: opts.tools as boolean | undefined,
resources: opts.resources as boolean | undefined,
prompts: opts.prompts as boolean | undefined,
instructions: opts.instructions as boolean | undefined,
regex: opts.regex as boolean | undefined,
caseSensitive: opts.caseSensitive as boolean | undefined,
maxResults,
...globalOpts,
});
process.exit(exitCode);
});
// 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)')
.action(() => {});
// help command: mcpc help [command] (supports "help x402 sign"); --skill prints the agent guide
program
.command('help [command] [subcommand]')
.description('Show help for a command')
.option('--skill', 'Print the agent skill (mental model, workflows, examples)')
.action(async (cmdName?: string, subcommand?: string, opts?: { skill?: boolean }) => {
if (opts?.skill) {
if (cmdName) {
throw new ClientError(
'mcpc help --skill prints the agent skill and takes no command name'
);
}
help.printGuide();
return;
}
if (!cmdName) {
program.outputHelp();
return;
}
// Raw MCP method names ("server/discover") are accepted wherever a command name
// is expected, so `help` must resolve them too — otherwise looking up the alias
// you just used successfully reports it as an unknown command.
const slashAlias = normalizeSlashCommand(cmdName);
if (
slashAlias !== cmdName &&
[...KNOWN_COMMANDS, ...KNOWN_SESSION_COMMANDS].includes(slashAlias)
) {
cmdName = slashAlias;
}
// 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) {
tuneCommandHelp(topLevelCmd);
topLevelCmd.outputHelp();
return;
}
// Check session subcommands
if (showSessionCommandHelp(cmdName)) return;
console.error(`Unknown command: ${cmdName}`);
const suggestion = suggestCommand(cmdName, [...KNOWN_COMMANDS, ...KNOWN_SESSION_COMMANDS]);
if (suggestion) {
console.error(`\nDid you mean: mcpc help ${suggestion}`);
}
console.error(`Run "mcpc --help" for usage information.`);
process.exit(1);
});
return program;
}
/**
* Tune a command's help display: add --json option and hide --help.
*/
function tuneCommandHelp(cmd: Command): void {
if (!cmd.options.some((o) => o.long === '--json')) {
cmd.option('--json', 'Output in JSON format');
}
// A command that disabled its help option did so deliberately (e.g. tools-call
// intercepts --help in its action to show the tool's schema) — re-registering
// it here would make Commander swallow --help before the action ever runs.
// Commander marks a disabled help option with `_helpOption === null`.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((cmd as any)._helpOption === null) {
return;
}
cmd.helpOption('-h, --help', 'Display help');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const helpOpt = (cmd as any)._getHelpOption?.();
if (helpOpt) helpOpt.hidden = true;
}
/**
* Show help for a session subcommand by name.
* Returns true if the command was found and help was displayed.
*/
function showSessionCommandHelp(cmdName: string): boolean {