-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathclient.ts
More file actions
480 lines (435 loc) · 13.1 KB
/
client.ts
File metadata and controls
480 lines (435 loc) · 13.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
/**
* MCP Client - Connection management for MCP servers
*/
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import type { Tool } from '@modelcontextprotocol/sdk/types.js';
import {
type HttpServerConfig,
type ServerConfig,
type StdioServerConfig,
debug,
filterTools,
getConcurrencyLimit,
getMaxRetries,
getRetryDelayMs,
getTimeoutMs,
isDaemonEnabled,
isHttpServer,
isToolAllowed,
} from './config.js';
import {
type DaemonConnection,
cleanupOrphanedDaemons,
getDaemonConnection,
} from './daemon-client.js';
import { VERSION } from './version.js';
// Re-export config utilities for convenience
export { debug, getTimeoutMs, getConcurrencyLimit };
export interface ConnectedClient {
client: Client;
close: () => Promise<void>;
}
/**
* Unified connection interface that works with both daemon and direct connections
*/
export interface McpConnection {
listTools: () => Promise<ToolInfo[]>;
callTool: (
toolName: string,
args: Record<string, unknown>,
) => Promise<unknown>;
getInstructions: () => Promise<string | undefined>;
close: () => Promise<void>;
isDaemon: boolean;
}
export interface ServerInfo {
name: string;
version?: string;
protocolVersion?: string;
}
export interface ToolInfo {
name: string;
description?: string;
inputSchema: Record<string, unknown>;
}
/**
* Retry configuration
*/
interface RetryConfig {
maxRetries: number;
baseDelayMs: number;
maxDelayMs: number;
totalBudgetMs: number;
}
/**
* Get retry config respecting MCP_TIMEOUT budget
*/
function getRetryConfig(): RetryConfig {
const totalBudgetMs = getTimeoutMs();
const maxRetries = getMaxRetries();
const baseDelayMs = getRetryDelayMs();
// Reserve at least 5s for the final attempt
const retryBudgetMs = Math.max(0, totalBudgetMs - 5000);
return {
maxRetries,
baseDelayMs,
maxDelayMs: Math.min(10000, retryBudgetMs / 2),
totalBudgetMs,
};
}
/**
* Check if an error is transient and worth retrying
* Uses error codes when available, falls back to message matching
*/
export function isTransientError(error: Error): boolean {
// Check error code first (more reliable than message matching)
const nodeError = error as NodeJS.ErrnoException;
if (nodeError.code) {
const transientCodes = [
'ECONNREFUSED',
'ECONNRESET',
'ETIMEDOUT',
'ENOTFOUND',
'EPIPE',
'ENETUNREACH',
'EHOSTUNREACH',
'EAI_AGAIN',
];
if (transientCodes.includes(nodeError.code)) {
return true;
}
}
// Fallback to message matching for errors without codes
const message = error.message;
// HTTP transient errors - require status code at start or with HTTP context
// Pattern: "502", "502 Bad Gateway", "HTTP 502", "status 502", "status code 502"
if (/^(502|503|504|429)\b/.test(message)) return true;
if (/\b(http|status(\s+code)?)\s*(502|503|504|429)\b/i.test(message))
return true;
if (
/\b(502|503|504|429)\s+(bad gateway|service unavailable|gateway timeout|too many requests)/i.test(
message,
)
)
return true;
// Generic network terms - more specific patterns
if (/network\s*(error|fail|unavailable|timeout)/i.test(message)) return true;
if (/connection\s*(reset|refused|timeout)/i.test(message)) return true;
if (/\btimeout\b/i.test(message)) return true;
return false;
}
/**
* Calculate delay with exponential backoff and jitter
*/
function calculateDelay(attempt: number, config: RetryConfig): number {
const exponentialDelay = config.baseDelayMs * 2 ** attempt;
const cappedDelay = Math.min(exponentialDelay, config.maxDelayMs);
// Add jitter (±25%)
const jitter = cappedDelay * 0.25 * (Math.random() * 2 - 1);
return Math.round(cappedDelay + jitter);
}
/**
* Sleep for specified milliseconds
*/
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Whether server stderr should be streamed live to the terminal.
*
* Default is quiet to avoid noisy MCP/LSP server logs polluting stdout/stderr
* for normal CLI use and AI-agent pipelines. Use MCP_DEBUG=1 to see live logs.
*/
export function shouldStreamServerStderr(): boolean {
return Boolean(process.env.MCP_DEBUG);
}
/**
* Execute a function with retry logic for transient failures
* Respects overall timeout budget from MCP_TIMEOUT
*/
async function withRetry<T>(
fn: () => Promise<T>,
operationName: string,
config: RetryConfig = getRetryConfig(),
): Promise<T> {
let lastError: Error | undefined;
const startTime = Date.now();
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
// Check if we've exceeded the total timeout budget
const elapsed = Date.now() - startTime;
if (elapsed >= config.totalBudgetMs) {
debug(`${operationName}: timeout budget exhausted after ${elapsed}ms`);
break;
}
try {
return await fn();
} catch (error) {
lastError = error as Error;
const remainingBudget = config.totalBudgetMs - (Date.now() - startTime);
const shouldRetry =
attempt < config.maxRetries &&
isTransientError(lastError) &&
remainingBudget > 1000; // At least 1s remaining
if (shouldRetry) {
const delay = Math.min(
calculateDelay(attempt, config),
remainingBudget - 1000,
);
debug(
`${operationName} failed (attempt ${attempt + 1}/${config.maxRetries + 1}): ${lastError.message}. Retrying in ${delay}ms...`,
);
await sleep(delay);
} else {
throw lastError;
}
}
}
throw lastError;
}
/**
* Safely close a connection, logging but not throwing on error
*/
export async function safeClose(close: () => Promise<void>): Promise<void> {
try {
await close();
} catch (err) {
debug(`Failed to close connection: ${(err as Error).message}`);
}
}
/**
* Connect to an MCP server with retry logic
* Captures stderr from stdio servers to include in error messages
*/
export async function connectToServer(
serverName: string,
config: ServerConfig,
): Promise<ConnectedClient> {
// Collect stderr for better error messages
const stderrChunks: string[] = [];
return withRetry(async () => {
const client = new Client(
{
name: 'mcp-cli',
version: VERSION,
},
{
capabilities: {},
},
);
let transport: StdioClientTransport | StreamableHTTPClientTransport;
if (isHttpServer(config)) {
transport = createHttpTransport(config);
} else {
transport = createStdioTransport(config);
// Capture stderr for debugging - attach BEFORE connect
// Only stream stderr live in debug mode to avoid noisy servers polluting output
const stderrStream = transport.stderr;
if (stderrStream) {
stderrStream.on('data', (chunk: Buffer) => {
const text = chunk.toString();
stderrChunks.push(text);
// In debug mode, show server stderr with server name prefix
if (shouldStreamServerStderr()) {
process.stderr.write(`[${serverName}] ${text}`);
}
});
}
}
try {
await client.connect(transport);
} catch (error) {
// Enhance error with captured stderr
const stderrOutput = stderrChunks.join('').trim();
if (stderrOutput) {
const err = error as Error;
err.message = `${err.message}\n\nServer stderr:\n${stderrOutput}`;
}
throw error;
}
// For successful connections, forward stderr to console only in debug mode
if (!isHttpServer(config)) {
const stderrStream = (transport as StdioClientTransport).stderr;
if (stderrStream) {
stderrStream.on('data', (chunk: Buffer) => {
if (shouldStreamServerStderr()) {
process.stderr.write(chunk);
}
});
}
}
return {
client,
close: async () => {
await client.close();
},
};
}, `connect to ${serverName}`);
}
/**
* Create HTTP transport for remote servers
*/
function createHttpTransport(
config: HttpServerConfig,
): StreamableHTTPClientTransport {
const url = new URL(config.url);
return new StreamableHTTPClientTransport(url, {
requestInit: {
headers: config.headers,
},
});
}
/**
* Create stdio transport for local servers
* Uses stderr: 'pipe' to capture server output for debugging
*/
function createStdioTransport(config: StdioServerConfig): StdioClientTransport {
// Merge process.env with config.env, filtering out undefined values
const mergedEnv: Record<string, string> = {};
for (const [key, value] of Object.entries(process.env)) {
if (value !== undefined) {
mergedEnv[key] = value;
}
}
if (config.env) {
Object.assign(mergedEnv, config.env);
}
return new StdioClientTransport({
command: config.command,
args: config.args,
env: mergedEnv,
cwd: config.cwd,
stderr: 'pipe', // Capture stderr for better error messages
});
}
/**
* List all tools from a connected client with retry logic
*/
export async function listTools(client: Client): Promise<ToolInfo[]> {
return withRetry(async () => {
const result = await client.listTools();
return result.tools.map((tool: Tool) => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema as Record<string, unknown>,
}));
}, 'list tools');
}
/**
* Get a specific tool by name
*/
export async function getTool(
client: Client,
toolName: string,
): Promise<ToolInfo | undefined> {
const tools = await listTools(client);
return tools.find((t) => t.name === toolName);
}
/**
* Call a tool with arguments and retry logic
*/
export async function callTool(
client: Client,
toolName: string,
args: Record<string, unknown>,
): Promise<unknown> {
return withRetry(async () => {
const result = await client.callTool(
{
name: toolName,
arguments: args,
},
undefined,
{ timeout: getTimeoutMs() },
);
return result;
}, `call tool ${toolName}`);
}
// ============================================================================
// Unified Connection Interface (Daemon + Direct)
// ============================================================================
/**
* Get a unified connection to an MCP server
*
* If daemon mode is enabled (default), tries to use a cached daemon connection.
* Falls back to direct connection if daemon fails or is disabled.
*
* @param serverName - Name of the server from config
* @param config - Server configuration
* @returns McpConnection with listTools, callTool, and close methods
*/
export async function getConnection(
serverName: string,
config: ServerConfig,
): Promise<McpConnection> {
// Clean up any orphaned daemons on first call
await cleanupOrphanedDaemons();
// Try daemon connection if enabled
if (isDaemonEnabled()) {
try {
const daemonConn = await getDaemonConnection(serverName, config);
if (daemonConn) {
debug(`Using daemon connection for ${serverName}`);
return {
async listTools(): Promise<ToolInfo[]> {
const data = await daemonConn.listTools();
const tools = data as ToolInfo[];
// Apply tool filtering from config
return filterTools(tools, config);
},
async callTool(
toolName: string,
args: Record<string, unknown>,
): Promise<unknown> {
// Check if tool is allowed before calling
if (!isToolAllowed(toolName, config)) {
throw new Error(
`Tool "${toolName}" is disabled by configuration`,
);
}
return daemonConn.callTool(toolName, args);
},
async getInstructions(): Promise<string | undefined> {
return daemonConn.getInstructions();
},
async close(): Promise<void> {
await daemonConn.close();
},
isDaemon: true,
};
}
} catch (err) {
debug(
`Daemon connection failed for ${serverName}: ${(err as Error).message}, falling back to direct`,
);
}
}
// Fall back to direct connection
debug(`Using direct connection for ${serverName}`);
const { client, close } = await connectToServer(serverName, config);
return {
async listTools(): Promise<ToolInfo[]> {
const tools = await listTools(client);
// Apply tool filtering from config
return filterTools(tools, config);
},
async callTool(
toolName: string,
args: Record<string, unknown>,
): Promise<unknown> {
// Check if tool is allowed before calling
if (!isToolAllowed(toolName, config)) {
throw new Error(`Tool "${toolName}" is disabled by configuration`);
}
return callTool(client, toolName, args);
},
async getInstructions(): Promise<string | undefined> {
return client.getInstructions();
},
async close(): Promise<void> {
await close();
},
isDaemon: false,
};
}