@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/index.js CHANGED
@@ -1,17 +1,22 @@
1
1
  /**
2
2
  * @fileoverview @lushly-dev/afd-client - MCP client library for Agent-First Development
3
3
  *
4
- * This package provides a client for connecting to MCP servers:
4
+ * This package provides clients for AFD command servers:
5
5
  *
6
- * - **McpClient**: Main client class with connection management
7
- * - **Transports**: SSE and HTTP transports for communication
6
+ * - **McpClient**: Client for AFD MCP servers (`createMcpServer()`), with connection management
7
+ * - **Transports**: SSE and HTTP for AFD servers, direct for an in-process registry
8
+ * - **DirectClient**: Zero-overhead in-process command execution
8
9
  * - **Type-safe**: Full TypeScript support with CommandResult integration
9
10
  * - **Handoff Support**: Protocol handlers for streaming connections
10
11
  *
12
+ * McpClient does not implement the MCP Streamable HTTP transport, so it cannot talk to servers
13
+ * built on the official MCP SDK.
14
+ *
11
15
  * @packageDocumentation
12
16
  */
13
- export { createClient, McpClient } from './client.js';
14
- export { createDirectClient, DirectClient, DirectTransport, } from './direct.js';
17
+ export { createClient, McpClient, SERVER_DEADLINE_MARGIN_MS, } from './client.js';
18
+ export { HttpStatusError, JsonRpcResponseError, NotConnectedError, RequestTimeoutError, } from './client-errors.js';
19
+ export { createDirectClient, DirectClient, DirectTransport, isUnknownToolError, } from './direct.js';
15
20
  // Built-in protocol handlers
16
21
  export { builtinHandlers, sseHandler, websocketHandler } from './handlers.js';
