@lushly-dev/afd-client 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +197 -34
  2. package/dist/backoff.d.ts +20 -0
  3. package/dist/backoff.d.ts.map +1 -0
  4. package/dist/backoff.js +42 -0
  5. package/dist/backoff.js.map +1 -0
  6. package/dist/client-errors.d.ts +39 -0
  7. package/dist/client-errors.d.ts.map +1 -0
  8. package/dist/client-errors.js +163 -0
  9. package/dist/client-errors.js.map +1 -0
  10. package/dist/client-events.d.ts +23 -0
  11. package/dist/client-events.d.ts.map +1 -0
  12. package/dist/client-events.js +47 -0
  13. package/dist/client-events.js.map +1 -0
  14. package/dist/client.d.ts +86 -30
  15. package/dist/client.d.ts.map +1 -1
  16. package/dist/client.js +359 -450
  17. package/dist/client.js.map +1 -1
  18. package/dist/direct-timeout.d.ts +22 -0
  19. package/dist/direct-timeout.d.ts.map +1 -0
  20. package/dist/direct-timeout.js +54 -0
  21. package/dist/direct-timeout.js.map +1 -0
  22. package/dist/direct-transport.d.ts +71 -0
  23. package/dist/direct-transport.d.ts.map +1 -0
  24. package/dist/direct-transport.js +203 -0
  25. package/dist/direct-transport.js.map +1 -0
  26. package/dist/direct-types.d.ts +106 -0
  27. package/dist/direct-types.d.ts.map +1 -0
  28. package/dist/direct-types.js +5 -0
  29. package/dist/direct-types.js.map +1 -0
  30. package/dist/direct-validation.d.ts +1 -1
  31. package/dist/direct-validation.d.ts.map +1 -1
  32. package/dist/direct-validation.js +4 -1
  33. package/dist/direct-validation.js.map +1 -1
  34. package/dist/direct.d.ts +62 -192
  35. package/dist/direct.d.ts.map +1 -1
  36. package/dist/direct.js +116 -450
  37. package/dist/direct.js.map +1 -1
  38. package/dist/handlers.d.ts.map +1 -1
  39. package/dist/handlers.js +24 -21
  40. package/dist/handlers.js.map +1 -1
  41. package/dist/handoff.d.ts +17 -4
  42. package/dist/handoff.d.ts.map +1 -1
  43. package/dist/handoff.js +110 -86
  44. package/dist/handoff.js.map +1 -1
  45. package/dist/index.d.ts +12 -7
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +10 -5
  48. package/dist/index.js.map +1 -1
  49. package/dist/mcp-session.d.ts +29 -0
  50. package/dist/mcp-session.d.ts.map +1 -0
  51. package/dist/mcp-session.js +67 -0
  52. package/dist/mcp-session.js.map +1 -0
  53. package/dist/mcp-stream.d.ts +56 -0
  54. package/dist/mcp-stream.d.ts.map +1 -0
  55. package/dist/mcp-stream.js +192 -0
  56. package/dist/mcp-stream.js.map +1 -0
  57. package/dist/result-parsing.d.ts +27 -0
  58. package/dist/result-parsing.d.ts.map +1 -0
  59. package/dist/result-parsing.js +107 -0
  60. package/dist/result-parsing.js.map +1 -0
  61. package/dist/sse-parser.d.ts +70 -0
  62. package/dist/sse-parser.d.ts.map +1 -0
  63. package/dist/sse-parser.js +159 -0
  64. package/dist/sse-parser.js.map +1 -0
  65. package/dist/transport.d.ts +46 -6
  66. package/dist/transport.d.ts.map +1 -1
  67. package/dist/transport.js +181 -40
  68. package/dist/transport.js.map +1 -1
  69. package/dist/types.d.ts +40 -10
  70. package/dist/types.d.ts.map +1 -1
  71. package/dist/unknown-tool.d.ts +28 -8
  72. package/dist/unknown-tool.d.ts.map +1 -1
  73. package/dist/unknown-tool.js +51 -52
  74. package/dist/unknown-tool.js.map +1 -1
  75. package/package.json +7 -7
package/dist/client.js CHANGED
@@ -1,10 +1,35 @@
1
+ // afd-override: max-lines=950 — MCP client lifecycle and public request APIs; parsing and transport helpers are separate modules
1
2
  /**
2
3
  * @fileoverview MCP Client implementation
3
4
  */
4
- import { createMcpRequest, failure, isCompleteChunk, isDataChunk, isErrorChunk, isProgressChunk, success, wrapError, } from '@lushly-dev/afd-core';
5
+ import { createMcpRequest, failure, isCompleteChunk, isDataChunk, isErrorChunk, isProgressChunk, success, } from '@lushly-dev/afd-core';
6
+ import { backoffDelay, CancellableDelay } from './backoff.js';
7
+ import { isOutcomeUnknown, JsonRpcResponseError, NotConnectedError, RequestTimeoutError, toCommandError, } from './client-errors.js';
8
+ import { McpClientEventEmitter } from './client-events.js';
9
+ import { DirectTransport } from './direct-transport.js';
10
+ import { deriveStreamUrl, streamDirect, streamErrorChunk, streamOverHttp, } from './mcp-stream.js';
11
+ import { createBatchFailure, createPipelineFailure, createUnknownOutcomeBatch, createUnknownOutcomePipeline, getTextContent, isBatchResult, isCommandResult, isPipelineResult, outcomeUnknownError, parseTextContent, } from './result-parsing.js';
12
+ import { DEFAULT_MAX_SSE_EVENT_SIZE } from './sse-parser.js';
5
13
  import { createTransport } from './transport.js';
