-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathsessions.ts
More file actions
1015 lines (922 loc) · 32.2 KB
/
Copy pathsessions.ts
File metadata and controls
1015 lines (922 loc) · 32.2 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
/**
* Sessions command handlers
*/
import { createServer } from 'net';
import {
OutputMode,
isValidSessionName,
generateSessionName,
validateProfileName,
isProcessAlive,
getServerHost,
redactHeaders,
matchSessionByTarget,
pickAvailableSessionName,
} from '../../lib/index.js';
import { DISCONNECTED_THRESHOLD_MS } from '../../lib/types.js';
import type { ServerConfig, ProxyConfig } from '../../lib/types.js';
import {
formatOutput,
formatSuccess,
formatWarning,
formatError,
formatSessionLine,
formatServerDetails,
} from '../output.js';
import { withMcpClient, resolveTarget, resolveAuthProfile } from '../helpers.js';
import { listAuthProfiles } from '../../lib/auth/profiles.js';
import {
sessionExists,
deleteSession,
saveSession,
updateSession,
consolidateSessions,
getSession,
loadSessions,
} from '../../lib/sessions.js';
import {
startBridge,
StartBridgeOptions,
stopBridge,
reconnectCrashedSessions,
} from '../../lib/bridge-manager.js';
import {
storeKeychainSessionHeaders,
storeKeychainProxyBearerToken,
} from '../../lib/auth/keychain.js';
import {
AuthError,
ClientError,
isAuthenticationError,
createServerAuthError,
} from '../../lib/index.js';
import { getWallet } from '../../lib/wallets.js';
import chalk from 'chalk';
import { createLogger } from '../../lib/logger.js';
import { parseProxyArg } from '../parser.js';
import { loadConfig, listServers } from '../../lib/config.js';
const logger = createLogger('sessions');
/**
* Check if a port is available for binding
*/
async function checkPortAvailable(host: string, port: number): Promise<boolean> {
return new Promise((resolve) => {
const server = createServer();
server.once('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') {
resolve(false);
} else {
// Other errors (like permission denied) - treat as unavailable
resolve(false);
}
});
server.once('listening', () => {
server.close(() => {
resolve(true);
});
});
server.listen(port, host);
});
}
/**
* Find an existing session that matches the given server target and authentication settings.
* Used when auto-generating session names to reuse existing sessions instead of creating duplicates.
*
* @returns The matching session name (with @ prefix), or undefined if no match found
*/
export async function findMatchingSession(
parsed:
| { type: 'url'; url: string }
| { type: 'config'; file: string; entry: string }
| { type: 'command'; command: string; args: string[]; env?: Record<string, string> },
options: { profile?: string; headers?: string[]; noProfile?: boolean }
): Promise<string | undefined> {
const storage = await loadSessions();
return matchSessionByTarget(storage, parsed, options);
}
/**
* Resolve the session name when @session is omitted from `mcpc connect`.
* Finds an existing matching session or generates a new unique name.
*
* @returns Session name with @ prefix
*/
export async function resolveSessionName(
parsed:
| { type: 'url'; url: string }
| { type: 'config'; file: string; entry: string }
| { type: 'command'; command: string; args: string[]; env?: Record<string, string> },
options: {
outputMode: OutputMode;
profile?: string;
headers?: string[];
noProfile?: boolean;
}
): Promise<string> {
// First, check if an existing session matches this server + auth settings
const existingName = await findMatchingSession(parsed, options);
if (existingName) {
return existingName;
}
// Generate a new session name
const candidateName = generateSessionName(parsed);
// For inline commands, always append a numeric suffix (starting at -1) since the binary
// basename is rarely as distinctive as a hostname or config entry.
// For URL/config targets, try the bare name first, then -2, -3, ...
const storage = await loadSessions();
const picked = pickAvailableSessionName(storage, candidateName, parsed.type === 'command');
if (picked) {
if (options.outputMode === 'human') {
console.log(chalk.cyan(`Using session name: ${picked}`));
}
return picked;
}
let targetDescription: string;
if (parsed.type === 'url') {
targetDescription = parsed.url;
} else if (parsed.type === 'config') {
targetDescription = `${parsed.file}:${parsed.entry}`;
} else {
targetDescription = [parsed.command, ...parsed.args].join(' ');
}
throw new ClientError(
`Cannot auto-generate session name: too many sessions for this server.\n` +
`Specify a name explicitly: mcpc connect ${targetDescription} @my-session`
);
}
/**
* Creates a new session, starts a bridge process, and instructs it to connect an MCP server.
* If session already exists with crashed bridge, reconnects it automatically
*/
export async function connectSession(
target: string,
name: string,
options: {
outputMode: OutputMode;
verbose?: boolean;
config?: string;
headers?: string[];
timeout?: number;
profile?: string;
noProfile?: boolean;
proxy?: string;
proxyBearerToken?: string;
x402?: boolean;
insecure?: boolean;
skipDetails?: boolean;
quiet?: boolean;
/**
* Pre-built ServerConfig (for inline stdio commands). When provided,
* resolveTarget() is skipped and this config is used directly.
*/
inlineServerConfig?: ServerConfig;
}
): Promise<void> {
// Validate session name
if (!isValidSessionName(name)) {
throw new ClientError(
`Invalid session name: ${name}\n` +
`Session names must start with @ and be followed by 1-64 characters, alphanumeric with hyphens or underscores only (e.g., @my-session).`
);
}
// Validate profile name (if provided)
if (options.profile) {
validateProfileName(options.profile);
}
// Parse proxy configuration (if provided)
let proxyConfig: ProxyConfig | undefined;
if (options.proxy) {
proxyConfig = parseProxyArg(options.proxy);
logger.debug(`Proxy config: ${proxyConfig.host}:${proxyConfig.port}`);
// Validate port is available before starting bridge
const portAvailable = await checkPortAvailable(proxyConfig.host, proxyConfig.port);
if (!portAvailable) {
throw new ClientError(
`Port ${proxyConfig.port} is already in use on ${proxyConfig.host}. ` +
`Choose a different port with --proxy [host:]port`
);
}
}
// Validate proxy-bearer-token is only used with --proxy
if (options.proxyBearerToken && !options.proxy) {
throw new ClientError('--proxy-bearer-token requires --proxy to be specified');
}
// Check if session already exists
const existingSession = await getSession(name);
if (existingSession) {
const bridgeStatus = getBridgeStatus(existingSession);
if (bridgeStatus === 'live') {
// Session exists and bridge is running - just show server info
if (options.outputMode === 'human' && !options.quiet) {
console.log(formatSuccess(`Session ${name} is already active`));
}
if (!options.skipDetails) {
await showServerDetails(name, { ...options, hideTarget: false });
}
return;
}
// Bridge has crashed or expired - reconnect with warning
if (options.outputMode === 'human' && !options.quiet) {
console.log(
chalk.yellow(`Session ${name} exists but bridge is ${bridgeStatus}, reconnecting...`)
);
}
// Clean up old bridge resources before reconnecting
try {
await stopBridge(name);
} catch {
// Bridge may already be stopped
}
}
// Resolve target to transport config (or use the pre-built inline config for stdio commands)
const serverConfig = options.inlineServerConfig
? options.inlineServerConfig
: await resolveTarget(target, options);
// Detect conflicting auth flags: --profile and --header "Authorization: ..." are mutually exclusive
const hasExplicitAuthHeader = serverConfig.headers?.Authorization !== undefined;
const hasExplicitProfile = options.profile !== undefined;
if (hasExplicitAuthHeader && hasExplicitProfile) {
throw new ClientError(
`Cannot combine --profile with --header "Authorization: ...".\n\n` +
`Use either:\n` +
` --profile ${options.profile} (OAuth authentication via saved profile)\n` +
` --header "Authorization: Bearer <token>" (static bearer token)`
);
}
// For HTTP targets, resolve auth profile (with helpful errors if none available)
// Skip OAuth profile resolution when:
// - --no-profile is specified (explicit anonymous connection)
// - --header "Authorization: ..." is provided (explicit bearer token)
// - --x402 is specified (x402 payment auth instead of OAuth)
let profileName: string | undefined;
if (serverConfig.url) {
if (options.noProfile) {
logger.debug('Skipping OAuth profile: --no-profile specified');
} else if (hasExplicitAuthHeader) {
logger.debug(
'Skipping OAuth profile auto-detection: explicit Authorization header provided via --header'
);
} else if (options.x402 && !options.profile) {
// When using --x402 without explicit --profile, don't try to auto-discover default profile
// since x402 itself serves as the authentication mechanism
logger.debug('Skipping OAuth profile auto-detection: --x402 specified');
} else {
profileName = await resolveAuthProfile(serverConfig.url, target, options.profile, {
sessionName: name,
});
}
}
// Store headers in OS keychain (secure storage) before starting bridge
let headers: Record<string, string> | undefined;
if (Object.keys(serverConfig.headers || {}).length > 0) {
headers = { ...serverConfig.headers };
if (Object.keys(headers).length > 0) {
logger.debug(
`Storing ${Object.keys(headers).length} headers for session ${name} in keychain`
);
await storeKeychainSessionHeaders(name, headers);
} else {
headers = undefined;
}
}
// Store proxy bearer token in keychain (if provided)
if (options.proxyBearerToken) {
logger.debug(`Storing proxy bearer token for session ${name} in keychain`);
await storeKeychainProxyBearerToken(name, options.proxyBearerToken);
}
// Validate x402 wallet (if provided)
if (options.x402) {
const wallet = await getWallet();
if (!wallet) {
throw new ClientError('x402 wallet not found. Create one with: mcpc x402 init');
}
logger.debug(`Using x402 wallet: ${wallet.address}`);
}
// Create or update session record (without pid - that comes from startBridge)
// Store serverConfig with headers redacted (actual values in keychain)
const isReconnect = !!existingSession;
const { headers: _originalHeaders, ...baseTransportConfig } = serverConfig;
const sessionTransportConfig: ServerConfig = {
...baseTransportConfig,
...(headers && { headers: redactHeaders(headers) }),
};
const sessionUpdate: Parameters<typeof updateSession>[1] = {
server: sessionTransportConfig,
...(profileName && { profileName }),
...(proxyConfig && { proxy: proxyConfig }),
...(options.x402 && { x402: true }),
...(options.insecure && { insecure: true }),
// Clear any previous error status (unauthorized, expired) when reconnecting
...(isReconnect && { status: 'active' }),
};
if (isReconnect) {
await updateSession(name, sessionUpdate);
logger.debug(`Session record updated for reconnect: ${name}`);
} else {
await saveSession(name, {
server: sessionTransportConfig,
createdAt: new Date().toISOString(),
status: 'connecting',
lastConnectionAttemptAt: new Date().toISOString(),
...sessionUpdate,
});
logger.debug(`Initial session record created for: ${name}`);
}
// Start bridge process (handles spawning and IPC credential delivery)
try {
const bridgeOptions: StartBridgeOptions = {
sessionName: name,
serverConfig: serverConfig,
verbose: options.verbose || false,
};
if (headers) {
bridgeOptions.headers = headers;
}
if (profileName) {
bridgeOptions.profileName = profileName;
}
if (proxyConfig) {
bridgeOptions.proxyConfig = proxyConfig;
}
if (options.x402) {
bridgeOptions.x402 = true;
}
if (options.insecure) {
bridgeOptions.insecure = true;
}
const { pid } = await startBridge(bridgeOptions);
// Update session with bridge info and mark as active (clears 'connecting' status)
await updateSession(name, { pid, status: 'active' });
logger.debug(`Session ${name} updated with bridge PID: ${pid}`);
} catch (error) {
// Clean up on bridge start failure
logger.debug(`Bridge start failed, cleaning up session ${name}`);
if (!isReconnect) {
// Only delete session record for new sessions (not reconnects)
try {
await deleteSession(name);
} catch {
// Ignore cleanup errors
}
}
throw error;
}
// When skipDetails is set (bulk connect from config file), print success immediately
// without waiting for the bridge to complete MCP handshake. The session will auto-recover
// if the server is slow or unreachable; the user can check status with `mcpc @session`.
if (options.skipDetails) {
if (options.outputMode === 'human' && !options.quiet) {
console.log(formatSuccess(`Session ${name} ${isReconnect ? 'reconnected' : 'created'}`));
}
return;
}
// Verify the connection works by fetching server details.
// showServerDetails blocks until the bridge is connected (via health check),
// so by the time it returns or throws, we have definitive bridge status.
// Only print success after the server actually responds.
try {
await showServerDetails(name, {
...options,
hideTarget: false, // Show session info prefix
});
// Server responded — now we can print success
if (options.outputMode === 'human') {
console.log(formatSuccess(`Session ${name} ${isReconnect ? 'reconnected' : 'created'}`));
}
} catch (detailsError) {
if (detailsError instanceof AuthError) {
throw detailsError;
}
// Fallback: check error message for auth patterns (error may have been wrapped
// as ClientError/ServerError during bridge IPC serialization)
if (detailsError instanceof Error && isAuthenticationError(detailsError.message)) {
throw createServerAuthError(serverConfig.url || target, { sessionName: name });
}
// Non-auth failure: session was created but server didn't respond properly.
// Show a warning instead of silent success, so the user knows something is wrong.
if (options.outputMode === 'human') {
const errorMsg = detailsError instanceof Error ? detailsError.message : String(detailsError);
console.log(
formatWarning(
`Session ${name} created but server is not responding: ${errorMsg}\n` +
` The session will auto-recover when the server becomes available.\n` +
` Check status with: mcpc ${name}`
)
);
}
logger.debug(
`showServerDetails failed for new session ${name}: ${(detailsError as Error).message}`
);
}
}
// DISCONNECTED_THRESHOLD_MS imported from ../../lib/types.js
export type DisplayStatus =
| 'live'
| 'connecting'
| 'reconnecting'
| 'disconnected'
| 'crashed'
| 'unauthorized'
| 'expired';
/**
* Determine bridge status for a session
*/
export function getBridgeStatus(session: {
status?: string;
pid?: number;
lastSeenAt?: string;
}): DisplayStatus {
if (session.status === 'unauthorized') {
return 'unauthorized';
}
if (session.status === 'expired') {
return 'expired';
}
// Transient states: connecting (initial) or reconnecting (after crash)
if (session.status === 'connecting' || session.status === 'reconnecting') {
return session.status;
}
if (!session.pid || !isProcessAlive(session.pid)) {
return 'crashed';
}
// Bridge is alive — check if server is actually responding
if (session.lastSeenAt) {
const lastSeenMs = Date.now() - new Date(session.lastSeenAt).getTime();
if (lastSeenMs > DISCONNECTED_THRESHOLD_MS) {
return 'disconnected';
}
}
return 'live';
}
/**
* Format bridge status for display with dot indicator
*/
export function formatBridgeStatus(status: DisplayStatus): { dot: string; text: string } {
switch (status) {
case 'live':
return { dot: chalk.green('●'), text: chalk.green('live') };
case 'connecting':
return { dot: chalk.yellow('●'), text: chalk.yellow('connecting') };
case 'reconnecting':
return { dot: chalk.yellow('●'), text: chalk.yellow('reconnecting') };
case 'disconnected':
return { dot: chalk.yellow('●'), text: chalk.yellow('disconnected') };
case 'crashed':
return { dot: chalk.yellow('○'), text: chalk.yellow('crashed') };
case 'unauthorized':
return { dot: chalk.red('○'), text: chalk.red('unauthorized') };
case 'expired':
return { dot: chalk.red('○'), text: chalk.red('expired') };
}
}
/**
* Format time ago in human-friendly way
*/
export function formatTimeAgo(isoDate: string | undefined): string {
if (!isoDate) return '';
const date = new Date(isoDate);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffSecs = Math.floor(diffMs / 1000);
const diffMins = Math.floor(diffSecs / 60);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffSecs < 60) return 'just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays === 1) return 'yesterday';
if (diffDays < 7) return `${diffDays} days ago`;
if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;
return `${Math.floor(diffDays / 30)} months ago`;
}
/**
* List active sessions and authentication profiles
* Consolidates session state first (cleans up crashed bridges, removes expired sessions)
*/
export async function listSessionsAndAuthProfiles(options: {
outputMode: OutputMode;
}): Promise<void> {
// Consolidate sessions first (cleans up crashed bridges, removes expired sessions)
const consolidateResult = await consolidateSessions(false);
const sessions = Object.values(consolidateResult.sessions);
// Auto-restart crashed bridges in the background (fire-and-forget)
reconnectCrashedSessions(consolidateResult.sessionsToRestart);
// Load auth profiles from disk
const profiles = await listAuthProfiles();
if (options.outputMode === 'json') {
// Add bridge status to JSON output
const sessionsWithStatus = sessions.map((session) => ({
...session,
status: getBridgeStatus(session),
}));
console.log(
formatOutput(
{
sessions: sessionsWithStatus,
profiles,
},
'json'
)
);
} else {
// Display sessions
if (sessions.length === 0) {
console.log(chalk.bold('No active MCP sessions.'));
console.log(chalk.dim(' ↳ run: mcpc connect mcp.example.com @test'));
} else {
console.log(chalk.bold('MCP sessions:'));
for (const session of sessions) {
const status = getBridgeStatus(session);
const { dot, text } = formatBridgeStatus(status);
// Format status with time ago info (show for non-live states and stale live sessions)
let statusStr = `${dot} ${text}`;
if (session.lastSeenAt) {
const lastSeenMs = Date.now() - new Date(session.lastSeenAt).getTime();
const isStale = lastSeenMs > 5 * 60 * 1000; // 5 minutes
if (status !== 'live' || isStale) {
const timeAgo = formatTimeAgo(session.lastSeenAt);
if (timeAgo) {
statusStr += chalk.dim(`, ${timeAgo}`);
}
}
}
console.log(` ${formatSessionLine(session)} ${statusStr}`);
// Show recovery hints for non-live sessions
if (status === 'unauthorized') {
console.log(chalk.dim(` ↳ run: mcpc ${session.name} restart`));
} else if (status === 'crashed') {
console.log(chalk.dim(` ↳ run: mcpc ${session.name}`));
} else if (status === 'expired') {
console.log(chalk.dim(` ↳ run: mcpc ${session.name} restart`));
}
}
}
// Display auth profiles
console.log('');
if (profiles.length === 0) {
console.log(chalk.bold('No OAuth profiles.'));
console.log(chalk.dim(' ↳ run: mcpc login mcp.example.com'));
} else {
console.log(chalk.bold('Saved OAuth profiles:'));
for (const profile of profiles) {
const hostStr = getServerHost(profile.serverUrl);
const nameStr = chalk.magenta(profile.name);
const userStr = profile.userEmail || profile.userName || '';
// Show refreshedAt if available, otherwise createdAt
const timeAgo = formatTimeAgo(profile.refreshedAt || profile.createdAt);
const timeLabel = profile.refreshedAt ? 'refreshed' : 'created';
let line = ` ${hostStr} / ${nameStr}`;
if (userStr) {
line += chalk.dim(` (${userStr})`);
}
if (timeAgo) {
line += chalk.dim(`, ${timeLabel} ${timeAgo}`);
}
console.log(line);
}
}
}
}
/**
* Close a session
*/
export async function closeSession(
name: string,
options: { outputMode: OutputMode }
): Promise<void> {
try {
// Check if session exists
if (!(await sessionExists(name))) {
throw new ClientError(`Session not found: ${name}`);
}
// Stop the bridge process (graceful: send IPC shutdown on Windows so
// the bridge can send HTTP DELETE to the server before exiting)
await stopBridge(name, { graceful: true });
// Delete session record from storage
await deleteSession(name);
// Success!
if (options.outputMode === 'human') {
console.log(formatSuccess(`Session ${name} closed successfully\n`));
} else {
console.log(
formatOutput(
{
sessionName: name,
closed: true,
},
'json'
)
);
}
} catch (error) {
if (options.outputMode === 'human') {
console.error(formatError((error as Error).message));
} else {
console.error(
formatOutput(
{
sessionName: name,
closed: false,
error: (error as Error).message,
},
'json'
)
);
}
throw error;
}
}
/**
* Get server instructions and capabilities (also used for help command)
*/
export async function showServerDetails(
target: string,
options: {
outputMode: OutputMode;
config?: string;
headers?: string[];
timeout?: number;
verbose?: boolean;
hideTarget?: boolean;
}
): Promise<void> {
await withMcpClient(target, options, async (client, context) => {
const serverDetails = await client.getServerDetails();
const { serverInfo, capabilities, instructions, protocolVersion } = serverDetails;
// Get tools list (uses bridge cache when available, no extra server call)
const cachedToolsResult = await client.listAllTools();
const tools = cachedToolsResult.tools;
if (options.outputMode === 'human') {
console.log(formatServerDetails(serverDetails, target, tools));
} else {
// JSON output MUST match MCP InitializeResult structure!
// See https://modelcontextprotocol.io/specification/2025-11-25/schema#initializeresult
// Build _mcpc.server with redacted headers for security
const server: ServerConfig = {
...context.serverConfig,
...(context.serverConfig?.headers && {
headers: redactHeaders(context.serverConfig.headers),
}),
};
console.log(
formatOutput(
{
_mcpc: {
sessionName: context.sessionName,
profileName: context.profileName,
server,
},
protocolVersion,
capabilities,
serverInfo,
instructions,
...(tools.length > 0 && { toolNames: tools.map((t) => t.name) }),
},
'json'
)
);
}
});
}
/**
* Restart a session by stopping and restarting the bridge process
*/
export async function restartSession(
name: string,
options: { outputMode: OutputMode; verbose?: boolean }
): Promise<void> {
try {
// Get existing session
const session = await getSession(name);
if (!session) {
throw new ClientError(`Session not found: ${name}`);
}
if (options.outputMode === 'human') {
console.log(chalk.yellow(`Restarting session ${name}...`));
}
// Stop the bridge (even if it's alive)
try {
await stopBridge(name);
} catch {
// Bridge may already be stopped
}
// Get server config from session
const serverConfig = session.server;
if (!serverConfig) {
throw new ClientError(`Session ${name} has no server configuration`);
}
// Load headers from keychain if present
const { readKeychainSessionHeaders } = await import('../../lib/auth/keychain.js');
const headers = await readKeychainSessionHeaders(name);
// Start bridge process
const bridgeOptions: StartBridgeOptions = {
sessionName: name,
serverConfig: { ...serverConfig, ...(headers && { headers }) },
verbose: options.verbose || false,
};
if (headers) {
bridgeOptions.headers = headers;
}
// Resolve auth profile: use stored profile, or auto-detect a "default" profile.
// This handles the case where user creates a session without auth, then later runs
// `mcpc login <server>` to create a default profile, and restarts the session.
const hasExplicitAuthHeader = headers?.Authorization !== undefined;
let profileName = session.profileName;
if (!profileName && serverConfig.url && !hasExplicitAuthHeader && !session.x402) {
profileName = await resolveAuthProfile(serverConfig.url, serverConfig.url, undefined, {
sessionName: name,
});
if (profileName) {
logger.debug(`Discovered auth profile "${profileName}" for session ${name}`);
await updateSession(name, { profileName });
}
}
if (profileName) {
bridgeOptions.profileName = profileName;
}
if (session.proxy) {
bridgeOptions.proxyConfig = session.proxy;
}
if (session.x402) {
bridgeOptions.x402 = session.x402;
}
if (session.insecure) {
bridgeOptions.insecure = session.insecure;
}
// NOTE: Do NOT pass mcpSessionId on explicit restart.
// Explicit restart should create a fresh session, not try to resume the old one.
// Session resumption is only attempted on automatic bridge restart (when bridge crashes
// and CLI detects it). If server rejects the session ID, session is marked as expired.
const { pid } = await startBridge(bridgeOptions);
// Update session with new bridge PID and clear any expired/crashed status
await updateSession(name, { pid, status: 'active' });
logger.debug(`Session ${name} restarted with bridge PID: ${pid}`);
// Success message
if (options.outputMode === 'human') {
console.log(formatSuccess(`Session ${name} restarted`));
}
// Show server details (like when creating a session)
await showServerDetails(name, {
...options,
hideTarget: false,
});
} catch (error) {
if (options.outputMode === 'human') {
console.error(formatError((error as Error).message));
} else {
console.error(
formatOutput(
{
sessionName: name,
restarted: false,
error: (error as Error).message,
},
'json'
)
);
}
throw error;
}
}
/**
* Connect all servers defined in a config file, auto-generating session names from entry names.
* Launches all bridge processes in parallel and displays status badges when done.
*/
export async function connectAllFromConfig(
configFile: string,
options: {
outputMode: OutputMode;
verbose?: boolean;
headers?: string[];
timeout?: number;
profile?: string;
noProfile?: boolean;
proxy?: string;
proxyBearerToken?: string;
x402?: boolean;
insecure?: boolean;
}
): Promise<void> {
const config = loadConfig(configFile);
const serverNames = listServers(config);
if (serverNames.length === 0) {
throw new ClientError(`No servers found in config file: ${configFile}`);
}
if (options.outputMode === 'human') {
console.log(
chalk.cyan(
`Connecting ${serverNames.length} server${serverNames.length === 1 ? '' : 's'} from ${configFile}...`
)
);
}
// Prepare entries with deterministic session names derived from entry names.
// Re-running `mcpc connect <file>` reuses existing sessions via connectSession's
// "already active" path instead of creating @entry-2 duplicates.
const entries = serverNames.map((entry) => ({
entry,
sessionName: generateSessionName({ type: 'config', file: configFile, entry }),
}));
// Pre-check which sessions are already live (for accurate status badges)
const liveSet = new Set<string>();
for (const { sessionName } of entries) {
const session = await getSession(sessionName);
if (session && getBridgeStatus(session) === 'live') {
liveSet.add(sessionName);
}
}
// Launch all connections in parallel (quiet mode — we display results below)
const settled = await Promise.allSettled(
entries.map(async ({ entry, sessionName }) =>
connectSession(entry, sessionName, {
...options,
config: configFile,
skipDetails: true,
quiet: true,
})
)
);
// Build results with status badges
type ConnectResult = {
entry: string;
sessionName: string;
status: 'created' | 'active' | 'reconnected' | 'failed';
error?: string;
};
const results: ConnectResult[] = settled.map((outcome, i) => {
const { entry, sessionName } = entries[i]!;
if (outcome.status === 'fulfilled') {
if (liveSet.has(sessionName)) {
return { entry, sessionName, status: 'active' };
}
return { entry, sessionName, status: 'created' };
}
const error = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
return { entry, sessionName, status: 'failed', error };
});
// Display badges
if (options.outputMode === 'human') {
for (const r of results) {
const name = chalk.cyan(r.sessionName);
switch (r.status) {
case 'created':
// Bridge started but MCP handshake not yet verified
console.log(` ${chalk.yellow('●')} ${name} ${chalk.yellow('connecting')}`);
break;
case 'active':
console.log(` ${chalk.green('●')} ${name} ${chalk.dim('already active')}`);
break;
case 'reconnected':
console.log(` ${chalk.yellow('●')} ${name} ${chalk.yellow('reconnecting')}`);
break;
case 'failed':
console.log(
` ${chalk.red('●')} ${name} ${chalk.red('failed')}${r.error ? chalk.dim(` — ${r.error}`) : ''}`
);
break;
}
}
}
const active = results.filter((r) => r.status === 'active').length;
const connecting = results.filter(
(r) => r.status === 'created' || r.status === 'reconnected'
).length;
const failed = results.filter((r) => r.status === 'failed').length;
if (options.outputMode === 'json') {
console.log(
formatOutput(
{
configFile,
results: results.map((r) => ({
entry: r.entry,
sessionName: r.sessionName,
status: r.status,
...(r.error && { error: r.error }),
})),
},
'json'
)
);
} else if (results.length > 1) {
const parts: string[] = [];
if (active > 0) parts.push(`${active} already active`);
if (connecting > 0) parts.push(`${connecting} connecting`);
if (failed > 0) parts.push(`${failed} failed`);
const summary = parts.join(', ');
if (failed === 0) {
console.log(formatSuccess(summary));
} else if (active + connecting > 0) {
console.log(formatWarning(summary));
}
}