17
22
  // Handoff protocol handlers and utilities
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAYH,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAGN,kBAAkB,EAElB,YAAY,EAGZ,eAAe,GAEf,MAAM,aAAa,CAAC;AACrB,6BAA6B;AAC7B,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAC9E,0CAA0C;AAC1C,OAAO;AACN,mBAAmB;AACnB,0BAA0B,EAC1B,qBAAqB;AACrB,uBAAuB;AACvB,cAAc,EACd,yBAAyB,EACzB,aAAa,EACb,kBAAkB,EASlB,kBAAkB;AAClB,sCAAsC;AACtC,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EAEpB,oBAAoB;AAGpB,4BAA4B;AAC5B,uBAAuB,EACvB,yBAAyB,GACzB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAkB,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAYH,OAAO,EACN,YAAY,EACZ,SAAS,EAET,yBAAyB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,GACnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGN,kBAAkB,EAElB,YAAY,EAGZ,eAAe,EACf,kBAAkB,GAElB,MAAM,aAAa,CAAC;AACrB,6BAA6B;AAC7B,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAC9E,0CAA0C;AAC1C,OAAO;AACN,mBAAmB;AACnB,0BAA0B,EAC1B,qBAAqB;AACrB,uBAAuB;AACvB,cAAc,EACd,yBAAyB,EACzB,aAAa,EACb,kBAAkB,EAUlB,kBAAkB;AAClB,sCAAsC;AACtC,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EAEpB,oBAAoB;AAGpB,4BAA4B;AAC5B,uBAAuB,EACvB,yBAAyB,GACzB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAkB,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @fileoverview The MCP session of the HTTP and SSE transports (`Mcp-Session-Id`).
3
+ */
4
+ import type { McpRequest } from '@lushly-dev/afd-core';
5
+ /**
6
+ * The MCP session a server issued in the `Mcp-Session-Id` header of its `initialize`
7
+ * response. It is repeated on later requests, so per-session server state (such as the
8
+ * active context of `afd-context-enter`) belongs to this client alone.
9
+ */
10
+ export declare class McpSession {
11
+ private id;
12
+ private initialize;
13
+ /** The current session ID, if the server issued one. */
14
+ get sessionId(): string | undefined;
15
+ reset(): void;
16
+ /**
17
+ * POST one JSON-RPC request. If the server answers 404 to a request that carried a
18
+ * session (it restarted or expired the session), start a new session with the same
19
+ * `initialize` request and retry once; the server ran nothing for the rejected request.
20
+ */
21
+ post(url: string, headers: Record<string, string> | undefined, request: McpRequest, signal: AbortSignal): Promise<Response>;
22
+ /**
23
+ * Replace the session with a new one by re-sending the last `initialize` request.
24
+ * Returns `false`, sending nothing, when no `initialize` request was sent yet.
25
+ */
26
+ renew(url: string, headers: Record<string, string> | undefined, signal: AbortSignal): Promise<boolean>;
27
+ private send;
28
+ }
29
+ //# sourceMappingURL=mcp-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-session.d.ts","sourceRoot":"","sources":["../src/mcp-session.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;;;GAIG;AACH,qBAAa,UAAU;IACtB,OAAO,CAAC,EAAE,CAAqB;IAC/B,OAAO,CAAC,UAAU,CAAyB;IAE3C,wDAAwD;IACxD,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED,KAAK,IAAI,IAAI;IAKb;;;;OAIG;IACG,IAAI,CACT,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAC3C,OAAO,EAAE,UAAU,EACnB,MAAM,EAAE,WAAW,GACjB,OAAO,CAAC,QAAQ,CAAC;IAYpB;;;OAGG;IACG,KAAK,CACV,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAC3C,MAAM,EAAE,WAAW,GACjB,OAAO,CAAC,OAAO,CAAC;YAQL,IAAI;CAoBlB"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @fileoverview The MCP session of the HTTP and SSE transports (`Mcp-Session-Id`).
3
+ */
4
+ /**
5
+ * The MCP session a server issued in the `Mcp-Session-Id` header of its `initialize`
6
+ * response. It is repeated on later requests, so per-session server state (such as the
7
+ * active context of `afd-context-enter`) belongs to this client alone.
8
+ */
9
+ export class McpSession {
10
+ id;
11
+ initialize;
12
+ /** The current session ID, if the server issued one. */
13
+ get sessionId() {
14
+ return this.id;
15
+ }
16
+ reset() {
17
+ this.id = undefined;
18
+ this.initialize = undefined;
19
+ }
20
+ /**
21
+ * POST one JSON-RPC request. If the server answers 404 to a request that carried a
22
+ * session (it restarted or expired the session), start a new session with the same
23
+ * `initialize` request and retry once; the server ran nothing for the rejected request.
24
+ */
25
+ async post(url, headers, request, signal) {
26
+ if (request.method === 'initialize') {
27
+ this.id = undefined;
28
+ this.initialize = request;
29
+ }
30
+ const sentSession = this.id !== undefined;
31
+ const response = await this.send(url, headers, request, signal);
32
+ if (response.status !== 404 || !sentSession)
33
+ return response;
34
+ if (!(await this.renew(url, headers, signal)))
35
+ return response;
36
+ return this.send(url, headers, request, signal);
37
+ }
38
+ /**
39
+ * Replace the session with a new one by re-sending the last `initialize` request.
40
+ * Returns `false`, sending nothing, when no `initialize` request was sent yet.
41
+ */
42
+ async renew(url, headers, signal) {
43
+ if (!this.initialize)
44
+ return false;
45
+ this.id = undefined;
46
+ const renewed = await this.send(url, headers, this.initialize, signal);
47
+ await renewed.body?.cancel();
48
+ return true;
49
+ }
50
+ async send(url, headers, request, signal) {
51
+ const response = await fetch(url, {
52
+ method: 'POST',
53
+ headers: {
54
+ 'Content-Type': 'application/json',
55
+ ...headers,
56
+ ...(this.id ? { 'Mcp-Session-Id': this.id } : {}),
57
+ },
58
+ body: JSON.stringify(request),
59
+ signal,
60
+ });
61
+ const issued = response.headers?.get('mcp-session-id');
62
+ if (issued)
63
+ this.id = issued;
64
+ return response;
65
+ }
66
+ }
67
+ //# sourceMappingURL=mcp-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-session.js","sourceRoot":"","sources":["../src/mcp-session.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH;;;;GAIG;AACH,MAAM,OAAO,UAAU;IACd,EAAE,CAAqB;IAC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,MAAM,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACb,CAAC;IAEO,KAAK,CAAC,IAAI,CACjB,GAAW,EACX,OAA2C,EAC3C,OAAmB,EACnB,MAAmB;QAEnB,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;YACjC,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACR,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;gBACV,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACjD;YACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;YAC7B,MAAM;SACN,CAAC,CAAC;QACH,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,gBAAgB,CAAC,CAAC;QACvD,IAAI,MAAM;YAAE,IAAI,CAAC,EAAE,GAAG,MAAM,CAAC;QAC7B,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @fileoverview `McpClient.stream()` over HTTP (`POST <base>/stream/<command>`) and in process.
3
+ *
4
+ * Every stream ends with exactly one terminal chunk the caller can rely on: the server's
5
+ * `complete` or `error` chunk, or a client-made error chunk that says why the stream stopped
6
+ * (`STREAM_TRUNCATED`, `STREAM_TIMEOUT`, `STREAM_CANCELLED`, `STREAM_EVENT_TOO_LARGE`, ...).
7
+ */
8
+ import type { CommandError, ErrorChunk, StreamChunk } from '@lushly-dev/afd-core';
9
+ import type { DirectRegistry } from './direct-types.js';
10
+ /**
11
+ * The `/stream/<command>` URL for a server URL. A trailing `/sse`, `/message` or `/messages` is
12
+ * replaced and any other base path is kept, so `http://host/api/mcp/sse` streams from
13
+ * `http://host/api/mcp/stream/<command>` (the same rule as the Python client).
14
+ */
15
+ export declare function deriveStreamUrl(serverUrl: string, commandName: string): string;
16
+ /** A client-made terminal error chunk. */
17
+ export declare function streamErrorChunk(error: CommandError, chunksBeforeError: number, recoverable?: boolean): ErrorChunk;
18
+ /** Why a stream's signal was aborted. */
19
+ export interface StreamAbortState {
20
+ /** The stream's own timeout fired. */
21
+ timedOut: boolean;
22
+ /** The caller's signal, if any. */
23
+ callerSignal?: AbortSignal;
24
+ /** The signal the client aborts on `disconnect()` or timeout. */
25
+ controller: AbortController;
26
+ }
27
+ /** The client's MCP session, as its transport exposes it. */
28
+ export interface StreamSession {
29
+ /** Sent as `Mcp-Session-Id` when set. */
30
+ readonly sessionId?: string;
31
+ /** Start a new session after the server rejected this one; `false` when it cannot. */
32
+ renewSession?(signal?: AbortSignal): Promise<boolean>;
33
+ }
34
+ /** Options for {@link streamOverHttp}. */
35
+ export interface HttpStreamRequest {
36
+ url: string;
37
+ args: Record<string, unknown> | undefined;
38
+ headers: Record<string, string>;
39
+ /** The session the stream runs in, so it sees the session's active context. */
40
+ session?: StreamSession;
41
+ signal: AbortSignal;
42
+ abort: StreamAbortState;
43
+ timeoutMs: number | undefined;
44
+ maxEventSize: number;
45
+ debug: (message: string, data?: unknown) => void;
46
+ }
47
+ /**
48
+ * Stream a command from an AFD server's `/stream/<command>` endpoint.
49
+ */
50
+ export declare function streamOverHttp<T>(request: HttpStreamRequest): AsyncGenerator<StreamChunk<T>, void, unknown>;
51
+ /**
52
+ * Stream a command in process through a registry, with the stream semantics of core's
53
+ * `executeStream()`.
54
+ */
55
+ export declare function streamDirect<T>(registry: DirectRegistry, name: string, args: Record<string, unknown> | undefined, signal: AbortSignal, abort: StreamAbortState, timeoutMs: number | undefined): AsyncGenerator<StreamChunk<T>, void, unknown>;
56
+ //# sourceMappingURL=mcp-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-stream.d.ts","sourceRoot":"","sources":["../src/mcp-stream.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KA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AAC;CACjD;AA8BD;;GAEG;AACH,wBAAuB,cAAc,CAAC,CAAC,EACtC,OAAO,EAAE,iBAAiB,GACxB,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAsE/C;AAED;;;GAGG;AACH,wBAAuB,YAAY,CAAC,CAAC,EACpC,QAAQ,EAAE,cAAc,EACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACzC,MAAM,EAAE,WAAW,EACnB,KAAK,EAAE,gBAAgB,EACvB,SAAS,EAAE,MAAM,GAAG,SAAS,GAC3B,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAe/C"}
@@ -0,0 +1,192 @@
1
+ /**
2
+ * @fileoverview `McpClient.stream()` over HTTP (`POST <base>/stream/<command>`) and in process.
3
+ *
4
+ * Every stream ends with exactly one terminal chunk the caller can rely on: the server's
5
+ * `complete` or `error` chunk, or a client-made error chunk that says why the stream stopped
6
+ * (`STREAM_TRUNCATED`, `STREAM_TIMEOUT`, `STREAM_CANCELLED`, `STREAM_EVENT_TOO_LARGE`, ...).
7
+ */
8
+ import { executeStream, isCommandError, isCompleteChunk, isErrorChunk, isStreamChunk, } from '@lushly-dev/afd-core';
9
+ import { toCommandError } from './client-errors.js';
10
+ import { readSseEvents, SseEventTooLargeError } from './sse-parser.js';
11
+ /**
12
+ * The `/stream/<command>` URL for a server URL. A trailing `/sse`, `/message` or `/messages` is
13
+ * replaced and any other base path is kept, so `http://host/api/mcp/sse` streams from
14
+ * `http://host/api/mcp/stream/<command>` (the same rule as the Python client).
15
+ */
16
+ export function deriveStreamUrl(serverUrl, commandName) {
17
+ const url = new URL(serverUrl);
18
+ const base = url.pathname.replace(/\/+$/, '').replace(/\/(?:sse|messages?)$/, '');
19
+ url.pathname = `${base}/stream/${encodeURIComponent(commandName)}`;
20
+ url.search = '';
21
+ url.hash = '';
22
+ return url.toString();
23
+ }
24
+ /** A client-made terminal error chunk. */
25
+ export function streamErrorChunk(error, chunksBeforeError, recoverable = false) {
26
+ return { type: 'error', error, chunksBeforeError, recoverable };
27
+ }
28
+ function abortChunk(state, timeoutMs, chunks) {
29
+ if (state.timedOut) {
30
+ return streamErrorChunk({
31
+ code: 'STREAM_TIMEOUT',
32
+ message: `Stream did not finish within ${timeoutMs}ms`,
33
+ suggestion: 'Retry with a larger timeout. The command may still have run, so check its effect before retrying a mutation.',
34
+ retryable: true,
35
+ }, chunks);
36
+ }
37
+ const byCaller = state.callerSignal?.aborted === true;
38
+ const reason = state.controller.signal.reason;
39
+ return streamErrorChunk({
40
+ code: 'STREAM_CANCELLED',
41
+ message: byCaller
42
+ ? 'Stream was cancelled by the caller'
43
+ : reason instanceof Error
44
+ ? `Stream was cancelled: ${reason.message}`
45
+ : 'Stream was cancelled',
46
+ suggestion: byCaller
47
+ ? 'The request was aborted by the client'
48
+ : 'Reconnect the client and start the stream again if the result is still needed',
49
+ }, chunks);
50
+ }
51
+ const TRUNCATED = {
52
+ code: 'STREAM_TRUNCATED',
53
+ message: 'The stream ended without a complete or error chunk',
54
+ suggestion: 'The connection closed before the command reported its result. Check whether the command took effect before running it again.',
55
+ retryable: false,
56
+ };
57
+ async function httpFailure(response) {
58
+ let body;
59
+ try {
60
+ body = await response.json();
61
+ }
62
+ catch {
63
+ body = undefined;
64
+ }
65
+ if (typeof body === 'object' && body !== null && 'error' in body && isCommandError(body.error)) {
66
+ return body.error;
67
+ }
68
+ return {
69
+ code: 'STREAM_ERROR',
70
+ message: `HTTP ${response.status}: ${response.statusText}`,
71
+ suggestion: 'Check the command name and arguments, and that the server supports streaming',
72
+ retryable: response.status >= 500,
73
+ };
74
+ }
75
+ function postStream(request, sessionId) {
76
+ return fetch(request.url, {
77
+ method: 'POST',
78
+ headers: {
79
+ 'Content-Type': 'application/json',
80
+ Accept: 'text/event-stream',
81
+ ...request.headers,
82
+ ...(sessionId ? { 'Mcp-Session-Id': sessionId } : {}),
83
+ },
84
+ body: JSON.stringify(request.args ?? {}),
85
+ signal: request.signal,
86
+ });
87
+ }
88
+ /**
89
+ * POST the stream request in the client's session. A 404 to a request that carried a session
90
+ * means the server expired or forgot it: renew the session and retry once, as `/message`
91
+ * requests do. The server ran nothing for the rejected request.
92
+ */
93
+ async function openStream(request) {
94
+ const sessionId = request.session?.sessionId;
95
+ const response = await postStream(request, sessionId);
96
+ if (response.status !== 404 || !sessionId)
97
+ return response;
98
+ if (!(await request.session?.renewSession?.(request.signal)))
99
+ return response;
100
+ await response.body?.cancel();
101
+ return postStream(request, request.session?.sessionId);
102
+ }
103
+ /**
104
+ * Stream a command from an AFD server's `/stream/<command>` endpoint.
105
+ */
106
+ export async function* streamOverHttp(request) {
107
+ let reader;
108
+ let chunks = 0;
109
+ try {
110
+ const response = await openStream(request);
111
+ if (!response.ok) {
112
+ yield streamErrorChunk(await httpFailure(response), 0);
113
+ return;
114
+ }
115
+ reader = response.body?.getReader();
116
+ if (!reader) {
117
+ yield streamErrorChunk({
118
+ code: 'STREAM_ERROR',
119
+ message: 'Response body is not readable',
120
+ suggestion: 'The server does not support streaming',
121
+ }, 0);
122
+ return;
123
+ }
124
+ for await (const event of readSseEvents(reader, request.maxEventSize)) {
125
+ if (event.data === '[DONE]')
126
+ break;
127
+ let chunk;
128
+ try {
129
+ chunk = JSON.parse(event.data);
130
+ }
131
+ catch {
132
+ request.debug('Malformed stream chunk:', event.data);
133
+ continue;
134
+ }
135
+ if (!isStreamChunk(chunk)) {
136
+ request.debug('Ignoring a stream event that is not a chunk:', event.data);
137
+ continue;
138
+ }
139
+ const typed = chunk;
140
+ yield typed;
141
+ if (isCompleteChunk(typed) || isErrorChunk(typed))
142
+ return;
143
+ chunks++;
144
+ }
145
+ yield request.signal.aborted
146
+ ? abortChunk(request.abort, request.timeoutMs, chunks)
147
+ : streamErrorChunk(TRUNCATED, chunks);
148
+ }
149
+ catch (error) {
150
+ if (request.signal.aborted) {
151
+ yield abortChunk(request.abort, request.timeoutMs, chunks);
152
+ }
153
+ else if (error instanceof SseEventTooLargeError) {
154
+ yield streamErrorChunk({
155
+ code: 'STREAM_EVENT_TOO_LARGE',
156
+ message: error.message,
157
+ suggestion: 'Have the command emit smaller chunks, or raise maxStreamEventSize in the client config',
158
+ retryable: false,
159
+ }, chunks);
160
+ }
161
+ else {
162
+ yield streamErrorChunk(toCommandError(error), chunks, true);
163
+ }
164
+ }
165
+ finally {
166
+ if (reader) {
167
+ try {
168
+ await reader.cancel();
169
+ }
170
+ catch {
171
+ // The underlying fetch may already have released the reader.
172
+ }
173
+ reader.releaseLock();
174
+ }
175
+ }
176
+ }
177
+ /**
178
+ * Stream a command in process through a registry, with the stream semantics of core's
179
+ * `executeStream()`.
180
+ */
181
+ export async function* streamDirect(registry, name, args, signal, abort, timeoutMs) {
182
+ let chunks = 0;
183
+ for await (const chunk of executeStream(name, args ?? {}, (command, input, context) => registry.execute(command, input, context), { signal })) {
184
+ if (isErrorChunk(chunk) && chunk.error.code === 'STREAM_ABORTED' && signal.aborted) {
185
+ yield abortChunk(abort, timeoutMs, chunks);
186
+ return;
187
+ }
188
+ yield chunk;
189
+ chunks++;
190
+ }
191
+ }
192
+ //# sourceMappingURL=mcp-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-stream.js","sourceRoot":"","sources":["../src/mcp-stream.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EACN,aAAa,EACb,cAAc,EACd,eAAe,EACf,YAAY,EACZ,aAAa,GACb,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAEvE;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,SAAiB,EAAE,WAAmB;IACrE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,SAAS,C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atchResult, CommandError, CommandResult, McpToolCallResult, PipelineRequest, PipelineResult } from '@lushly-dev/afd-core';
2
+ import { isBatchResult, isPipelineResult } from '@lushly-dev/afd-core';
3
+ export declare function getTextContent(result: McpToolCallResult): string;
4
+ export declare function parseTextContent(result: McpToolCallResult): unknown;
5
+ export declare function isCommandResult(value: unknown): value is CommandResult;
6
+ export declare function createBatchFailure<T>(commands: BatchCommand[], startedAt: string, error: CommandError, reasoning: string): BatchResult<T>;
7
+ /**
8
+ * The error for a batch or pipeline whose request got no result: it timed out or the connection
9
+ * failed after the request may have reached the server, so some or all commands may have run.
10
+ *
11
+ * @param cause - The request error, already converted with `toCommandError()`
12
+ */
13
+ export declare function outcomeUnknownError(cause: CommandError, operation: 'batch' | 'pipeline'): CommandError;
14
+ /**
15
+ * A failed batch whose outcome is unknown. It reports no per-command statuses: `results` is
16
+ * empty and every summary count except `total` is zero, because no command is known to have
17
+ * failed or succeeded.
18
+ */
19
+ export declare function createUnknownOutcomeBatch<T>(commands: BatchCommand[], startedAt: string, error: CommandError): BatchResult<T>;
20
+ /**
21
+ * A pipeline whose outcome is unknown. Like core's rejected pipelines it carries the error on a
22
+ * single pipeline-level entry (`index: -1`) instead of inventing a status for each step.
23
+ */
24
+ export declare function createUnknownOutcomePipeline<T>(request: PipelineRequest, error: CommandError): PipelineResult<T>;
25
+ export declare function createPipelineFailure<T>(request: PipelineRequest, error?: CommandError): PipelineResult<T>;
26
+ export { isBatchResult, isPipelineResult };
27
+ //# sourceMappingURL=result-parsing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-parsing.d.ts","sourceRoot":"","sources":["../src/result-parsing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAEvE,wBAAgB,cAAc,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAKhE;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAOnE;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAOtE;AAED,wBAAgB,kBAAkB,CAAC,CAAC,EACnC,QAAQ,EAAE,YAAY,EAAE,EACxB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,MAAM,GACf,WAAW,CAAC,CAAC,CAAC,CAoBhB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,OAAO,GAAG,UAAU,GAC7B,YAAY,CAQd;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,EAC1C,QAAQ,EAAE,YAAY,EAAE,EACxB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,YAAY,GACjB,WAAW,CAAC,CAAC,CAAC,CAKhB;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAAC,CAAC,EAC7C,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,YAAY,GACjB,cAAc,CAAC,CAAC,CAAC,CAKnB;AAED,wBAAgB,qBAAqB,CAAC,CAAC,EACtC,OAAO,EAAE,eAAe,EACxB,KAAK,CAAC,EAAE,YAAY,GAClB,cAAc,CAAC,CAAC,CAAC,CAyBnB;AAED,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1,107 @@
1
+ import { isBatchResult, isPipelineResult } from '@lushly-dev/afd-core';
2
+ export function getTextContent(result) {
3
+ return result.content
4
+ .filter((content) => content.type === 'text')
5
+ .map((content) => content.text)
6
+ .join('');
7
+ }
8
+ export function parseTextContent(result) {
9
+ const text = getTextContent(result);
10
+ try {
11
+ return JSON.parse(text);
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ }
17
+ export function isCommandResult(value) {
18
+ return (typeof value === 'object' &&
19
+ value !== null &&
20
+ 'success' in value &&
21
+ typeof value.success === 'boolean');
22
+ }
23
+ export function createBatchFailure(commands, startedAt, error, reasoning) {
24
+ return {
25
+ success: false,
26
+ results: [],
27
+ summary: {
28
+ total: commands.length,
29
+ successCount: 0,
30
+ failureCount: commands.length,
31
+ skippedCount: 0,
32
+ },
33
+ timing: {
34
+ startedAt,
35
+ completedAt: new Date().toISOString(),
36
+ totalMs: 0,
37
+ averageMs: 0,
38
+ },
39
+ confidence: 0,
40
+ reasoning,
41
+ error,
42
+ };
43
+ }
44
+ /**
45
+ * The error for a batch or pipeline whose request got no result: it timed out or the connection
46
+ * failed after the request may have reached the server, so some or all commands may have run.
47
+ *
48
+ * @param cause - The request error, already converted with `toCommandError()`
49
+ */
50
+ export function outcomeUnknownError(cause, operation) {
51
+ return {
52
+ code: 'OUTCOME_UNKNOWN',
53
+ message: `No ${operation} result was received (${cause.message}). The server may have run some or all of its commands.`,
54
+ suggestion: `Check the effect of each command before retrying: running the ${operation} again can repeat writes that already happened.`,
55
+ retryable: false,
56
+ details: { cause: cause.code, ...cause.details },
57
+ };
58
+ }
59
+ /**
60
+ * A failed batch whose outcome is unknown. It reports no per-command statuses: `results` is
61
+ * empty and every summary count except `total` is zero, because no command is known to have
62
+ * failed or succeeded.
63
+ */
64
+ export function createUnknownOutcomeBatch(commands, startedAt, error) {
65
+ return {
66
+ ...createBatchFailure(commands, startedAt, error, error.message),
67
+ summary: { total: commands.length, successCount: 0, failureCount: 0, skippedCount: 0 },
68
+ };
69
+ }
70
+ /**
71
+ * A pipeline whose outcome is unknown. Like core's rejected pipelines it carries the error on a
72
+ * single pipeline-level entry (`index: -1`) instead of inventing a status for each step.
73
+ */
74
+ export function createUnknownOutcomePipeline(request, error) {
75
+ return {
76
+ ...createPipelineFailure(request),
77
+ steps: [{ index: -1, command: '', status: 'failure', error, executionTimeMs: 0 }],
78
+ };
79
+ }
80
+ export function createPipelineFailure(request, error) {
81
+ return {
82
+ data: undefined,
83
+ metadata: {
84
+ confidence: 0,
85
+ confidenceBreakdown: [],
86
+ reasoning: [],
87
+ warnings: [],
88
+ sources: [],
89
+ alternatives: [],
90
+ executionTimeMs: 0,
91
+ completedSteps: 0,
92
+ totalSteps: request.steps.length,
93
+ },
94
+ steps: error
95
+ ? request.steps.map((step, index) => ({
96
+ index,
97
+ alias: step.as,
98
+ command: step.command,
99
+ status: 'failure',
100
+ error,
101
+ executionTimeMs: 0,
102
+ }))
103
+ : [],
104
+ };
105
+ }
106
+ export { isBatchResult, isPipelineResult };
107
+ //# sourceMappingURL=result-parsing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-parsing.js","sourceRoot":"","sources":["../src/result-parsing.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAEvE,MAAM,UAAU,cAAc,CAAC,MAAyB;IACvD,OAAO,MAAM,CAAC,OAAO;SACnB,MAAM,CAAC,CAAC,OAAO,EAA6C,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC;SACvF,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;SAC9B,IAAI,CAAC,EAAE,CAAC,CAAC;AACZ,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAyB;IACzD,MAAM,IAAI,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;IACpC,IAAI,CAAC;QACJ,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAc;IAC7C,OAAO,CACN,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,SAAS,IAAI,KAAK;QAClB,OAAO,KAAK,CAAC,O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U,4BAA4B,CAC3C,OAAwB,EACxB,KAAmB;IAEnB,OAAO;QACN,GAAG,qBAAqB,CAAI,OAAO,CAAC;QACpC,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,EAAE,CAAC;KACjF,CAAC;AACH,CAAC;AAED,MAAM,UAAU,qBAAqB,CACpC,OAAwB,EACxB,KAAoB;IAEpB,OAAO;QACN,IAAI,EAAE,SAAc;QACpB,QAAQ,EAAE;YACT,UAAU,EAAE,CAAC;YACb,mBAAmB,EAAE,EAAE;YACvB,SAAS,EAAE,EAAE;YACb,QAAQ,EAAE,EAAE;YACZ,OAAO,EAAE,EAAE;YACX,YAAY,EAAE,EAAE;YAChB,eAAe,EAAE,CAAC;YAClB,cAAc,EAAE,CAAC;YACjB,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,MAAM;SAChC;QACD,KAAK,EAAE,KAAK;YACX,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;gBACpC,KAAK;gBACL,KAAK,EAAE,IAAI,CAAC,EAAE;gBACd,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,MAAM,EAAE,SAAkB;gBAC1B,KAAK;gBACL,eAAe,EAAE,CAAC;aAClB,CAAC,CAAC;YACJ,CAAC,CAAC,EAAE;KACL,CAAC;AACH,CAAC;AAED,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @fileoverview Server-Sent Events parser shared by `McpClient.stream()` and the SSE handoff handler.
3
+ *
4
+ * Follows the WHATWG event-stream format: lines end in CRLF, LF or CR; a line starting with `:`
5
+ * is a comment; `field:value` drops one leading space from the value (`data:x` and `data: x` are
6
+ * the same); several `data` lines join with `\n`; a blank line dispatches the event. An event that
7
+ * the stream ends before its blank line is discarded, as the spec requires.
8
+ *
9
+ * Input is scanned once, so the cost is linear in the stream size, and one event (its data lines
10
+ * plus the line being read) is bounded by `maxEventSize` characters.
11
+ */
12
+ /** Default bound for one event: 1 MiB of characters. */
13
+ export declare const DEFAULT_MAX_SSE_EVENT_SIZE: number;
14
+ /** One dispatched server-sent event. */
15
+ export interface SseEvent {
16
+ /** The `event` field, or `'message'` when the event had none. */
17
+ event: string;
18
+ /** The `data` lines joined with `\n`. */
19
+ data: string;
20
+ /** The last `id` field seen on the stream, if any. */
21
+ id?: string;
22
+ }
23
+ /** Thrown when one event grows beyond the parser's `maxEventSize`. */
24
+ export declare class SseEventTooLargeError extends Error {
25
+ readonly limit: number;
26
+ constructor(limit: number);
27
+ }
28
+ /**
29
+ * Incremental event-stream parser. Feed decoded text with `feed()` (or `push()`); it yields the
30
+ * events that text completed.
31
+ */
32
+ export declare class SseParser {
33
+ private readonly maxEventSize;
34
+ private lineParts;
35
+ private lineLength;
36
+ private dataLines;
37
+ private dataLength;
38
+ private eventType;
39
+ private lastEventId;
40
+ /** The previous chunk ended in CR, so a leading LF in the next chunk belongs to it. */
41
+ private pendingCr;
42
+ constructor(maxEventSize?: number);
43
+ /**
44
+ * Parse the next piece of the stream, returning the events it completed.
45
+ *
46
+ * @throws SseEventTooLargeError when the current event exceeds `maxEventSize`
47
+ */
48
+ push(text: string): SseEvent[];
49
+ /**
50
+ * Parse the next piece of the stream, yielding each event as soon as it is complete, so the
51
+ * events before an oversized one are delivered before the error.
52
+ *
53
+ * @throws SseEventTooLargeError when the current event exceeds `maxEventSize`
54
+ */
55
+ feed(text: string): Generator<SseEvent, void, unknown>;
56
+ private appendToLine;
57
+ private takeLine;
58
+ /** Apply one line; a blank line returns the event it completes, if any. */
59
+ private processLine;
60
+ private dispatch;
61
+ }
62
+ /**
63
+ * Read a byte stream as server-sent events.
64
+ *
65
+ * @param reader - Reader of the response body
66
+ * @param maxEventSize - Bound for one event in characters
67
+ * @throws SseEventTooLargeError when an event exceeds `maxEventSize`
68
+ */
69
+ export declare function readSseEvents(reader: ReadableStreamDefaultReader<Uint8Array>, maxEventSize?: number): AsyncGenerator<SseEvent, void, unknown>;
70
+ //# sourceMappingURL=sse-parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse-parser.d.ts","sourceRoot":"","sources":["../src/sse-parser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,wDAAwD;AACxD,eAAO,MAAM,0BAA0B,QAAc,CAAC;AAEtD,wCAAwC;AACxC,MAAM,WAAW,QAAQ;IACxB,iEAAiE;IACjE,KAAK,EAAE,MAAM,CAAC;IACd,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,sDAAsD;IACtD,EAAE,CAAC,EAAE,MAAM,CAAC;CACZ;AAED,sEAAsE;AACtE,qBAAa,qBAAsB,SAAQ,KAAK;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM;gBAAb,KAAK,EAAE,MAAM;CAIlC;AAKD;;;GAGG;AACH,qBAAa,SAAS;IAUT,OAAO,CAAC,QAAQ,CAAC,YAAY;IATzC,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,SAAS,CAAM;IACvB,OAAO,CAAC,WAAW,CAAqB;IACxC,uFAAuF;IACvF,OAAO,CAAC,SAAS,CAAS;gBAEG,YAAY,SAA6B;IAEtE;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,EAAE;IAI9B;;;;;OAKG;IACF,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC;IAqBvD,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,QAAQ;IAOhB,2EAA2E;IAC3E,OAAO,CAAC,WAAW;IA2BnB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