-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathsessions.ts
More file actions
722 lines (648 loc) · 22.1 KB
/
sessions.ts
File metadata and controls
722 lines (648 loc) · 22.1 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
/**
* Sessions command handlers
*/
import { createServer } from 'net';
import {
OutputMode,
isValidSessionName,
validateProfileName,
isProcessAlive,
getServerHost,
redactHeaders,
} from '../../lib/index.js';
import { DISCONNECTED_THRESHOLD_MS } from '../../lib/types.js';
import type { ServerConfig, ProxyConfig } from '../../lib/types.js';
import {
formatOutput,
formatSuccess,
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,
} from '../../lib/sessions.js';
import { startBridge, StartBridgeOptions, stopBridge } from '../../lib/bridge-manager.js';
import {
storeKeychainSessionHeaders,
storeKeychainProxyBearerToken,
} from '../../lib/auth/keychain.js';
import { AuthError, ClientError } 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';
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);
});
}
/**
* 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;
}
): 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') {
console.log(formatSuccess(`Session ${name} is already active`));
}
await showServerDetails(name, { ...options, hideTarget: false });
return;
}
// Bridge has crashed or expired - reconnect with warning
if (options.outputMode === 'human') {
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
const serverConfig = 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)
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 {
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(),
...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 (socket path is computed from session name)
await updateSession(name, { pid });
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;
}
// Success! Show server info like when running "mcpc <target>"
if (options.outputMode === 'human') {
console.log(formatSuccess(`Session ${name} ${isReconnect ? 'reconnected' : 'created'}`));
}
// Display server info via the new session (best-effort).
// showServerDetails blocks until the bridge is connected (via health check),
// so by the time it returns or throws, we have definitive bridge status.
// Re-throw auth errors (real failures requiring user action), but swallow others
// (TLS errors, timeouts, etc.) since the session was created and can be used later.
try {
await showServerDetails(name, {
...options,
hideTarget: false, // Show session info prefix
});
} catch (detailsError) {
if (detailsError instanceof AuthError) {
throw detailsError;
}
logger.debug(
`showServerDetails failed for new session ${name}: ${(detailsError as Error).message}`
);
}
}
// DISCONNECTED_THRESHOLD_MS imported from ../../lib/types.js
type DisplayStatus = 'live' | 'disconnected' | 'crashed' | 'unauthorized' | 'expired';
/**
* Determine bridge status for a session
*/
function getBridgeStatus(session: {
status?: string;
pid?: number;
lastSeenAt?: string;
}): DisplayStatus {
if (session.status === 'unauthorized') {
return 'unauthorized';
}
if (session.status === 'expired') {
return 'expired';
}
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
*/
function formatBridgeStatus(status: DisplayStatus): { dot: string; text: string } {
switch (status) {
case 'live':
return { dot: chalk.green('●'), text: chalk.green('live') };
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
*/
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);
// 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 hint for unauthorized sessions
if (status === 'unauthorized') {
const target = getServerHost(session.server.url || session.server.command || '');
console.log(chalk.dim(` ↳ run: mcpc login ${target} && 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
await stopBridge(name);
// 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 && { tools }),
},
'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) {
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;
}
}
/**
* Show help for a server (alias for getInstructions)
*/
export async function showHelp(target: string, options: { outputMode: OutputMode }): Promise<void> {
await showServerDetails(target, options);
}
/**
* Open an interactive shell for a target
*/
export async function openShell(target: string): Promise<void> {
// Import shell dynamically to avoid circular dependencies
const { startShell } = await import('../shell.js');
await startShell(target);
}