@lushly-dev/afd-client 1.0.0 → 2.1.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 (79) hide show
  1. package/README.md +217 -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 +89 -31
  15. package/dist/client.d.ts.map +1 -1
  16. package/dist/client.js +364 -452
  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 +72 -0
  23. package/dist/direct-transport.d.ts.map +1 -0
  24. package/dist/direct-transport.js +231 -0
  25. package/dist/direct-transport.js.map +1 -0
  26. package/dist/direct-types.d.ts +108 -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 +19 -6
  42. package/dist/handoff.d.ts.map +1 -1
  43. package/dist/handoff.js +112 -88
  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 +37 -0
  50. package/dist/mcp-session.d.ts.map +1 -0
  51. package/dist/mcp-session.js +159 -0
  52. package/dist/mcp-session.js.map +1 -0
  53. package/dist/mcp-stream.d.ts +59 -0
  54. package/dist/mcp-stream.d.ts.map +1 -0
  55. package/dist/mcp-stream.js +215 -0
  56. package/dist/mcp-stream.js.map +1 -0
  57. package/dist/request-abort.d.ts +3 -0
  58. package/dist/request-abort.d.ts.map +1 -0
  59. package/dist/request-abort.js +18 -0
  60. package/dist/request-abort.js.map +1 -0
  61. package/dist/result-parsing.d.ts +27 -0
  62. package/dist/result-parsing.d.ts.map +1 -0
  63. package/dist/result-parsing.js +107 -0
  64. package/dist/result-parsing.js.map +1 -0
  65. package/dist/sse-parser.d.ts +70 -0
  66. package/dist/sse-parser.d.ts.map +1 -0
  67. package/dist/sse-parser.js +159 -0
  68. package/dist/sse-parser.js.map +1 -0
  69. package/dist/transport.d.ts +53 -6
  70. package/dist/transport.d.ts.map +1 -1
  71. package/dist/transport.js +193 -40
  72. package/dist/transport.js.map +1 -1
  73. package/dist/types.d.ts +40 -10
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/unknown-tool.d.ts +28 -8
  76. package/dist/unknown-tool.d.ts.map +1 -1
  77. package/dist/unknown-tool.js +51 -52
  78. package/dist/unknown-tool.js.map +1 -1
  79. package/package.json +7 -7
package/README.md CHANGED
@@ -12,14 +12,32 @@ pnpm add @lushly-dev/afd-client
12
12
 
13
13
  ## Overview
14
14
 
15
- This package provides a client for connecting to MCP (Model Context Protocol) servers. It supports:
15
+ This package provides clients for AFD command servers. It supports:
16
16
 
17
17
  - **SSE Transport**: Real-time streaming with Server-Sent Events
18
18
  - **HTTP Transport**: Simple request/response communication
19
19
  - **Direct Transport**: Zero-overhead in-process execution for co-located agents
20
- - **Auto-reconnection**: Automatic reconnection with exponential backoff
20
+ - **Auto-reconnection**: Exponential backoff with jitter and a cap
21
21
  - **Type-safe API**: Full TypeScript support with CommandResult integration
22
22
 
23
+ ### Supported servers
24
+
25
+ `McpClient` talks to **AFD servers**: `createMcpServer()` from `@lushly-dev/afd-server`
26
+ (and the AFD Python server), through their HTTP transport:
27
+
28
+ | Route | Used for |
29
+ |-------|----------|
30
+ | `GET <base>/sse` | Event stream of the `sse` transport |
31
+ | `POST <base>/message` | JSON-RPC requests (`initialize`, `tools/list`, `tools/call`) |
32
+ | `GET <base>/health` | Reachability check on connect (`http` transport) |
33
+ | `POST <base>/stream/<command>` | `stream()` |
34
+
35
+ `McpClient` is **not a general MCP client**. It does not implement the MCP Streamable HTTP
36
+ transport (the `Accept: application/json, text/event-stream` negotiation and its session
37
+ handling), and it ignores the `endpoint` event of the legacy MCP SSE transport. Servers built
38
+ on the official MCP SDK answer it with HTTP 406 or 400. To talk to those servers, use the
39
+ official `@modelcontextprotocol/sdk` client.
40
+
23
41
  ## Usage
24
42
 
25
43
  ### Basic Connection
@@ -69,6 +87,22 @@ if (isSuccess(result)) {
69
87
  }