14
+ const SUPPORTED_TRANSPORTS = new Set([
15
+ 'sse',
16
+ 'http',
17
+ 'direct',
18
+ ]);
19
+ /** Node timers fire immediately for delays above 2^31 - 1 ms. */
20
+ const MAX_TIMER_MS = 2_147_483_647;
6
21
  /**
7
- * MCP Client for connecting to MCP servers.
22
+ * Extra time `batch()` and `pipe()` wait beyond the server-side deadline in their options, so
23
+ * the server's own timeout result can arrive before the client gives up.
24
+ */
25
+ export const SERVER_DEADLINE_MARGIN_MS = 5000;
26
+ /**
27
+ * MCP Client for AFD servers (`createMcpServer()` from `@lushly-dev/afd-server`) and in-process
28
+ * registries.
29
+ *
30
+ * It speaks the AFD server's HTTP transport (`/sse` + `POST /message`, `POST /stream/<command>`).
31
+ * It does not implement the MCP Streamable HTTP transport or read the legacy SSE `endpoint`
32
+ * event, so it cannot talk to servers built on the official MCP SDK.
8
33
  *
9
34
  * @example
10
35
  * ```typescript
@@ -16,13 +41,14 @@ import { createTransport } from './transport.js';
16
41
  * const tools = await client.listTools();
17
42
  *
18
43
  * // Call a tool
19
- * const result = await client.call('document.create', { title: 'Test' });
44
+ * const result = await client.call('document-create', { title: 'Test' });
20
45
  *
21
46
  * await client.disconnect();
22
47
  * ```
23
48
  */
