-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathindex.ts
More file actions
1460 lines (1288 loc) · 49.9 KB
/
index.ts
File metadata and controls
1460 lines (1288 loc) · 49.9 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
/**
* Bridge process for maintaining persistent MCP connections
* This executable is spawned by the CLI and maintains a long-running connection to an MCP server
* It communicates with the CLI via Unix domain sockets
*/
import { initProxy, proxyFetch } from '../lib/proxy.js';
import { createServer, type Server as NetServer, type Socket } from 'net';
import { unlink } from 'fs/promises';
import { createMcpClient, CreateMcpClientOptions } from '../core/index.js';
import type { McpClient } from '../core/index.js';
import type { ServerConfig, IpcMessage, LoggingLevel } from '../lib/index.js';
import { KEEPALIVE_INTERVAL_MS } from '../lib/types.js';
import { createLogger, setVerbose, initFileLogger, closeFileLogger } from '../lib/index.js';
import {
fileExists,
getBridgesDir,
getSocketPath,
ensureDir,
cleanupOrphanedLogFiles,
isSessionExpiredError,
} from '../lib/index.js';
import { ClientError, NetworkError, AuthError, isAuthenticationError } from '../lib/index.js';
import { getSession, loadSessions, updateSession } from '../lib/sessions.js';
import type { AuthCredentials, X402WalletCredentials } from '../lib/types.js';
import { OAuthTokenManager } from '../lib/auth/oauth-token-manager.js';
import { OAuthProvider } from '../lib/auth/oauth-provider.js';
import { storeKeychainOAuthTokenInfo, readKeychainOAuthTokenInfo } from '../lib/auth/keychain.js';
import { updateAuthProfileRefreshedAt } from '../lib/auth/profiles.js';
import { readKeychainProxyBearerToken } from '../lib/auth/keychain.js';
import {
LoggingMessageNotificationSchema,
type Tool,
type Resource,
type Prompt,
type Task,
} from '@modelcontextprotocol/sdk/types.js';
import type { TaskUpdate } from '../lib/types.js';
import { createRequire } from 'module';
const { version: mcpcVersion } = createRequire(import.meta.url)('../../package.json') as {
version: string;
};
import { ProxyServer } from './proxy-server.js';
import type { ProxyConfig } from '../lib/types.js';
import { createX402FetchMiddleware } from '../lib/x402/fetch-middleware.js';
import type { SignerWallet } from '../lib/x402/signer.js';
import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
// HTTP proxy and TLS settings are configured in main() after parsing --insecure flag
// KEEPALIVE_INTERVAL_MS imported from ../lib/types.js
// Maximum IPC buffer size (10 MB) — destroy socket if exceeded
const MAX_BUFFER_SIZE = 10 * 1024 * 1024;
const logger = createLogger('bridge');
interface BridgeOptions {
sessionName: string;
serverConfig: ServerConfig;
verbose?: boolean;
profileName?: string; // Auth profile name for token refresh
proxyConfig?: ProxyConfig; // Proxy server configuration
mcpSessionId?: string; // MCP session ID for resumption (Streamable HTTP only)
x402?: boolean; // Enable x402 auto-payment
insecure?: boolean; // Skip TLS certificate verification
}
/**
* Bridge process class
* Manages MCP connection and Unix socket server for a single session
*/
class BridgeProcess {
private client: McpClient | null = null;
private server: NetServer | null = null;
private proxyServer: ProxyServer | null = null;
private connections: Set<Socket> = new Set();
private options: BridgeOptions;
private socketPath: string;
private isShuttingDown = false;
private keepaliveInterval: NodeJS.Timeout | null = null;
// OAuth token manager (created when CLI sends auth credentials via IPC)
private tokenManager: OAuthTokenManager | null = null;
// OAuth provider for SDK transport (wraps tokenManager)
private authProvider: OAuthProvider | null = null;
// HTTP headers (received via IPC, stored in memory only)
private headers: Record<string, string> | null = null;
// x402 wallet for automatic payment signing (received via IPC, stored in memory only)
private x402Wallet: SignerWallet | null = null;
// Active async tasks (in-memory, also persisted to disk for crash recovery)
private activeTasks: Map<string, Task> = new Map();
// Promise to track when auth credentials are received (for startup sequencing)
private authCredentialsReceived: Promise<void> | null = null;
private authCredentialsResolver: (() => void) | null = null;
// Promise to track when x402 wallet is received (for startup sequencing)
private x402WalletReceived: Promise<void> | null = null;
private x402WalletResolver: (() => void) | null = null;
// Promise to track when MCP client is connected (for blocking requests until ready)
private mcpClientReady: Promise<void>;
private mcpClientReadyResolver!: () => void;
private mcpClientReadyRejecter!: (error: Error) => void;
constructor(options: BridgeOptions) {
this.options = options;
// Compute socket path from session name (platform-aware: Unix socket or Windows named pipe)
this.socketPath = getSocketPath(options.sessionName);
// Create promise that resolves when MCP client connects
this.mcpClientReady = new Promise<void>((resolve, reject) => {
this.mcpClientReadyResolver = resolve;
this.mcpClientReadyRejecter = reject;
});
if (options.verbose) {
setVerbose(true);
}
}
/**
* Set auth credentials received from CLI via IPC
* Handles both OAuth (with refresh token) and HTTP headers
*/
setAuthCredentials(credentials: AuthCredentials): void {
logger.info(`Received auth credentials for profile: ${credentials.profileName}`);
logger.debug(` serverUrl: ${credentials.serverUrl}`);
logger.debug(` refreshToken: ${credentials.refreshToken ? 'present' : 'MISSING'}`);
logger.debug(` clientId: ${credentials.clientId ? 'present' : 'MISSING'}`);
logger.debug(` headers: ${credentials.headers ? Object.keys(credentials.headers).length : 0}`);
// Set up OAuth token manager if refresh token and client ID are provided
if (credentials.refreshToken && credentials.clientId) {
this.tokenManager = new OAuthTokenManager({
serverUrl: credentials.serverUrl,
profileName: credentials.profileName,
clientId: credentials.clientId,
refreshToken: credentials.refreshToken,
// Reload tokens from keychain before refresh (handles token rotation by other processes)
onBeforeRefresh: async () => {
logger.debug('Reloading tokens from keychain before refresh...');
const tokenInfo = await readKeychainOAuthTokenInfo(
credentials.serverUrl,
credentials.profileName
);
if (!tokenInfo) {
logger.debug('No tokens found in keychain');
return undefined;
}
logger.debug('Loaded tokens from keychain');
// Build result object with only defined properties (for exactOptionalPropertyTypes)
const result: {
refreshToken?: string;
accessToken?: string;
accessTokenExpiresAt?: number;
} = {
accessToken: tokenInfo.accessToken,
};
if (tokenInfo.refreshToken) {
result.refreshToken = tokenInfo.refreshToken;
}
if (tokenInfo.expiresAt !== undefined) {
result.accessTokenExpiresAt = tokenInfo.expiresAt;
}
return result;
},
// Persist new tokens when refresh token rotation happens
onTokenRefresh: async (tokens) => {
logger.debug('Token refresh detected, persisting new tokens to keychain');
const tokenInfo: Parameters<typeof storeKeychainOAuthTokenInfo>[2] = {
accessToken: tokens.access_token,
tokenType: tokens.token_type,
};
if (tokens.expires_in !== undefined) {
tokenInfo.expiresIn = tokens.expires_in;
tokenInfo.expiresAt = Math.floor(Date.now() / 1000) + tokens.expires_in;
}
if (tokens.refresh_token !== undefined) {
tokenInfo.refreshToken = tokens.refresh_token;
}
if (tokens.scope !== undefined) {
tokenInfo.scope = tokens.scope;
}
await storeKeychainOAuthTokenInfo(
credentials.serverUrl,
credentials.profileName,
tokenInfo
);
// Update profile's refreshedAt timestamp (atomic operation)
await updateAuthProfileRefreshedAt(credentials.serverUrl, credentials.profileName);
logger.debug('Profile refreshedAt timestamp updated');
logger.debug('New tokens persisted to keychain');
},
});
logger.debug('OAuth token manager initialized');
// Create auth provider for SDK transport (enables automatic token refresh)
this.authProvider = new OAuthProvider({
serverUrl: credentials.serverUrl,
profileName: credentials.profileName,
tokenManager: this.tokenManager,
clientId: credentials.clientId,
});
logger.debug('OAuthProvider created for SDK transport (runtime mode)');
} else if (credentials.refreshToken && !credentials.clientId) {
logger.warn('Refresh token provided but client ID is missing - token refresh will not work');
}
// Store headers if provided (used when no OAuth refresh token available)
if (credentials.headers) {
this.headers = credentials.headers;
logger.debug(`Stored headers "${Object.keys(this.headers).join(', ')}" in memory`);
}
// Signal that auth credentials have been received (unblocks startup)
if (this.authCredentialsResolver) {
this.authCredentialsResolver();
this.authCredentialsResolver = null;
}
}
/**
* Set x402 wallet received from CLI via IPC
* The wallet private key is used for automatic payment signing
*/
setX402Wallet(credentials: X402WalletCredentials): void {
logger.info(`Received x402 wallet: ${credentials.address}`);
this.x402Wallet = {
privateKey: credentials.privateKey,
address: credentials.address,
};
logger.debug('x402 wallet stored in memory');
// Signal that wallet has been received (unblocks startup)
if (this.x402WalletResolver) {
this.x402WalletResolver();
this.x402WalletResolver = null;
}
}
/**
* Get a valid access token, refreshing if necessary,
* and update transport config with headers
*
* Priority:
* 1. OAuth token manager (uses refresh token to get fresh access token)
* 2. HTTP headers (static headers from --header flags)
*/
private async updateTransportAuth(): Promise<ServerConfig> {
const config = { ...this.options.serverConfig };
// Only update auth for HTTP transport
if (!config.url) {
return config;
}
try {
// Priority 1: Use OAuth token manager if available (can refresh tokens)
if (this.tokenManager) {
const token = await this.tokenManager.getValidAccessToken();
config.headers = {
...this.headers, // Include any other headers from --header flags
...config.headers,
Authorization: `Bearer ${token}`, // OAuth token takes priority
};
logger.debug('Updated transport config with fresh OAuth access token');
return config;
}
// Priority 2: Use static headers if available
if (this.headers) {
config.headers = {
...config.headers,
...this.headers,
};
logger.debug(`Updated transport config with ${Object.keys(this.headers).length} headers`);
return config;
}
} catch (error) {
logger.error('Failed to get access token:', error);
// Mark session as unauthorized if token refresh fails
await this.markSessionStatusAndExit('unauthorized');
throw error;
}
return config;
}
/**
* Clean up log files for sessions that no longer exist
* Runs asynchronously without blocking bridge startup
*/
private runOrphanedLogCleanup(): void {
// Run cleanup asynchronously without blocking startup
void (async () => {
try {
logger.debug('Starting cleanup of orphaned log files');
// Load active sessions
const sessionsStorage = await loadSessions();
const activeSessions = sessionsStorage.sessions;
// Clean orphaned logs, skipping current session
const deleted = await cleanupOrphanedLogFiles(activeSessions, {
skipSession: this.options.sessionName,
});
logger.debug(`Finished cleanup of orphaned log files (deleted: ${deleted})`);
} catch (error) {
// Don't fail startup if cleanup fails
logger.warn('Failed to clean up orphaned log files:', error);
}
})();
}
/**
* Start the bridge process for a specific session.
*/
async start(): Promise<void> {
// 1. First, initialize file logger to see what's going on
await initFileLogger(`bridge-${this.options.sessionName}.log`, {
version: mcpcVersion,
command: process.argv.slice(1).join(' '),
});
logger.info(`Bridge process starting for session: ${this.options.sessionName}`);
if (this.options.insecure) {
logger.warn('TLS certificate verification is disabled (--insecure)');
}
// 2. Clean up orphaned log files (runs asynchronously in background)
this.runOrphanedLogCleanup();
try {
// 3. Create Unix socket server FIRST (so CLI can send auth credentials)
await this.createSocketServer();
// 4. Wait for auth credentials and/or x402 wallet from CLI via IPC
// The CLI sends these immediately after detecting the socket file
const ipcWaiters: Promise<void>[] = [];
if (this.options.profileName) {
logger.debug(`Waiting for auth credentials (profile: ${this.options.profileName})...`);
this.authCredentialsReceived = new Promise<void>((resolve) => {
this.authCredentialsResolver = resolve;
});
ipcWaiters.push(this.authCredentialsReceived);
}
if (this.options.x402) {
logger.debug('Waiting for x402 wallet...');
this.x402WalletReceived = new Promise<void>((resolve) => {
this.x402WalletResolver = resolve;
});
ipcWaiters.push(this.x402WalletReceived);
}
if (ipcWaiters.length > 0) {
// Wait with timeout (5 seconds should be plenty for local IPC)
const timeout = new Promise<void>((_, reject) => {
setTimeout(() => reject(new Error('Timeout waiting for IPC credentials')), 5000);
});
await Promise.race([Promise.all(ipcWaiters), timeout]);
logger.debug('IPC credentials received, proceeding with MCP connection');
}
// 5. Connect to MCP server (now with auth credentials if provided)
try {
await this.connectToMcp();
// 5b. Start proxy server if configured (BEFORE signaling ready)
if (this.options.proxyConfig && this.client) {
await this.startProxyServer();
}
// Signal that MCP client is ready (unblocks pending requests)
// Only signal after both MCP connection AND proxy server are ready
this.mcpClientReadyResolver();
} catch (error) {
// Signal that MCP connection or proxy startup failed (rejects pending requests with actual error)
// Don't exit immediately - stay alive briefly so CLI can receive the error
logger.error(
'Bridge startup failed, will stay alive briefly for CLI to receive error:',
error
);
this.mcpClientReadyRejecter(error as Error);
// If the error was due to session ID rejection or auth failure, mark session status
// User must explicitly use 'mcpc @session restart' or 'mcpc login' to recover
const errorMsg = (error as Error).message || '';
if (isSessionExpiredError(errorMsg)) {
logger.warn('Session rejected by server (expired session ID), marking as expired');
try {
await updateSession(this.options.sessionName, { status: 'expired' });
} catch (updateError) {
logger.error('Failed to mark session as expired:', updateError);
}
} else if (isAuthenticationError(errorMsg)) {
logger.warn('Server requires authentication, marking as unauthorized');
try {
await updateSession(this.options.sessionName, { status: 'unauthorized' });
} catch (updateError) {
logger.error('Failed to mark session as unauthorized:', updateError);
}
}
// Set up signal handlers so we can be killed
this.setupSignalHandlers();
// Stay alive for 10 seconds to allow CLI to connect and get the error
// Then shutdown gracefully
setTimeout(() => {
logger.info('Shutting down after startup failure');
this.shutdown().catch(() => process.exit(1));
}, 10_000);
return; // Don't continue with keepalive etc
}
// 6. Start keepalive ping
this.startKeepalive();
// 7. Set up signal handlers
this.setupSignalHandlers();
logger.info('Bridge process started successfully');
} catch (error) {
logger.error('Failed to start bridge:', error);
await this.cleanup();
throw error;
}
}
/**
* Broadcast a notification to all connected clients
*/
private broadcastNotification(method: string, params?: unknown): void {
const notification: IpcMessage = {
type: 'notification',
notification: {
method: method as IpcMessage['notification'] extends { method: infer M } ? M : never,
params,
},
};
const data = JSON.stringify(notification) + '\n';
for (const socket of this.connections) {
try {
socket.write(data);
} catch (error) {
logger.error('Failed to send notification to client:', error);
}
}
}
/**
* Update session with notification timestamp for list changes
*/
private async updateNotificationTimestamp(
type: 'tools' | 'prompts' | 'resources'
): Promise<void> {
const now = new Date().toISOString();
await updateSession(this.options.sessionName, {
notifications: {
[type]: { listChangedAt: now },
},
});
logger.debug(`Updated ${type} listChangedAt timestamp`);
}
/**
* Connect to the MCP server
*/
private async connectToMcp(): Promise<void> {
logger.debug('Connecting to MCP server...');
logger.debug(` authProvider: ${this.authProvider ? 'present' : 'NOT SET'}`);
logger.debug(` tokenManager: ${this.tokenManager ? 'present' : 'NOT SET'}`);
logger.debug(` headers: ${this.headers ? Object.keys(this.headers).join(', ') : 'none'}`);
// Get transport config
let serverConfig: ServerConfig;
if (this.authProvider) {
// TODO: feels like this code should (is?) be handled by updateTransportAuth
// If we have an authProvider, DON'T add Authorization header to transport
// Let the SDK's authProvider handle token refresh automatically
// Only add non-OAuth headers (from --header flags) to transport
serverConfig = { ...this.options.serverConfig };
if (this.headers) {
serverConfig.headers = { ...serverConfig.headers, ...this.headers };
logger.debug(
`Added non-OAuth headers "${Object.keys(this.headers).join(', ')}" to transport`
);
}
} else {
// No authProvider - use updateTransportAuth for static headers
logger.debug('No authProvider - using updateTransportAuth for headers');
serverConfig = await this.updateTransportAuth();
}
logger.debug('Building MCP client config...');
logger.debug(` this.authProvider is set: ${!!this.authProvider}`);
logger.debug(` this.x402Wallet is set: ${!!this.x402Wallet}`);
if (this.authProvider) {
logger.debug(` authProvider type: ${this.authProvider.constructor.name}`);
}
// Build x402 fetch middleware if wallet is configured
let customFetch: FetchLike | undefined;
if (this.x402Wallet && serverConfig.url) {
logger.debug('Creating x402 fetch middleware for payment signing');
// We use a closure that defers tool lookup to the connected client
// The client may not have tools cached yet at this point, but will
// after it connects and receives the auto-refreshed tools list
const wallet = this.x402Wallet;
const getToolByName = (name: string): Tool | undefined => {
// McpClient caches tools in-memory after the first listAllTools call
return this.client?.getCachedTools()?.find((t: Tool) => t.name === name);
};
customFetch = createX402FetchMiddleware(proxyFetch as FetchLike, { wallet, getToolByName });
}
const clientConfig: CreateMcpClientOptions = {
clientInfo: { name: 'mcpc', version: mcpcVersion },
serverConfig,
capabilities: {
roots: { listChanged: true },
sampling: {},
tasks: {
list: {},
cancel: {},
requests: {
sampling: { createMessage: {} },
},
},
},
// Pass auth provider for automatic token refresh (HTTP transport only)
...(this.authProvider && { authProvider: this.authProvider }),
// Pass session ID for resumption (HTTP transport only)
...(this.options.mcpSessionId && { mcpSessionId: this.options.mcpSessionId }),
// Pass x402 fetch middleware (HTTP transport only)
...(customFetch && { customFetch }),
listChanged: {
tools: {
// We handle refresh ourselves to fetch ALL pages (SDK only fetches the first page).
// SDK's debounceMs still applies, preventing multiple rapid refreshes.
autoRefresh: false,
onChanged: () => {
logger.debug('Tools list changed notification received, refreshing all tools...');
if (this.client) {
this.client.listAllTools({ refreshCache: true }).catch((err) => {
logger.warn('Failed to refresh tools cache:', err);
});
}
// Broadcast notification to all connected clients
this.broadcastNotification('tools/list_changed');
// Update session with notification timestamp
this.updateNotificationTimestamp('tools').catch((err) => {
logger.warn('Failed to update tools notification timestamp:', err);
});
},
},
resources: {
autoRefresh: true,
onChanged: (error: Error | null, resources: Resource[] | null) => {
logger.debug('Resources list changed', { error, count: resources?.length });
// Broadcast notification to all connected clients
this.broadcastNotification('resources/list_changed');
// Update session with notification timestamp
this.updateNotificationTimestamp('resources').catch((err) => {
logger.warn('Failed to update resources notification timestamp:', err);
});
},
},
prompts: {
autoRefresh: true,
onChanged: (error: Error | null, prompts: Prompt[] | null) => {
logger.debug('Prompts list changed', { error, count: prompts?.length });
// Broadcast notification to all connected clients
this.broadcastNotification('prompts/list_changed');
// Update session with notification timestamp
this.updateNotificationTimestamp('prompts').catch((err) => {
logger.warn('Failed to update prompts notification timestamp:', err);
});
},
},
},
autoConnect: true,
verbose: this.options.verbose || false,
};
logger.debug('Calling createMcpClient with authProvider:', !!clientConfig.authProvider);
if (clientConfig.mcpSessionId) {
logger.info(
`Attempting session resumption with MCP-Session-Id: ${clientConfig.mcpSessionId}`
);
}
// Connect to MCP server - if session ID is rejected, this will throw
// and the bridge will mark the session as expired (user must explicitly restart)
this.client = await createMcpClient(clientConfig);
logger.info('Connected to MCP server');
logger.debug('MCP client created successfully, authProvider was:', !!clientConfig.authProvider);
// Forward server logging messages to connected IPC clients
this.client
.getSDKClient()
.setNotificationHandler(LoggingMessageNotificationSchema, (notification) => {
this.broadcastNotification('logging/message', notification.params);
});
// Update session with protocol version, MCP session ID, and lastSeenAt
const serverDetails = await this.client.getServerDetails();
const newMcpSessionId = this.client.getMcpSessionId();
const sessionUpdate: Parameters<typeof updateSession>[1] = {
lastSeenAt: new Date().toISOString(),
};
if (serverDetails.protocolVersion) {
sessionUpdate.protocolVersion = serverDetails.protocolVersion;
}
if (serverDetails.serverInfo) {
sessionUpdate.serverInfo = serverDetails.serverInfo;
}
if (newMcpSessionId) {
sessionUpdate.mcpSessionId = newMcpSessionId;
logger.info(`MCP-Session-Id saved for resumption: ${newMcpSessionId}`);
}
await updateSession(this.options.sessionName, sessionUpdate);
// Note: Token refresh is handled automatically by the SDK
// The SDK calls authProvider.tokens() before each request,
// which triggers OAuthTokenManager.getValidAccessToken() to refresh if needed
// Pre-populate tools cache (used by x402 proactive signing and listAllTools IPC method)
if (serverDetails.capabilities?.tools) {
await this.client.listAllTools({ refreshCache: true }).catch((err) => {
logger.warn('Failed to pre-populate tools cache:', err);
});
}
}
/**
* Start the proxy MCP server
* Creates an HTTP server that forwards MCP requests to upstream client
*/
private async startProxyServer(): Promise<void> {
if (!this.options.proxyConfig || !this.client) {
return;
}
const { host, port } = this.options.proxyConfig;
// Load proxy bearer token from keychain if stored
const bearerToken = await readKeychainProxyBearerToken(this.options.sessionName);
logger.info(`Starting proxy server on ${host}:${port}`);
if (bearerToken) {
logger.debug('Proxy server will require bearer token authentication');
}
// Get upstream server instructions to pass to proxy clients
const serverDetails = await this.client.getServerDetails();
const instructions = serverDetails.instructions;
const proxyOptions: ConstructorParameters<typeof ProxyServer>[0] = {
host,
port,
client: this.client,
sessionName: this.options.sessionName,
};
if (bearerToken) {
proxyOptions.bearerToken = bearerToken;
}
if (instructions) {
proxyOptions.instructions = instructions;
}
this.proxyServer = new ProxyServer(proxyOptions);
await this.proxyServer.start();
logger.info(`Proxy server started at ${this.proxyServer.getAddress()}`);
}
/**
* Start periodic keepalive ping to maintain connection
*/
private startKeepalive(): void {
logger.debug(`Starting keepalive ping every ${KEEPALIVE_INTERVAL_MS / 1000}s`);
this.keepaliveInterval = setInterval(() => {
this.sendKeepalivePing().catch((error) => {
logger.error('Keepalive ping failed:', error);
// If ping fails, the session might be expired - check and handle
this.handlePossibleExpiration(error as Error);
});
}, KEEPALIVE_INTERVAL_MS);
// Don't block process exit waiting for this interval
this.keepaliveInterval.unref();
}
/**
* Send a single keepalive ping to the MCP server
*/
private async sendKeepalivePing(): Promise<void> {
if (!this.client || this.isShuttingDown) {
return;
}
logger.debug('Sending keepalive ping');
await this.client.ping();
logger.debug('Keepalive ping successful');
// Update lastSeenAt on successful ping
await this.updateLastSeenAt();
}
/**
* Update lastSeenAt timestamp to track when server was last responsive
*/
private async updateLastSeenAt(): Promise<void> {
try {
await updateSession(this.options.sessionName, {
lastSeenAt: new Date().toISOString(),
});
} catch (error) {
// Don't fail operations if timestamp update fails
logger.error('Failed to update lastSeenAt:', error);
}
}
/**
* Check if an error indicates session expiration or auth failure and handle accordingly.
* Session expiry is checked first since it's more specific (404/session-not-found),
* while auth errors are broader (401/403/unauthorized) and could overlap.
*/
private handlePossibleExpiration(error: Error): void {
if (isSessionExpiredError(error.message)) {
logger.warn('Session appears to be expired, marking as expired and shutting down');
this.markSessionStatusAndExit('expired').catch((e) => {
logger.error('Failed to mark session as expired:', e);
process.exit(1);
});
} else if (isAuthenticationError(error.message)) {
logger.warn('Authentication rejected, marking session as unauthorized and shutting down');
this.markSessionStatusAndExit('unauthorized').catch((e) => {
logger.error('Failed to mark session as unauthorized:', e);
process.exit(1);
});
}
}
/**
* Mark the session with given status in sessions.json and exit
*/
private async markSessionStatusAndExit(status: 'expired' | 'unauthorized'): Promise<void> {
if (this.isShuttingDown) {
return;
}
try {
await updateSession(this.options.sessionName, { status });
logger.info(`Session ${this.options.sessionName} marked as ${status}`);
} catch (error) {
logger.error('Failed to update session status:', error);
}
// Gracefully shutdown
await this.shutdown();
}
/**
* Create socket server for IPC (Unix domain socket or Windows named pipe)
*/
private async createSocketServer(): Promise<void> {
// Ensure bridges directory exists (for Unix sockets; Windows named pipes don't need this)
if (process.platform !== 'win32') {
await ensureDir(getBridgesDir());
// Remove existing socket file if it exists (Unix only).
// Fail on error
if (await fileExists(this.socketPath)) {
logger.debug(`Removing existing socket: ${this.socketPath}`);
await unlink(this.socketPath);
}
}
// Create server
const server = createServer((socket) => this.handleConnection(socket));
this.server = server;
// Listen on socket/pipe
await new Promise<void>((resolve, reject) => {
server.listen(this.socketPath, () => {
logger.info(`Socket server listening: ${this.socketPath}`);
resolve();
});
server.on('error', (error) => {
logger.error('Socket server error:', error);
reject(error);
});
});
}
/**
* Handle a new client connection
*/
private handleConnection(socket: Socket): void {
logger.debug('New client connected');
this.connections.add(socket);
let buffer = '';
socket.on('data', (data) => {
buffer += data.toString();
if (buffer.length > MAX_BUFFER_SIZE) {
logger.error(`IPC buffer exceeded ${MAX_BUFFER_SIZE} bytes, destroying socket`);
socket.destroy();
this.connections.delete(socket);
return;
}
// Process complete JSON messages (newline-delimited)
let newlineIndex: number;
while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, newlineIndex);
buffer = buffer.slice(newlineIndex + 1);
if (line.trim()) {
this.handleMessage(socket, line).catch((error) => {
logger.error('Error handling message:', error);
});
}
}
});
socket.on('end', () => {
logger.debug('Client disconnected');
this.connections.delete(socket);
});
socket.on('error', (error) => {
logger.error('Socket error:', error);
this.connections.delete(socket);
});
}
/**
* Handle an IPC message from the CLI
*/
private async handleMessage(socket: Socket, data: string): Promise<void> {
let messageId: string | undefined;
try {
const message = JSON.parse(data) as IpcMessage;
messageId = message.id;
logger.debug('Received message:', { type: message.type, method: message.method });
// Handle different message types
switch (message.type) {
case 'request':
await this.handleMcpRequest(socket, message);
break;
case 'shutdown':
logger.info('Received shutdown request');
if (message.id) {
this.sendResponse(socket, { type: 'response', id: message.id });
}
await this.shutdown();
break;
case 'set-auth-credentials':
if (message.authCredentials) {
this.setAuthCredentials(message.authCredentials);
if (message.id) {
this.sendResponse(socket, {
type: 'response',
id: message.id,
result: { success: true },
});
}
} else {
throw new ClientError('Missing authCredentials in set-auth-credentials message');
}
break;
case 'set-x402-wallet':
if (message.x402Wallet) {
this.setX402Wallet(message.x402Wallet);
if (message.id) {
this.sendResponse(socket, {
type: 'response',
id: message.id,
result: { success: true },
});
}
} else {
throw new ClientError('Missing x402Wallet in set-x402-wallet message');
}
break;
default:
throw new ClientError(`Unknown message type: ${message.type}`);
}
} catch (error) {
logger.error('Failed to handle message:', error);
this.sendError(socket, error as Error, messageId);
}
}
/**
* Forward an MCP request to the MCP server
* Blocks until MCP client is connected, propagates connection errors to caller
*/
private async handleMcpRequest(socket: Socket, message: IpcMessage): Promise<void> {
logger.debug(`>>> handleMcpRequest: ${message.method} <<<`);
// Wait for MCP client to be ready (blocks if still connecting, throws if connection failed)
await this.mcpClientReady;
if (!this.client) {
// Should never happen after mcpClientReady resolves, but TypeScript needs this check
throw new NetworkError('MCP client not connected');
}
if (!message.method) {
throw new ClientError('Missing method in request');
}
// Log auth state before making request
logger.debug(` authProvider is set: ${!!this.authProvider}`);
if (this.tokenManager) {
const expiresIn = this.tokenManager.getSecondsUntilExpiry();
logger.debug(` token expires in: ${expiresIn} seconds`);
}
try {
// Apply per-request timeout if provided (from CLI --timeout flag, in seconds → milliseconds)
if (message.timeout !== undefined) {
this.client.setRequestTimeout(message.timeout * 1000);
}
let result: unknown;
// Route to appropriate client method
switch (message.method) {
case 'ping':
result = await this.client.ping();
break;
case 'listTools': {
const cursor = message.params as string | undefined;
result = await this.client.listTools(cursor);
break;
}
case 'callTool': {
const params = message.params as {
name: string;
arguments?: Record<string, unknown>;
_meta?: Record<string, unknown>;
useTask?: boolean;
detach?: boolean;
};
if (params.useTask && this.client.supportsTasksForToolCall()) {
if (params.detach) {
// Detached execution: start task and return task ID immediately
// The tool continues running in the background on the server
const taskUpdate = await this.client.callToolDetached(
params.name,
params.arguments,
params._meta
);
this.activeTasks.set(taskUpdate.taskId, {
taskId: taskUpdate.taskId,
status: taskUpdate.status,
statusMessage: taskUpdate.statusMessage,
createdAt: taskUpdate.createdAt ?? new Date().toISOString(),
lastUpdatedAt: taskUpdate.lastUpdatedAt ?? new Date().toISOString(),
} as Task);
await this.persistActiveTask(taskUpdate.taskId, params.name);
result = taskUpdate;
} else {
// Task-augmented tool call: stream updates to requesting socket
const onUpdate = (update: TaskUpdate): void => {
// Track active task