70
88
  ```
71
89
 
90
+ Pass per-request deadlines and cancellation to `call()`, `callTool()`, or `request()`:
91
+
92
+ ```typescript
93
+ const result = await client.call('item-get', { id: '123' }, {
94
+ timeout: 5_000,
95
+ signal: controller.signal,
96
+ });
97
+ ```
98
+
99
+ With the direct transport, deadlines and cancellation settle the request even when a handler
100
+ ignores its abort signal. Disconnecting also aborts active execution. A handler that has already
101
+ started may still complete its side effects; check a mutation's effect before retrying.
102
+ Direct discovery preserves the registry's input schema and planning metadata.
103
+ HTTP and SSE session renewal requires a successful JSON-RPC initialize result and a replacement
104
+ session ID before replaying a rejected request. Concurrent requests share renewal work.
105
+
72
106
  ### Event Handling
73
107
 
74
108
  ```typescript
@@ -102,6 +136,18 @@ client.on('toolsChanged', (tools) => {
102
136
  await client.connect();
103
137
  ```
104
138
 
139
+ - `connected` fires once the server is initialized **and** the tools list is loaded, so
140
+ `client.getTools()` is ready inside the handler. A failed tools refresh does not fail the
141
+ connection; the list stays empty.
142
+ - While reconnecting, each attempt emits `reconnecting`; failed attempts emit nothing else. If
143
+ every attempt fails, the client emits one `error` ("Max reconnection attempts reached", with the
144
+ last failure as `cause`) and moves to the `error` state.
145
+ - The delay before attempt *n* is `reconnectDelay * 2^(n-1)` plus up to 100 ms of jitter, capped
146
+ at `maxReconnectDelay`.
147
+ - The `sse` transport notices a closed event stream. The `http` transport has no persistent
148
+ connection, so it reports the connection as lost after 3 consecutive requests get no HTTP
149
+ response at all; `autoReconnect` then applies to it too.
150
+
105
151
  ### Client Status
106
152
 
107
153
  ```typescript
@@ -127,26 +173,92 @@ console.log('Content:', rawResult.content);
127
173
  console.log('Is error:', rawResult.isError);
128
174
  ```
129
175
 
176
+ `callTool()` and `request()` take an optional `{ timeout }` that overrides the client timeout
177
+ for that request. They throw `NotConnectedError`, `RequestTimeoutError`, `JsonRpcResponseError`
178
+ (with the JSON-RPC `code` and `data`) or `HttpStatusError`; `call()`, `batch()`, `pipe()` and
179
+ `stream()` never throw and return these as failures instead.
180
+
181
+ ### Batches and Pipelines
182
+
183
+ ```typescript
184
+ const batch = await client.batch(
185
+ [
186
+ { command: 'todo-create', input: { title: 'First' } },
187
+ { command: 'todo-create', input: { title: 'Second' } },
188
+ ],
189
+ { timeout: 60_000 } // server-side deadline for the whole batch
190
+ );
191
+
192
+ const pipeline = await client.pipe(
193
+ [{ command: 'user-get', input: { id: 1 }, as: 'user' }],
194
+ { timeoutMs: 60_000 } // server-side deadline for the whole pipeline
195
+ );
196
+ ```
197
+
198
+ The request waits for the batch `timeout` or pipeline `timeoutMs` plus a 5 second margin
199
+ (`SERVER_DEADLINE_MARGIN_MS`), and never less than the client `timeout`, so the server's own
200
+ timeout result arrives first.
201
+
202
+ If the server rejected the request (a JSON-RPC error, an HTTP 4xx) or the client was not
203
+ connected, nothing ran and the result is a definite failure. If the request timed out or the
204
+ connection failed after it was sent, the server may already have run some commands, so the
205
+ client does not guess: the result is an `OUTCOME_UNKNOWN` failure with `retryable: false`. A
206
+ batch then has no per-command `results` and zero success and failure counts; a pipeline has a
207
+ single pipeline-level step entry (`index: -1`) carrying the error. Check the commands' effects
208
+ before retrying.
209
+
210
+ ### Streaming
211
+
212
+ ```typescript
213
+ for await (const chunk of client.stream('report-generate', { month: 9 }, { timeout: 60_000 })) {
214
+ if (chunk.type === 'data') render(chunk.data);
215
+ if (chunk.type === 'error') console.error(chunk.error.code, chunk.error.suggestion);
216
+ }
217
+ ```
218
+
219
+ `stream()` posts to `<base>/stream/<command>`, where `<base>` is the client URL without a
220
+ trailing `/sse`, `/message` or `/messages` (so `https://host/api/mcp/sse` streams from
221
+ `https://host/api/mcp/stream/<command>`). It parses the event stream per the SSE spec
222
+ (`data:` with or without a space, multi-line `data`, comments, CRLF), and the last chunk is
223
+ always a `complete` or `error` chunk. The client makes the error chunk itself when:
224
+
225
+ | Code | When |
226
+ |------|------|
227
+ | `NOT_CONNECTED` | `stream()` was called before `connect()` (nothing is sent) |
228
+ | `STREAM_TRUNCATED` | The stream ended without a `complete` or `error` chunk |
229
+ | `STREAM_TIMEOUT` | `options.timeout` passed |
230
+ | `STREAM_CANCELLED` | `options.signal` aborted, or `disconnect()` was called |
231
+ | `STREAM_EVENT_TOO_LARGE` | One event exceeded `maxStreamEventSize` (default 1 MiB) |
232
+
233
+ A stream runs in the client's MCP session: it sends the `Mcp-Session-Id` from `initialize`, so
234
+ it sees the active context entered with `afd-context-enter`, like `call()`. If the server has
235
+ expired the session (HTTP 404), the client starts a new session and retries the stream once.
236
+
130
237
  ## Configuration
131
238
 
132
239
  ```typescript
133
240
  interface McpClientConfig {
134
- // Required
135
- url: string; // Server URL
241
+ url?: string; // Server URL (required unless transport is 'direct')
242
+ endpoint?: string; // Alias for url
136
243
 
137
- // Optional
138
- transport?: 'sse' | 'http'; // Default: 'sse'
244
+ transport?: 'sse' | 'http' | 'direct'; // Default: 'sse'
245
+ registry?: DirectRegistry; // Required with transport: 'direct'
139
246
  clientName?: string; // Default: '@lushly-dev/afd-client'
140
247
  clientVersion?: string; // Default: '0.1.0'
141
248
  timeout?: number; // Default: 30000 (30s)
142
249
  autoReconnect?: boolean; // Default: true
143
250
  maxReconnectAttempts?: number; // Default: 5
144
- reconnectDelay?: number; // Default: 1000 (1s)
251
+ reconnectDelay?: number; // Default: 1000 (1s), doubles per attempt
252
+ maxReconnectDelay?: number; // Default: 30000 (30s)
253
+ maxStreamEventSize?: number; // Default: 1048576 characters
145
254
  headers?: Record<string, string>;
146
255
  debug?: boolean; // Default: false
147
256
  }
148
257
  ```
149
258
 
259
+ Other transport names (`'websocket'`, `'stdio'`) are rejected by the type and, for JavaScript
260
+ callers, by the constructor with an error that names the supported ones.
261
+
150
262
  ## Transports
151
263
 
152
264
  ### SSE Transport (Default)
@@ -171,23 +283,55 @@ const client = createClient({
171
283
  });
172
284
  ```
173
285
 
174
- ### Direct Transport (Zero Overhead)
286
+ ### Direct Transport with McpClient
287
+
288
+ `transport: 'direct'` runs an `McpClient` against an in-process registry, so code written for a
289
+ remote AFD server works unchanged in tests or embedded setups. `call()`, `batch()`, `pipe()`
290
+ and `stream()` all work (batches and pipelines run through the same core executors as the
291
+ server). No URL is needed.
292
+
293
+ ```typescript
294
+ import { createClient } from '@lushly-dev/afd-client';
295
+ import { createDirectRegistry } from '@lushly-dev/afd-server';
296
+
297
+ const client = createClient({ transport: 'direct', registry: createDirectRegistry(commands) });
298
+ await client.connect();
299
+ const result = await client.call('todo-list', {});
300
+ ```
301
+
302
+ An unknown command returns an `UNKNOWN_TOOL` failure whose `suggestion` names the closest
303
+ command, exactly as `DirectClient` does, and a command that throws returns a
304
+ `COMMAND_EXECUTION_ERROR` failure without the exception text.
305
+
306
+ ### DirectClient (Zero Overhead)
175
307
 
176
- For co-located agents (same runtime as the application), use `createDirectClient` to bypass all transport overhead:
308
+ For co-located agents (same runtime as the application), use `createDirectClient` to bypass all transport overhead. Build the registry with `createDirectRegistry` from `@lushly-dev/afd-server`: it runs each call through the same engine as the MCP server (Zod input validation, middleware, error sanitization) and only offers commands exposed to agents (`expose.agent`, on by default).
177
309
 
178
310
  ```typescript
179
- import { createDirectClient } from '@lushly-dev/afd-client';
180
- import { registry } from '@my-app/commands';
311
+ import { isSuccess } from '@lushly-dev/afd-core';
312
+ import { createDirectClient, isUnknownToolError } from '@lushly-dev/afd-client';
313
+ import { createDirectRegistry } from '@lushly-dev/afd-server';
314
+ import { commands } from '@my-app/commands';
181
315
 
182
316
  // Direct execution - ~0.03-0.1ms latency vs 2-10ms for MCP
183
- const client = createDirectClient(registry);
317
+ const client = createDirectClient(createDirectRegistry(commands));
184
318
 
185
319
  const result = await client.call<Todo>('todo-create', { title: 'Fast!' });
186
- if (result.success) {
187
- console.log('Created:', result.data.id);
320
+ if (isUnknownToolError(result)) {
321
+ console.log(result.data?.hint); // "Did you mean 'todo-create'?"
322
+ } else if (isSuccess(result)) {
323
+ console.log('Created:', result.data.id); // result is CommandResult<Todo>
188
324
  }
189
325
  ```
190
326
 
327
+ `call<T>()` returns `CommandResult<T> | CommandResult<UnknownToolError>`, so
328
+ `result.success` alone does not narrow it. Rule out the unknown-tool case with
329
+ `isUnknownToolError(result)` first.
330
+
331
+ `call()` never rejects. If a registry, handler or client middleware throws, it returns a
332
+ `COMMAND_EXECUTION_ERROR` failure without the exception text (turn on `debug` to log the
333
+ exception), the same result `createDirectRegistry()` and the MCP server give.
334
+
191
335
  **Performance comparison:**
192
336
 
193
337
  | Transport | Avg Latency | Use Case |
@@ -202,16 +346,21 @@ if (result.success) {
202
346
  const client = createDirectClient(registry, {
203
347
  source: 'my-agent', // Identifier propagated to handlers
204
348
  debug: true, // Enable debug logging
205
- validateInputs: true, // Validate inputs against schemas (default: true)
349
+ validateInputs: true, // Shallow checks for registries with getCommand() (default: true)
350
+ middleware: [], // Client-side middleware, outside the registry's own
351
+ allow: (name) => name.startsWith('todo-'), // Others get COMMAND_NOT_ALLOWED
206
352
  });
207
353
  ```
208
354
 
209
- #### Context Propagation
355
+ `allow` narrows what the client may call. Refused commands return a
356
+ `COMMAND_NOT_ALLOWED` failure without reaching the registry, and are left out of
357
+ `listCommands()`, `listCommandNames()` and `hasCommand()`.
358
+
359
+ #### Context Propagation and Timeouts
210
360
 
211
- Pass context to individual calls for tracing and cancellation:
361
+ Pass context to individual calls for tracing, cancellation and timeouts:
212
362
 
213
363
  ```typescript
214
- // Custom trace ID
215
364
  const result = await client.call('command', args, {
216
365
  traceId: 'custom-trace-123',
217
366
  timeout: 5000,
@@ -222,32 +371,34 @@ const result = await client.call('command', args, {
222
371
  // Handler receives: { traceId, source, timeout, signal, ... }
223
372
  ```
224
373
 
374
+ `timeout` is enforced (per step in `pipe()`). When it passes, the `signal` the
375
+ handler receives aborts (it combines your `signal` with the timeout), and the
376
+ call resolves to a `TIMEOUT` failure even if the handler ignores the signal. The
377
+ handler may still finish its work, so check a mutation's effect before retrying.
378
+
225
379
  #### Input Validation
226
380
 
227
- If your registry implements `getCommand()`, DirectClient validates inputs:
381
+ `createDirectRegistry` validates every call with the command's Zod schema, so
382
+ wrong types, nested objects and out-of-range values are rejected before the
383
+ handler runs:
228
384
 
229
385
  ```typescript
230
- class MyRegistry implements DirectRegistry {
231
- // ... other methods ...
232
-
233
- getCommand(name: string): CommandDefinition | undefined {
234
- return this.commands.get(name);
235
- }
236
- }
237
-
238
- const client = createDirectClient(registry, { validateInputs: true });
239
-
240
- // Missing required parameter
241
- const result = await client.call('todo-create', {});
386
+ const result = await client.call('todo-create', { title: { nested: true } });
242
387
  // Result: { success: false, error: { code: 'VALIDATION_ERROR', ... } }
243
388
  ```
244
389
 
390
+ With a custom registry, DirectClient only performs shallow checks (required
391
+ top-level fields, primitive types, enums), and only when the registry implements
392
+ `getCommand()`.
393
+
245
394
  #### DirectRegistry Interface
246
395
 
247
- Your registry must implement:
396
+ `createDirectRegistry` returns a compatible registry. A custom registry must
397
+ implement the following, and is then responsible for its own validation and
398
+ exposure checks:
248
399
 
249
400
  ```typescript
250
- import { DirectRegistry, CommandDefinition } from '@lushly-dev/afd-client';
401
+ import type { CommandDefinition, DirectRegistry } from '@lushly-dev/afd-client';
251
402
  import type { CommandResult, CommandContext } from '@lushly-dev/afd-core';
252
403
 
253
404
  class MyRegistry implements DirectRegistry {
@@ -262,7 +413,7 @@ class MyRegistry implements DirectRegistry {
262
413
  listCommands(): Array<{ name: string; description: string }>;
263
414
  hasCommand(name: string): boolean;
264
415
 
265
- // Optional - enables input validation
416
+ // Optional - enables DirectClient's shallow input checks
266
417
  getCommand?(name: string): CommandDefinition | undefined;
267
418
  }
268
419
  ```
@@ -292,6 +443,38 @@ if (isFailure(result)) {
292
443
  }
293
444
  ```
294
445
 
446
+ Protocol and transport errors map to AFD codes with a `suggestion` and no stack trace. The
447
+ server's own `error.data.suggestion` is used when it sends one.
448
+
449
+ | Cause | `code` | `retryable` |
450
+ |-------|--------|-------------|
451
+ | JSON-RPC -32700 | `PARSE_ERROR` | no |
452
+ | JSON-RPC -32600 | `INVALID_REQUEST` | no |
453
+ | JSON-RPC -32601 | `METHOD_NOT_FOUND` | no |
454
+ | JSON-RPC -32602 | `INVALID_INPUT` | no |
455
+ | JSON-RPC -32603 | `INTERNAL_ERROR` | yes |
456
+ | JSON-RPC -32000 (AFD: Host, Origin, Content-Type or size rejected) | `REQUEST_REJECTED` | no |
457
+ | JSON-RPC -32001 (AFD: unknown or expired `Mcp-Session-Id`) | `SESSION_NOT_FOUND` | yes |
458
+ | Other JSON-RPC codes | `JSON_RPC_ERROR` | no |
459
+ | Other HTTP status | `HTTP_<status>` | 5xx and 429 only |
460
+ | No response within `timeout` | `TIMEOUT` | yes |
461
+ | Network failure | `CONNECTION_ERROR` | yes |
462
+ | Called before `connect()` | `NOT_CONNECTED` | no |
463
+
464
+ The details carry `jsonRpcCode` for JSON-RPC errors.
465
+
466
+ ## Handoff Reconnection
467
+
468
+ `createReconnectingHandoff(client, handoff, options)` accepts any client with a
469
+ `call(name, args)` method (`HandoffCommandClient`), so both `McpClient` and `DirectClient` work.
470
+ If the initial connection fails, the promise rejects and nothing keeps running: a browser
471
+ WebSocket that reports a failed handshake as `error` followed by `close` (1006) does not start
472
+ a background reconnect loop.
473
+
474
+ `maxAttempts` and `backoffMs` come from `options`, else from the handoff's
475
+ `metadata.reconnect`, else from core's `defaultReconnectPolicy` (3 attempts, 1000 ms base
476
+ backoff), the same policy `createHandoff()` applies on the server.
477
+
295
478
  ## License
296
479
 
297
480
  MIT
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @fileoverview Reconnection backoff shared by `McpClient` and `createReconnectingHandoff()`.
3
+ */
4
+ /**
5
+ * Exponential backoff with jitter and a cap: `base * 2^(attempt - 1)` plus up to 100 ms of
6
+ * jitter, never more than `maxMs`.
7
+ *
8
+ * @param attempt - Attempt number, starting at 1
9
+ * @param baseMs - Delay before the first attempt
10
+ * @param maxMs - Upper bound for any delay
11
+ */
12
+ export declare function backoffDelay(attempt: number, baseMs: number, maxMs: number): number;
13
+ /** A delay that can be cut short: `cancel()` resolves the pending `wait()` at once. */
14
+ export declare class CancellableDelay {
15
+ private timer;
16
+ private resolvePending;
17
+ wait(ms: number): Promise<void>;
18
+ cancel(): void;
19
+ }
20
+ //# sourceMappingURL=backoff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.d.ts","sourceRoot":"","sources":["../src/backoff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAGnF;AAED,uFAAuF;AACvF,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,KAAK,CAA8C;IAC3D,OAAO,CAAC,cAAc,CAA6B;IAEnD,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAY/B,MAAM,IAAI,IAAI;CAOd"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @fileoverview Reconnection backoff shared by `McpClient` and `createReconnectingHandoff()`.
3
+ */
4
+ /** Random jitter added to every delay, so clients that lost the same server spread out. */
5
+ const MAX_JITTER_MS = 100;
6
+ /**
7
+ * Exponential backoff with jitter and a cap: `base * 2^(attempt - 1)` plus up to 100 ms of
8
+ * jitter, never more than `maxMs`.
9
+ *
10
+ * @param attempt - Attempt number, starting at 1
11
+ * @param baseMs - Delay before the first attempt
12
+ * @param maxMs - Upper bound for any delay
13
+ */
14
+ export function backoffDelay(attempt, baseMs, maxMs) {
15
+ const exponential = baseMs * 2 ** Math.max(0, attempt - 1);
16
+ return Math.max(0, Math.min(exponential + Math.random() * MAX_JITTER_MS, maxMs));
17
+ }
18
+ /** A delay that can be cut short: `cancel()` resolves the pending `wait()` at once. */
19
+ export class CancellableDelay {
20
+ timer = null;
21
+ resolvePending = null;
22
+ wait(ms) {
23
+ this.cancel();
24
+ return new Promise((resolve) => {
25
+ this.resolvePending = resolve;
26
+ this.timer = setTimeout(() => {
27
+ this.timer = null;
28
+ this.resolvePending = null;
29
+ resolve();
30
+ }, ms);
31
+ });
32
+ }
33
+ cancel() {
34
+ if (this.timer)
35
+ clearTimeout(this.timer);
36
+ this.timer = null;
37
+ const resolve = this.resolvePending;
38
+ this.resolvePending = null;
39
+ resolve?.();
40
+ }
41
+ }
42
+ //# sourceMappingURL=backoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.js","sourceRoot":"","sources":["../src/backoff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,2FAA2F;AAC3F,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,MAAc,EAAE,KAAa;IAC1E,MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,CAAC,CAAC;IAC3D,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,WAAW,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC;AAClF,CAAC;AAED,uFAAuF;AACvF,MAAM,OAAO,gBAAgB;IACpB,KAAK,GAAyC,IAAI,CAAC;IACnD,cAAc,GAAwB,IAAI,CAAC;IAEnD,IAAI,CAAC,EAAU;QACd,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC9B,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC;YAC9B,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;gBAClB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACX,CAAC,EAAE,EAAE,CAAC,CAAC;QACR,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,MAAM;QACL,IAAI,IAAI,CAAC,KAAK;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC;QACpC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,OAAO,EAAE,EAAE,CAAC;IACb,CAAC;CACD"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @fileoverview Errors raised by `McpClient.request()` and their mapping to AFD `CommandError`s.
3
+ *
4
+ * `request()` throws one of these classes so callers can tell whether the server could have run
5
+ * the request: a JSON-RPC error answer or a 4xx HTTP status means it refused the request, while a
6
+ * timeout, a dropped connection or a 5xx status leaves the outcome unknown.
7
+ */
8
+ import type { CommandError, McpError } from '@lushly-dev/afd-core';
9
+ /** The client is not connected, so nothing was sent. */
10
+ export declare class NotConnectedError extends Error {
11
+ constructor();
12
+ }
13
+ /** No response arrived within the request timeout. */
14
+ export declare class RequestTimeoutError extends Error {
15
+ readonly method: string;
16
+ readonly timeoutMs: number;
17
+ constructor(method: string, timeoutMs: number);
18
+ }
19
+ /** The server answered with a non-2xx HTTP status and no JSON-RPC error body. */
20
+ export declare class HttpStatusError extends Error {
21
+ readonly status: number;
22
+ readonly statusText: string;
23
+ constructor(status: number, statusText: string);
24
+ }
25
+ /** The server answered with a JSON-RPC error object. */
26
+ export declare class JsonRpcResponseError extends Error {
27
+ readonly code: number;
28
+ readonly data: unknown;
29
+ constructor(error: McpError);
30
+ }
31
+ /** Map a JSON-RPC error answer to a CommandError, preferring the server's own suggestion. */
32
+ export declare function jsonRpcErrorToCommandError(error: JsonRpcResponseError): CommandError;
33
+ /** Whether the server can have run the request that failed with `error`. */
34
+ export declare function isOutcomeUnknown(error: unknown): boolean;
35
+ /**
36
+ * Convert an error thrown by `request()` into a CommandError without a stack trace.
37
+ */
38
+ export declare function toCommandError(error: unknown): CommandError;
39
+ //# sourceMappingURL=client-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-errors.d.ts","sourceRoot":"","sources":["../src/client-errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGnE,wDAAwD;AACxD,qBAAa,iBAAkB,SAAQ,KAAK;;CAK3C;AAED,sDAAsD;AACtD,qBAAa,mBAAoB,SAAQ,KAAK;IAE5C,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM;gBADjB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM;CAK3B;AAED,iFAAiF;AACjF,qBAAa,eAAgB,SAAQ,KAAK;IAExC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM;gBADlB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM;CAK5B;AAED,wDAAwD;AACxD,qBAAa,oBAAqB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;gBAEX,KAAK,EAAE,QAAQ;CAM3B;AA4DD,6FAA6F;AAC7F,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,oBAAoB,GAAG,YAAY,CAYpF;AAED,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAOxD;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,CAwC3D"}
@@ -0,0 +1,163 @@
1
+ /**
2
+ * @fileoverview Errors raised by `McpClient.request()` and their mapping to AFD `CommandError`s.
3
+ *
4
+ * `request()` throws one of these classes so callers can tell whether the server could have run
5
+ * the request: a JSON-RPC error answer or a 4xx HTTP status means it refused the request, while a
6
+ * timeout, a dropped connection or a 5xx status leaves the outcome unknown.
7
+ */
8
+ import { ErrorCodes, isCommandError } from '@lushly-dev/afd-core';
9
+ /** The client is not connected, so nothing was sent. */
10
+ export class NotConnectedError extends Error {
11
+ constructor() {
12
+ super('Not connected');
13
+ this.name = 'NotConnectedError';
14
+ }
15
+ }
16
+ /** No response arrived within the request timeout. */
17
+ export class RequestTimeoutError extends Error {
18
+ method;
19
+ timeoutMs;
20
+ constructor(method, timeoutMs) {
21
+ super(`Request '${method}' timed out after ${timeoutMs}ms`);
22
+ this.method = method;
23
+ this.timeoutMs = timeoutMs;
24
+ this.name = 'RequestTimeoutError';
25
+ }
26
+ }
27
+ /** The server answered with a non-2xx HTTP status and no JSON-RPC error body. */
28
+ export class HttpStatusError extends Error {
29
+ status;
30
+ statusText;
31
+ constructor(status, statusText) {
32
+ super(`HTTP error: ${status} ${statusText}`);
33
+ this.status = status;
34
+ this.statusText = statusText;
35
+ this.name = 'HttpStatusError';
36
+ }
37
+ }
38
+ /** The server answered with a JSON-RPC error object. */
39
+ export class JsonRpcResponseError extends Error {
40
+ code;
41
+ data;
42
+ constructor(error) {
43
+ super(error.message);
44
+ this.name = 'JsonRpcResponseError';
45
+ this.code = error.code;
46
+ this.data = error.data;
47
+ }
48
+ }
49
+ /** JSON-RPC 2.0 codes and the AFD server's `-32000`/`-32001` extensions. */
50
+ const JSON_RPC_CODES = {
51
+ [-32700]: {
52
+ code: 'PARSE_ERROR',
53
+ retryable: false,
54
+ suggestion: 'The server could not parse the request as JSON; check the arguments are serializable',
55
+ },
56
+ [-32600]: {
57
+ code: 'INVALID_REQUEST',
58
+ retryable: false,
59
+ suggestion: 'The server rejected the JSON-RPC envelope; check that it is an AFD MCP endpoint',
60
+ },
61
+ [-32601]: {
62
+ code: 'METHOD_NOT_FOUND',
63
+ retryable: false,
64
+ suggestion: 'The server does not support this MCP method; check the server type and version',
65
+ },
66
+ [-32602]: {
67
+ code: ErrorCodes.INVALID_INPUT,
68
+ retryable: false,
69
+ suggestion: 'Correct the request parameters (tool name and arguments object) and try again',
70
+ },
71
+ [-32603]: {
72
+ code: ErrorCodes.INTERNAL_ERROR,
73
+ retryable: true,
74
+ suggestion: 'The server failed while handling the request; retry, and check the server logs if it persists',
75
+ outcomeUnknown: true,
76
+ },
77
+ [-32000]: {
78
+ code: 'REQUEST_REJECTED',
79
+ retryable: false,
80
+ suggestion: 'The server rejected the HTTP request (Host, Origin, Content-Type or size); check the URL and headers',
81
+ },
82
+ [-32001]: {
83
+ code: 'SESSION_NOT_FOUND',
84
+ retryable: true,
85
+ suggestion: 'The MCP session is unknown or expired; reconnect to start a new session',
86
+ },
87
+ };
88
+ function serverSuggestion(data) {
89
+ if (typeof data !== 'object' || data === null || !('suggestion' in data))
90
+ return undefined;
91
+ return typeof data.suggestion === 'string' && data.suggestion.length > 0
92
+ ? data.suggestion
93
+ : undefined;
94
+ }
95
+ /** Map a JSON-RPC error answer to a CommandError, preferring the server's own suggestion. */
96
+ export function jsonRpcErrorToCommandError(error) {
97
+ const mapping = JSON_RPC_CODES[error.code];
98
+ return {
99
+ code: mapping?.code ?? 'JSON_RPC_ERROR',
100
+ message: error.message || 'The server returned a JSON-RPC error',
101
+ suggestion: serverSuggestion(error.data) ??
102
+ mapping?.suggestion ??
103
+ 'Check the request against the server documentation',
104
+ retryable: mapping?.retryable ?? false,
105
+ details: { jsonRpcCode: error.code },
106
+ };
107
+ }
108
+ /** Whether the server can have run the request that failed with `error`. */
109
+ export function isOutcomeUnknown(error) {
110
+ if (error instanceof NotConnectedError)
111
+ return false;
112
+ if (error instanceof JsonRpcResponseError) {
113
+ return JSON_RPC_CODES[error.code]?.outcomeUnknown === true;
114
+ }
115
+ if (error instanceof HttpStatusError)
116
+ return error.status < 400 || error.status >= 500;
117
+ return true;
118
+ }
119
+ /**
120
+ * Convert an error thrown by `request()` into a CommandError without a stack trace.
121
+ */
122
+ export function toCommandError(error) {
123
+ if (error instanceof JsonRpcResponseError)
124
+ return jsonRpcErrorToCommandError(error);
125
+ if (error instanceof NotConnectedError) {
126
+ return {
127
+ code: 'NOT_CONNECTED',
128
+ message: 'The client is not connected',
129
+ suggestion: 'Call connect() and try again',
130
+ retryable: false,
131
+ };
132
+ }
133
+ if (error instanceof RequestTimeoutError) {
134
+ return {
135
+ code: ErrorCodes.TIMEOUT,
136
+ message: error.message,
137
+ suggestion: 'Retry with a larger timeout. The server may still have run the request, so check its effect before retrying a mutation.',
138
+ retryable: true,
139
+ details: { method: error.method, timeoutMs: error.timeoutMs },
140
+ };
141
+ }
142
+ if (error instanceof HttpStatusError) {
143
+ const serverSide = error.status >= 500 || error.status === 429;
144
+ return {
145
+ code: `HTTP_${error.status}`,
146
+ message: error.message,
147
+ suggestion: serverSide
148
+ ? 'The server is unavailable or overloaded; retry later'
149
+ : 'The server refused the request; check that the URL points to an AFD MCP server endpoint',
150
+ retryable: serverSide,
151
+ };
152
+ }
153
+ if (isCommandError(error))
154
+ return { ...error };
155
+ const message = error instanceof Error ? error.message : String(error);
156
+ return {
157
+ code: ErrorCodes.CONNECTION_ERROR,
158
+ message: message || 'The request failed',
159
+ suggestion: 'Check that the server is reachable and retry. The request may have reached the server, so check its effect before retrying a mutation.',
160
+ retryable: true,
161
+ };
162
+ }
163
+ //# sourceMappingURL=client-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-errors.js","sourceRoot":"","sources":["../src/client-errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAElE,wDAAwD;AACxD,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAC3C;QACC,KAAK,CAAC,eAAe,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IACjC,CAAC;CACD;AAED,sDAAsD;AACtD,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAEnC;IACA;IAFV,YACU,MAAc,EACd,SAAiB;QAE1B,KAAK,CAAC,YAAY,MAAM,qBAAqB,SAAS,IAAI,CAAC,CAAC;QAHnD,WAAM,GAAN,MAAM,CAAQ;QACd,cAAS,GAAT,SAAS,CAAQ;QAG1B,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACnC,CAAC;CACD;AAED,iFAAiF;AACjF,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAE/B;IACA;IAFV,YACU,MAAc,EACd,UAAkB;QAE3B,KAAK,CAAC,eAAe,MAAM,IAAI,UAAU,EAAE,CAAC,CAAC;QAHpC,WAAM,GAAN,MAAM,CAAQ;QACd,eAAU,GAAV,UAAU,CAAQ;QAG3B,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAC/B,CAAC;CACD;AAED,wDAAwD;AACxD,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACrC,IAAI,CAAS;IACb,IAAI,CAAU;IAEvB,YAAY,KAAe;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