24
- export class McpClient {
49
+ export class McpClient extends McpClientEventEmitter {
25
50
  config;
51
+ registry;
26
52
  transport = null;
27
53
  state = 'disconnected';
28
54
  serverInfo = null;
@@ -31,31 +57,40 @@ export class McpClient {
31
57
  connectedAt = null;
32
58
  reconnectAttempts = 0;
33
59
  pendingRequests = new Map();
34
- eventHandlers = {
35
- stateChange: [],
36
- connected: [],
37
- disconnected: [],
38
- reconnecting: [],
39
- error: [],
40
- message: [],
41
- toolsChanged: [],
42
- };
60
+ activeStreams = new Set();
61
+ intentionalDisconnect = false;
62
+ connectionGeneration = 0;
63
+ connectionController = null;
64
+ reconnectWait = new CancellableDelay();
65
+ reconnectPromise = null;
66
+ reconnectGeneration = null;
43
67
  constructor(config) {
68
+ super();
69
+ const transport = config.transport ?? 'sse';
70
+ if (!SUPPORTED_TRANSPORTS.has(transport)) {
71
+ throw new Error(`Unsupported transport '${transport}'. McpClient supports 'sse', 'http' and 'direct' (with a registry).`);
72
+ }
73
+ if (transport === 'direct' && !config.registry) {
74
+ throw new Error("transport: 'direct' requires a registry: pass { transport: 'direct', registry: createDirectRegistry(commands) } (from @lushly-dev/afd-server), or use createDirectClient(registry).");
75
+ }
44
76
  // Resolve url from url or endpoint
45
- const resolvedUrl = config.url ?? config.endpoint;
77
+ const resolvedUrl = config.url ?? config.endpoint ?? (transport === 'direct' ? 'direct://in-process' : undefined);
46
78
  if (!resolvedUrl) {
47
79
  throw new Error('Either url or endpoint must be provided');
48
80
  }
81
+ this.registry = transport === 'direct' ? config.registry : undefined;
49
82
  this.config = {
50
83
  url: resolvedUrl,
51
84
  endpoint: config.endpoint,
52
- transport: config.transport ?? 'sse',
85
+ transport: transport,
53
86
  clientName: config.clientName ?? '@lushly-dev/afd-client',
54
87
  clientVersion: config.clientVersion ?? '0.1.0',
55
88
  timeout: config.timeout ?? 30000,
56
89
  autoReconnect: config.autoReconnect ?? true,
57
90
  maxReconnectAttempts: config.maxReconnectAttempts ?? 5,
58
91
  reconnectDelay: config.reconnectDelay ?? 1000,
92
+ maxReconnectDelay: config.maxReconnectDelay ?? 30000,
93
+ maxStreamEventSize: config.maxStreamEventSize ?? DEFAULT_MAX_SSE_EVENT_SIZE,
59
94
  headers: config.headers ?? {},
60
95
  debug: config.debug ?? false,
61
96
  };
@@ -64,61 +99,43 @@ export class McpClient {
64
99
  // CONNECTION MANAGEMENT
65
100
  // ═══════════════════════════════════════════════════════════════════════════
66
101
  /**
67
- * Connect to the MCP server.
102
+ * Connect to the MCP server. Resolves, and `connected` is emitted, once the server is
103
+ * initialized and the tools list has been fetched (a failed tools refresh leaves the list
104
+ * empty but does not fail the connection).
68
105
  */
69
106
  async connect() {
70
107
  if (this.state === 'connected') {
71
108
  throw new Error('Already connected');
72
109
  }
73
- this.setState('connecting');
74
- try {
75
- // Create transport
76
- if (this.config.transport === 'stdio') {
77
- throw new Error('stdio transport not yet implemented');
78
- }
79
- if (this.config.transport === 'direct') {
80
- throw new Error('Direct transport requires a registry. Use DirectClient or DirectTransport instead.');
81
- }
82
- this.transport = createTransport(this.config.transport, this.config.url, this.config.headers);
83
- // Set up transport handlers
84
- this.transport.onMessage((response) => this.handleMessage(response));
85
- this.transport.onError((error) => this.handleError(error));
86
- this.transport.onClose(() => this.handleClose());
87
- // Connect transport
88
- await this.transport.connect();
89
- // Initialize MCP session
90
- const initResult = await this.initialize();
91
- this.serverInfo = initResult.serverInfo;
92
- this.capabilities = initResult.capabilities;
93
- this.connectedAt = new Date();
94
- this.reconnectAttempts = 0;
95
- this.setState('connected');
96
- this.emit('connected', initResult);
97
- // Fetch initial tools list
98
- await this.refreshTools();
99
- return initResult;
100
- }
101
- catch (error) {
102
- this.setState('error');
103
- const err = error instanceof Error ? error : new Error(String(error));
104
- this.emit('error', err);
105
- throw err;
106
- }
110
+ this.intentionalDisconnect = false;
111
+ this.reconnectWait.cancel();
112
+ this.reconnectAttempts = 0;
113
+ const generation = ++this.connectionGeneration;
114
+ return this.establishConnection(generation, false);
107
115
  }
108
116
  /**
109
- * Disconnect from the MCP server.
117
+ * Disconnect from the MCP server. Pending requests reject and active streams end with a
118
+ * `STREAM_CANCELLED` error chunk.
110
119
  */
111
120
  async disconnect() {
112
- if (this.transport) {
113
- this.transport.disconnect();
114
- this.transport = null;
115
- }
116
- // Reject all pending requests
117
- for (const [_id, pending] of this.pendingRequests) {
121
+ this.intentionalDisconnect = true;
122
+ this.connectionGeneration++;
123
+ this.reconnectWait.cancel();
124
+ this.connectionController?.abort(new Error('Client disconnected'));
125
+ this.connectionController = null;
126
+ const transport = this.transport;
127
+ this.transport = null;
128
+ transport?.disconnect();
129
+ // Reject all pending requests and abort all streams
130
+ for (const pending of this.pendingRequests.values()) {
118
131
  clearTimeout(pending.timeout);
119
- pending.reject(new Error('Client disconnected'));
132
+ pending.controller.abort(new Error('Client disconnected'));
120
133
  }
121
134
  this.pendingRequests.clear();
135
+ for (const controller of this.activeStreams) {
136
+ controller.abort(new Error('Client disconnected'));
137
+ }
138
+ this.activeStreams.clear();
122
139
  this.setState('disconnected');
123
140
  this.emit('disconnected', 'Manual disconnect');
124
141
  this.serverInfo = null;
@@ -176,19 +193,22 @@ export class McpClient {
176
193
  *
177
194
  * @param name - Tool name
178
195
  * @param args - Tool arguments
196
+ * @param options - Request options such as `timeout`
179
197
  */
180
- async callTool(name, args) {
198
+ async callTool(name, args, options) {
181
199
  const params = {
182
200
  name,
183
201
  arguments: args,
184
202
  };
185
- return this.request('tools/call', params);
203
+ return this.request('tools/call', params, options);
186
204
  }
187
205
  /**
188
206
  * Call a command and return a CommandResult.
189
207
  *
190
208
  * This is the preferred method for AFD - it wraps the MCP response
191
- * in a standardized CommandResult.
209
+ * in a standardized CommandResult. It never rejects: a JSON-RPC error becomes a failure with
210
+ * a matching AFD code (`INVALID_INPUT` for -32602, `SESSION_NOT_FOUND` for -32001, ...), a
211
+ * timeout becomes `TIMEOUT`, and a connection problem `CONNECTION_ERROR` or `NOT_CONNECTED`.
192
212
  *
193
213
  * @param name - Command/tool name
194
214
  * @param args - Command arguments
@@ -196,12 +216,12 @@ export class McpClient {
196
216
  async call(name, args) {
197
217
  try {
198
218
  const result = await this.callTool(name, args);
219
+ const parsed = parseTextContent(result);
220
+ if (isCommandResult(parsed)) {
221
+ return parsed;
222
+ }
199
223
  if (result.isError) {
200
- // Extract error from content
201
- const errorText = result.content
202
- .filter((c) => c.type === 'text')
203
- .map((c) => c.text)
204
- .join('\n');
224
+ const errorText = getTextContent(result);
205
225
  return failure({
206
226
  code: 'TOOL_ERROR',
207
227
  message: errorText || 'Tool execution failed',
@@ -209,27 +229,13 @@ export class McpClient {
209
229
  });
210
230
  }
211
231
  // Try to parse JSON from text content
212
- const textContent = result.content
213
- .filter((c) => c.type === 'text')
214
- .map((c) => c.text)
215
- .join('');
216
- try {
217
- const data = JSON.parse(textContent);
218
- // If the data is already a CommandResult, return it directly
219
- if (typeof data === 'object' && data !== null && 'success' in data) {
220
- return data;
221
- }
222
- // Wrap raw data in a success result
223
- return success(data);
224
- }
225
- catch {
226
- // SAFETY: JSON parsing failed, so we return the raw text. The caller expects T but
227
- // will receive a string — acceptable as a best-effort fallback for non-JSON responses.
228
- return success(textContent);
229
- }
232
+ if (parsed !== undefined)
233
+ return success(parsed);
234
+ // SAFETY: Non-AFD tools may return plain text. Preserve that established fallback.
235
+ return success(getTextContent(result));
230
236
  }
231
237
  catch (error) {
232
- return failure(wrapError(error));
238
+ return failure(toCommandError(error));
233
239
  }
234
240
  }
235
241
  /**
@@ -239,6 +245,12 @@ export class McpClient {
239
245
  * succeeds if at least one command succeeds, with aggregated
240
246
  * confidence scores and detailed timing information.
241
247
  *
248
+ * The request waits for `options.timeout` (the server-side batch deadline) plus
249
+ * {@link SERVER_DEADLINE_MARGIN_MS}, and never less than the client's `timeout`. If no result
250
+ * arrives (timeout or connection failure), the server may already have run some commands, so
251
+ * the result is an `OUTCOME_UNKNOWN` failure with `retryable: false`, no per-command results
252
+ * and zero success and failure counts.
253
+ *
242
254
  * @param commands - Array of commands to execute
243
255
  * @param options - Batch execution options
244
256
  * @returns BatchResult with individual command results
@@ -246,9 +258,9 @@ export class McpClient {
246
258
  * @example
247
259
  * ```typescript
248
260
  * const result = await client.batch([
249
- * { name: 'todo-create', input: { title: 'First' } },
250
- * { name: 'todo-create', input: { title: 'Second' } },
251
- * { name: 'todo-list', input: {} }
261
+ * { command: 'todo-create', input: { title: 'First' } },
262
+ * { command: 'todo-create', input: { title: 'Second' } },
263
+ * { command: 'todo-list', input: {} }
252
264
  * ], { stopOnError: false });
253
265
  *
254
266
  * console.log(`${result.summary.successCount}/${result.summary.total} succeeded`);
@@ -258,99 +270,31 @@ export class McpClient {
258
270
  async batch(commands, options) {
259
271
  const startedAt = new Date().toISOString();
260
272
  try {
261
- const result = await this.callTool('afd.batch', {
262
- commands,
263
- options,
264
- });
265
- if (result.isError) {
266
- const errorText = result.content
267
- .filter((c) => c.type === 'text')
268
- .map((c) => c.text)
269
- .join('\n');
270
- // Return failed batch result
271
- return {
272
- success: false,
273
- results: [],
274
- summary: {
275
- total: commands.length,
276
- successCount: 0,
277
- failureCount: commands.length,
278
- skippedCount: 0,
279
- },
280
- timing: {
281
- startedAt,
282
- completedAt: new Date().toISOString(),
283
- totalMs: 0,
284
- averageMs: 0,
285
- },
286
- confidence: 0,
287
- reasoning: `Batch execution failed: ${errorText || 'Unknown error'}`,
288
- error: {
289
- code: 'BATCH_ERROR',
290
- message: errorText || 'Batch execution failed',
291
- suggestion: 'Check the batch commands and try again',
292
- },
293
- };
294
- }
295
- // Parse batch result from response
296
- const textContent = result.content
297
- .filter((c) => c.type === 'text')
298
- .map((c) => c.text)
299
- .join('');
300
- try {
301
- return JSON.parse(textContent);
273
+ const result = await this.callTool('afd-batch', { commands, options }, { timeout: this.timeoutWithMargin(options?.timeout) });
274
+ const parsed = parseTextContent(result);
275
+ if (isBatchResult(parsed)) {
276
+ return parsed;
302
277
  }
303
- catch {
304
- return {
305
- success: false,
306
- results: [],
307
- summary: {
308
- total: commands.length,
309
- successCount: 0,
310
- failureCount: commands.length,
311
- skippedCount: 0,
312
- },
313
- timing: {
314
- startedAt,
315
- completedAt: new Date().toISOString(),
316
- totalMs: 0,
317
- averageMs: 0,
318
- },
319
- confidence: 0,
320
- reasoning: 'Failed to parse batch result',
321
- error: {
322
- code: 'PARSE_ERROR',
323
- message: 'Failed to parse batch result',
324
- suggestion: 'The server returned an invalid response',
325
- },
326
- };
278
+ if (result.isError) {
279
+ const errorText = getTextContent(result);
280
+ return createBatchFailure(commands, startedAt, {
281
+ code: 'BATCH_ERROR',
282
+ message: errorText || 'Batch execution failed',
283
+ suggestion: 'Check the batch commands and try again',
284
+ }, `Batch execution failed: ${errorText || 'Unknown error'}`);
327
285
  }
286
+ return createBatchFailure(commands, startedAt, {
287
+ code: 'PARSE_ERROR',
288
+ message: 'Failed to parse batch result',
289
+ suggestion: 'The server returned an invalid response',
290
+ }, 'Failed to parse batch result');
328
291
  }
329
292
  catch (error) {
330
- const err = error instanceof Error ? error.message : String(error);
331
- return {
332
- success: false,
333
- results: [],
334
- summary: {
335
- total: commands.length,
336
- successCount: 0,
337
- failureCount: commands.length,
338
- skippedCount: 0,
339
- },
340
- timing: {
341
- startedAt,
342
- completedAt: new Date().toISOString(),
343
- totalMs: 0,
344
- averageMs: 0,
345
- },
346
- confidence: 0,
347
- reasoning: `Batch execution failed: ${err}`,
348
- error: {
349
- code: 'BATCH_ERROR',
350
- message: err,
351
- suggestion: 'Check the connection and try again',
352
- },
353
- };
293
+ const cause = toCommandError(error);
294
+ if (isOutcomeUnknown(error)) {
295
+ return createUnknownOutcomeBatch(commands, startedAt, outcomeUnknownError(cause, 'batch'));
296
+ }
297
+ return createBatchFailure(commands, startedAt, cause, `Batch was not executed: ${cause.message}`);
354
298
  }
355
299
  }
356
300
  /**
@@ -359,8 +303,14 @@ export class McpClient {
359
303
  * Pipelines enable declarative composition of commands where the output
360
304
  * of one becomes the input of the next via variable resolution.
361
305
  *
306
+ * The request waits for `timeoutMs` (the server-side pipeline deadline) plus
307
+ * {@link SERVER_DEADLINE_MARGIN_MS}, and never less than the client's `timeout`. If no result
308
+ * arrives (timeout or connection failure), earlier steps may already have run, so the result
309
+ * carries an `OUTCOME_UNKNOWN` error (`retryable: false`) on a single pipeline-level entry
310
+ * (`index: -1`) instead of a status for each step.
311
+ *
362
312
  * @param stepsOrRequest - Array of pipeline steps or full PipelineRequest
363
- * @param options - Optional pipeline options
313
+ * @param options - Optional pipeline options (used with an array of steps)
364
314
  * @returns Pipeline result with aggregated metadata
365
315
  *
366
316
  * @example
@@ -385,94 +335,27 @@ export class McpClient {
385
335
  try {
386
336
  // SAFETY: PipelineRequest is a plain object that serializes correctly as Record<string, unknown>
387
337
  // for the MCP tool call wire format.
388
- const result = await this.callTool('afd-pipe', request);
389
- if (result.isError) {
390
- const errorText = result.content
391
- .filter((c) => c.type === 'text')
392
- .map((c) => c.text)
393
- .join('\n');
394
- // Return failed pipeline result
395
- return {
396
- data: undefined,
397
- metadata: {
398
- confidence: 0,
399
- confidenceBreakdown: [],
400
- reasoning: [],
401
- warnings: [],
402
- sources: [],
403
- alternatives: [],
404
- executionTimeMs: 0,
405
- completedSteps: 0,
406
- totalSteps: request.steps.length,
407
- },
408
- steps: request.steps.map((step, i) => ({
409
- index: i,
410
- alias: step.as,
411
- command: step.command,
412
- status: 'failure',
413
- error: {
414
- code: 'PIPELINE_ERROR',
415
- message: errorText || 'Pipeline execution failed',
416
- suggestion: 'Check the pipeline steps and try again',
417
- },
418
- executionTimeMs: 0,
419
- })),
420
- };
338
+ const result = await this.callTool('afd-pipe', request, { timeout: this.timeoutWithMargin(request.options?.timeoutMs) });
339
+ const parsed = parseTextContent(result);
340
+ if (isPipelineResult(parsed)) {
341
+ return parsed;
421
342
  }
422
- // Parse pipeline result from response
423
- const textContent = result.content
424
- .filter((c) => c.type === 'text')
425
- .map((c) => c.text)
426
- .join('');
427
- try {
428
- return JSON.parse(textContent);
429
- }
430
- catch {
431
- return {
432
- data: undefined,
433
- metadata: {
434
- confidence: 0,
435
- confidenceBreakdown: [],
436
- reasoning: [],
437
- warnings: [],
438
- sources: [],
439
- alternatives: [],
440
- executionTimeMs: 0,
441
- completedSteps: 0,
442
- totalSteps: request.steps.length,
443
- },
444
- steps: [],
445
- };
343
+ if (result.isError) {
344
+ const errorText = getTextContent(result);
345
+ return createPipelineFailure(request, {
346
+ code: 'PIPELINE_ERROR',
347
+ message: errorText || 'Pipeline execution failed',
348
+ suggestion: 'Check the pipeline steps and try again',
349
+ });
446
350
  }
351
+ return createPipelineFailure(request);
447
352
  }
448
353
  catch (error) {
449
- const err = error instanceof Error ? error.message : String(error);
450
- return {
451
- data: undefined,
452
- metadata: {
453
- confidence: 0,
454
- confidenceBreakdown: [],
455
- reasoning: [],
456
- warnings: [],
457
- sources: [],
458
- alternatives: [],
459
- executionTimeMs: 0,
460
- completedSteps: 0,
461
- totalSteps: request.steps.length,
462
- },
463
- steps: request.steps.map((step, i) => ({
464
- index: i,
465
- alias: step.as,
466
- command: step.command,
467
- status: 'failure',
468
- error: {
469
- code: 'PIPELINE_ERROR',
470
- message: err,
471
- suggestion: 'Check the connection and try again',
472
- },
473
- executionTimeMs: 0,
474
- })),
475
- };
354
+ const cause = toCommandError(error);
355
+ if (isOutcomeUnknown(error)) {
356
+ return createUnknownOutcomePipeline(request, outcomeUnknownError(cause, 'pipeline'));
357
+ }
358
+ return createPipelineFailure(request, cause);
476
359
  }
477
360
  }
478
361
  /**
@@ -482,6 +365,19 @@ export class McpClient {
482
365
  * containing progress updates, incremental data, completion,
483
366
  * or error information.
484
367
  *
368
+ * The last chunk is always a `complete` or `error` chunk. The client makes the error chunk
369
+ * itself when the stream ends early (`STREAM_TRUNCATED`), `options.timeout` passes
370
+ * (`STREAM_TIMEOUT`), the caller's signal or `disconnect()` stops it (`STREAM_CANCELLED`),
371
+ * one event exceeds `maxStreamEventSize` (`STREAM_EVENT_TOO_LARGE`), or the client is not
372
+ * connected (`NOT_CONNECTED`).
373
+ *
374
+ * Over HTTP it posts to `<base>/stream/<command>`, where `<base>` is the client URL without
375
+ * a trailing `/sse`, `/message` or `/messages`, in the client's MCP session: the request
376
+ * carries the `Mcp-Session-Id` from `initialize`, so the stream sees the session's active
377
+ * context (`afd-context-enter`). If the server has expired that session (404), the client
378
+ * starts a new one and retries once, as it does for other requests. With
379
+ * `transport: 'direct'` it runs the command in process through core's `executeStream()`.
380
+ *
485
381
  * @param name - Command name to execute
486
382
  * @param args - Command arguments
487
383
  * @param options - Stream options (abort signal, timeout)
@@ -489,7 +385,7 @@ export class McpClient {
489
385
  *
490
386
  * @example
491
387
  * ```typescript
492
- * for await (const chunk of client.stream('llm.generate', { prompt: 'Hello' })) {
388
+ * for await (const chunk of client.stream('llm-generate', { prompt: 'Hello' })) {
493
389
  * if (chunk.type === 'progress') {
494
390
  * console.log(`Progress: ${(chunk.progress * 100).toFixed(0)}%`);
495
391
  * } else if (chunk.type === 'data') {
@@ -503,116 +399,49 @@ export class McpClient {
503
399
  * ```
504
400
  */
505
401
  async *stream(name, args, options) {
506
- const url = new URL(this.config.url);
507
- // Use the stream endpoint relative to base URL
508
- const streamUrl = `${url.protocol}//${url.host}/stream/${encodeURIComponent(name)}`;
402
+ if (!this.isConnected()) {
403
+ yield streamErrorChunk({
404
+ code: 'NOT_CONNECTED',
405
+ message: 'The client is not connected',
406
+ suggestion: 'Call connect() before stream()',
407
+ retryable: false,
408
+ }, 0);
409
+ return;
410
+ }
509
411
  const controller = new AbortController();
412
+ const abort = { timedOut: false, callerSignal: options?.signal, controller };
510
413
  const signal = options?.signal
511
- ? this.combineSignals(options.signal, controller.signal)
414
+ ? AbortSignal.any([options.signal, controller.signal])
512
415
  : controller.signal;
513
- // Setup timeout if specified
514
- let timeoutId;
515
- if (options?.timeout) {
516
- timeoutId = setTimeout(() => controller.abort(), options.timeout);
517
- }
416
+ const timeoutMs = typeof options?.timeout === 'number' && options.timeout > 0 ? options.timeout : undefined;
417
+ const timeoutId = timeoutMs === undefined
418
+ ? undefined
419
+ : setTimeout(() => {
420
+ abort.timedOut = true;
421
+ controller.abort(new Error(`Stream timed out after ${timeoutMs}ms`));
422
+ }, Math.min(timeoutMs, MAX_TIMER_MS));
423
+ this.activeStreams.add(controller);
518
424
  try {
519
- const response = await fetch(streamUrl, {
520
- method: 'POST',
521
- headers: {
522
- 'Content-Type': 'application/json',
523
- Accept: 'text/event-stream',
524
- ...this.config.headers,
525
- },
526
- body: JSON.stringify(args ?? {}),
527
- signal,
528
- });
529
- if (!response.ok) {
530
- yield {
531
- type: 'error',
532
- error: {
533
- code: 'STREAM_ERROR',
534
- message: `HTTP ${response.status}: ${response.statusText}`,
535
- suggestion: 'Check the command name and arguments',
536
- },
537
- chunksBeforeError: 0,
538
- recoverable: false,
539
- };
540
- return;
541
- }
542
- const reader = response.body?.getReader();
543
- if (!reader) {
544
- yield {
545
- type: 'error',
546
- error: {
547
- code: 'STREAM_ERROR',
548
- message: 'Response body is not readable',
549
- suggestion: 'The server does not support streaming',
550
- },
551
- chunksBeforeError: 0,
552
- recoverable: false,
553
- };
425
+ if (this.registry) {
426
+ yield* streamDirect(this.registry, name, args, signal, abort, timeoutMs);
554
427
  return;
555
428
  }
556
- const decoder = new TextDecoder();
557
- let buffer = '';
558
- let _chunksReceived = 0;
559
- while (true) {
560
- const { done, value } = await reader.read();
561
- if (done)
562
- break;
563
- buffer += decoder.decode(value, { stream: true });
564
- // Process SSE events
565
- const lines = buffer.split('\n');
566
- buffer = lines.pop() ?? ''; // Keep incomplete line in buffer
567
- for (const line of lines) {
568
- if (line.startsWith('data: ')) {
569
- const data = line.slice(6).trim();
570
- if (data === '[DONE]') {
571
- return;
572
- }
573
- try {
574
- const chunk = JSON.parse(data);
575
- _chunksReceived++;
576
- yield chunk;
577
- // Stop on complete or error
578
- if (isCompleteChunk(chunk) || isErrorChunk(chunk)) {
579
- return;
580
- }
581
- }
582
- catch {
583
- // Ignore malformed JSON
584
- this.debug('Malformed stream chunk:', data);
585
- }
586
- }
587
- }
588
- }
589
- }
590
- catch (error) {
591
- if (signal.aborted) {
592
- yield {
593
- type: 'error',
594
- error: {
595
- code: 'STREAM_CANCELLED',
596
- message: 'Stream was cancelled',
597
- suggestion: 'The request was aborted by the client',
598
- },
599
- chunksBeforeError: 0,
600
- recoverable: false,
601
- };
602
- }
603
- else {
604
- yield {
605
- type: 'error',
606
- error: wrapError(error),
607
- chunksBeforeError: 0,
608
- recoverable: true,
609
- };
610
- }
429
+ yield* streamOverHttp({
430
+ url: deriveStreamUrl(this.config.url, name),
431
+ args,
432
+ headers: this.config.headers,
433
+ session: this.transport ?? undefined,
434
+ signal,
435
+ abort,
436
+ timeoutMs,
437
+ maxEventSize: this.config.maxStreamEventSize,
438
+ debug: (message, data) => this.debug(message, data),
439
+ });
611
440
  }
612
441
  finally {
613
- if (timeoutId) {
614
- clearTimeout(timeoutId);
615
- }
442
+ clearTimeout(timeoutId);
443
+ controller.abort();
444
+ this.activeStreams.delete(controller);
616
445
  }
617
446
  }
618
447
  /**
@@ -629,7 +458,7 @@ export class McpClient {
629
458
  *
630
459
  * @example
631
460
  * ```typescript
632
- * await client.streamWithCallbacks('llm.generate', { prompt: 'Hello' }, {
461
+ * await client.streamWithCallbacks('llm-generate', { prompt: 'Hello' }, {
633
462
  * onProgress: (chunk) => console.log(`${(chunk.progress * 100).toFixed(0)}% - ${chunk.message}`),
634
463
  * onData: (chunk) => process.stdout.write(String(chunk.data)),
635
464
  * onComplete: (chunk) => console.log('Done!', chunk.data),
@@ -653,76 +482,65 @@ export class McpClient {
653
482
  }
654
483
  }
655
484
  }
656
- /**
657
- * Combine two AbortSignals into one.
658
- */
659
- combineSignals(signal1, signal2) {
660
- const controller = new AbortController();
661
- const abort = () => controller.abort();
662
- signal1.addEventListener('abort', abort);
663
- signal2.addEventListener('abort', abort);
664
- // Abort if either is already aborted
665
- if (signal1.aborted || signal2.aborted) {
666
- controller.abort();
667
- }
668
- return controller.signal;
669
- }
670
485
  // ═══════════════════════════════════════════════════════════════════════════
671
486
  // LOW-LEVEL REQUEST/RESPONSE
672
487
  // ═══════════════════════════════════════════════════════════════════════════
673
488
  /**
674
489
  * Send a raw MCP request and wait for response.
490
+ *
491
+ * @throws NotConnectedError when not connected; RequestTimeoutError when no response arrives
492
+ * in time; JsonRpcResponseError when the server answers with a JSON-RPC error;
493
+ * HttpStatusError for another non-2xx HTTP status
675
494
  */
676
- async request(method, params) {
677
- // Allow requests during 'connecting' (for initialize) and 'connected' states
495
+ async request(method, params, options) {
496
+ // Initialization requests must work during both initial connection and reconnection.
678
497
  const canRequest = this.transport &&
679
- (this.state === 'connected' || this.state === 'connecting') &&
498
+ (this.state === 'connected' ||
499
+ this.state === 'connecting' ||
500
+ this.state === 'reconnecting') &&
680
501
  this.transport.isConnected();
681
502
  if (!canRequest || !this.transport) {
682
- throw new Error('Not connected');
503
+ throw new NotConnectedError();
683
504
  }
684
505
  const request = createMcpRequest(method, params);
685
506
  this.debug(`Request [${request.id}]: ${method}`, params);
686
- // For transports that return response directly
687
- const response = await this.transport.send(request);
688
- this.debug(`Response [${request.id}]:`, response);
689
- if (response.error) {
690
- throw new Error(response.error.message);
507
+ const transport = this.transport;
508
+ const controller = new AbortController();
509
+ const timeoutMs = options?.timeout ?? this.config.timeout;
510
+ const timeout = setTimeout(() => {
511
+ controller.abort(new RequestTimeoutError(method, timeoutMs));
512
+ }, Math.min(timeoutMs, MAX_TIMER_MS));
513
+ this.pendingRequests.set(request.id, { controller, timeout, method });
514
+ try {
515
+ const response = await transport.send(request, controller.signal);
516
+ this.debug(`Response [${request.id}]:`, response);
517
+ if (response.error)
518
+ throw new JsonRpcResponseError(response.error);
519
+ return response.result;
691
520
  }
692
- return response.result;
693
- }
694
- // ═══════════════════════════════════════════════════════════════════════════
695
- // EVENT HANDLING
696
- // ═══════════════════════════════════════════════════════════════════════════
697
- /**
698
- * Subscribe to an event.
699
- */
700
- on(event, handler) {
701
- this.eventHandlers[event].push(handler);
702
- // Return unsubscribe function
703
- return () => {
704
- const index = this.eventHandlers[event].indexOf(handler);
705
- if (index > -1) {
706
- this.eventHandlers[event].splice(index, 1);
707
- }
708
- };
709
- }
710
- /**
711
- * Emit an event.
712
- */
713
- emit(event, ...args) {
714
- for (const handler of this.eventHandlers[event]) {
715
- try {
716
- handler(...args);
717
- }
718
- catch (error) {
719
- console.error(`Error in event handler for '${event}':`, error);
521
+ catch (error) {
522
+ if (controller.signal.aborted && controller.signal.reason instanceof Error) {
523
+ throw controller.signal.reason;
720
524
  }
525
+ throw error;
526
+ }
527
+ finally {
528
+ clearTimeout(timeout);
529
+ this.pendingRequests.delete(request.id);
721
530
  }
722
531
  }
723
532
  // ═══════════════════════════════════════════════════════════════════════════
724
533
  // INTERNAL
725
534
  // ═══════════════════════════════════════════════════════════════════════════
535
+ /** A request timeout that outlasts a server-side deadline by the margin. */
536
+ timeoutWithMargin(serverDeadlineMs) {
537
+ if (typeof serverDeadlineMs !== 'number' ||
538
+ !Number.isFinite(serverDeadlineMs) ||
539
+ serverDeadlineMs < 0) {
540
+ return this.config.timeout;
541
+ }
542
+ return Math.max(this.config.timeout, serverDeadlineMs + SERVER_DEADLINE_MARGIN_MS);
543
+ }
726
544
  async initialize() {
727
545
  const params = {
728
546
  protocolVersion: '2024-11-05',
@@ -736,6 +554,104 @@ export class McpClient {
736
554
  };
737
555
  return this.request('initialize', params);
738
556
  }
557
+ createConnectionTransport() {
558
+ if (this.registry)
559
+ return new DirectTransport(this.registry);
560
+ // SAFETY: the constructor only admits 'sse', 'http' and 'direct', and 'direct' has a registry.
561
+ const type = this.config.transport;
562
+ return createTransport(type, this.config.url, this.config.headers);
563
+ }
564
+ assertCurrent(generation) {
565
+ if (generation !== this.connectionGeneration || this.intentionalDisconnect) {
566
+ throw new Error('Connection attempt is no longer current');
567
+ }
568
+ }
569
+ /**
570
+ * Connect, initialize and refresh tools. An initial connection reports its failure through
571
+ * the `error` event and the rejection; reconnection attempts report nothing themselves, and
572
+ * the reconnect loop emits one `error` when it gives up.
573
+ */
574
+ async establishConnection(generation, reconnecting) {
575
+ this.setState(reconnecting ? 'reconnecting' : 'connecting');
576
+ const transport = this.createConnectionTransport();
577
+ this.transport = transport;
578
+ transport.onMessage((response) => this.handleMessage(response));
579
+ transport.onError((error) => this.handleError(transport, error));
580
+ transport.onClose(() => this.handleClose(generation, transport));
581
+ const controller = new AbortController();
582
+ this.connectionController = controller;
583
+ const timeout = setTimeout(() => {
584
+ controller.abort(new Error(`Connection timed out after ${this.config.timeout}ms`));
585
+ }, this.config.timeout);
586
+ try {
587
+ await transport.connect(controller.signal);
588
+ clearTimeout(timeout);
589
+ this.assertCurrent(generation);
590
+ const initResult = await this.initialize();
591
+ this.assertCurrent(generation);
592
+ this.serverInfo = initResult.serverInfo;
593
+ this.capabilities = initResult.capabilities;
594
+ this.connectedAt = new Date();
595
+ try {
596
+ await this.refreshTools();
597
+ }
598
+ catch (error) {
599
+ this.debug('Tools refresh after connect failed; the tools list stays empty', error);
600
+ }
601
+ this.assertCurrent(generation);
602
+ this.setState('connected');
603
+ this.emit('connected', initResult);
604
+ return initResult;
605
+ }
606
+ catch (error) {
607
+ const err = controller.signal.aborted && controller.signal.reason instanceof Error
608
+ ? controller.signal.reason
609
+ : error instanceof Error
610
+ ? error
611
+ : new Error(String(error));
612
+ if (this.transport === transport)
613
+ this.transport = null;
614
+ transport.disconnect();
615
+ if (!reconnecting &&
616
+ generation === this.connectionGeneration &&
617
+ !this.intentionalDisconnect) {
618
+ this.setState('error');
619
+ this.emit('error', err);
620
+ }
621
+ throw err;
622
+ }
623
+ finally {
624
+ clearTimeout(timeout);
625
+ if (this.connectionController === controller)
626
+ this.connectionController = null;
627
+ }
628
+ }
629
+ async runReconnectLoop(generation) {
630
+ let lastError;
631
+ while (!this.intentionalDisconnect &&
632
+ generation === this.connectionGeneration &&
633
+ this.reconnectAttempts < this.config.maxReconnectAttempts) {
634
+ this.reconnectAttempts++;
635
+ this.setState('reconnecting');
636
+ this.emit('reconnecting', this.reconnectAttempts, this.config.maxReconnectAttempts);
637
+ await this.reconnectWait.wait(backoffDelay(this.reconnectAttempts, this.config.reconnectDelay, this.config.maxReconnectDelay));
638
+ if (this.intentionalDisconnect || generation !== this.connectionGeneration)
639
+ return;
640
+ try {
641
+ await this.establishConnection(generation, true);
642
+ this.reconnectAttempts = 0;
643
+ return;
644
+ }
645
+ catch (error) {
646
+ // Continue until the configured attempt bound is reached.
647
+ lastError = error;
648
+ }
649
+ }
650
+ if (!this.intentionalDisconnect && generation === this.connectionGeneration) {
651
+ this.setState('error');
652
+ this.emit('error', new Error('Max reconnection attempts reached', { cause: lastError }));
653
+ }
654
+ }
739
655
  setState(state) {
740
656
  if (this.state !== state) {
741
657
  this.state = state;
@@ -744,49 +660,42 @@ export class McpClient {
744
660
  }
745
661
  handleMessage(response) {
746
662
  this.emit('message', response);
747
- // Handle pending request if this is a response
748
- const pending = this.pendingRequests.get(response.id);
749
- if (pending) {
750
- clearTimeout(pending.timeout);
751
- this.pendingRequests.delete(response.id);
752
- if (response.error) {
753
- pending.reject(new Error(response.error.message));
754
- }
755
- else {
756
- pending.resolve(response.result);
757
- }
758
- }
759
663
  }
760
- handleError(error) {
664
+ /**
665
+ * Forward transport errors of the current, established connection. While connecting or
666
+ * reconnecting, failures are reported by `connect()` and the reconnect loop instead.
667
+ */
668
+ handleError(transport, error) {
669
+ if (transport !== this.transport)
670
+ return;
671
+ if (this.state === 'connecting' || this.state === 'reconnecting')
672
+ return;
761
673
  this.emit('error', error);
762
674
  }
763
- handleClose() {
764
- if (this.state === 'connected' && this.config.autoReconnect) {
765
- this.attemptReconnect();
675
+ handleClose(generation, transport) {
676
+ if (generation !== this.connectionGeneration || transport !== this.transport)
677
+ return;
678
+ if (!this.intentionalDisconnect && this.state === 'connected' && this.config.autoReconnect) {
679
+ void this.attemptReconnect(generation);
766
680
  }
767
681
  else {
768
682
  this.setState('disconnected');
769
683
  this.emit('disconnected', 'Connection closed');
770
684
  }
771
685
  }
772
- async attemptReconnect() {
773
- if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {
774
- this.setState('error');
775
- this.emit('error', new Error('Max reconnection attempts reached'));
776
- return;
777
- }
778
- this.reconnectAttempts++;
779
- this.setState('reconnecting');
780
- this.emit('reconnecting', this.reconnectAttempts, this.config.maxReconnectAttempts);
781
- // Exponential backoff
782
- const delay = this.config.reconnectDelay * 2 ** (this.reconnectAttempts - 1);
783
- await new Promise((resolve) => setTimeout(resolve, delay));
784
- try {
785
- await this.connect();
786
- }
787
- catch {
788
- // Will trigger another reconnect via handleClose
686
+ attemptReconnect(generation) {
687
+ if (this.reconnectPromise && this.reconnectGeneration === generation) {
688
+ return this.reconnectPromise;
789
689
  }
690
+ const reconnectPromise = this.runReconnectLoop(generation).finally(() => {
691
+ if (this.reconnectPromise === reconnectPromise) {
692
+ this.reconnectPromise = null;
693
+ this.reconnectGeneration = null;
694
+ }
695
+ });
696
+ this.reconnectPromise = reconnectPromise;
697
+ this.reconnectGeneration = generation;
698
+ return reconnectPromise;
790
699
  }
791
700
  debug(message, data) {
792
701
  if (this.config.debug) {