@lushly-dev/afd-client 2.5.0 → 3.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 (47) hide show
  1. package/README.md +31 -2
  2. package/dist/client.d.ts +25 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +189 -5
  5. package/dist/client.js.map +1 -1
  6. package/dist/direct-approval.d.ts +12 -4
  7. package/dist/direct-approval.d.ts.map +1 -1
  8. package/dist/direct-approval.js +23 -6
  9. package/dist/direct-approval.js.map +1 -1
  10. package/dist/direct-timeout.d.ts.map +1 -1
  11. package/dist/direct-timeout.js +1 -0
  12. package/dist/direct-timeout.js.map +1 -1
  13. package/dist/direct-transport.d.ts.map +1 -1
  14. package/dist/direct-transport.js +16 -6
  15. package/dist/direct-transport.js.map +1 -1
  16. package/dist/direct-types.d.ts +36 -9
  17. package/dist/direct-types.d.ts.map +1 -1
  18. package/dist/direct.d.ts +7 -9
  19. package/dist/direct.d.ts.map +1 -1
  20. package/dist/direct.js +26 -13
  21. package/dist/direct.js.map +1 -1
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/result-parsing.d.ts +7 -0
  27. package/dist/result-parsing.d.ts.map +1 -1
  28. package/dist/result-parsing.js +24 -1
  29. package/dist/result-parsing.js.map +1 -1
  30. package/dist/result-state.d.ts +98 -0
  31. package/dist/result-state.d.ts.map +1 -0
  32. package/dist/result-state.js +91 -0
  33. package/dist/result-state.js.map +1 -0
  34. package/dist/streamable-http-transport.d.ts +18 -3
  35. package/dist/streamable-http-transport.d.ts.map +1 -1
  36. package/dist/streamable-http-transport.js +249 -5
  37. package/dist/streamable-http-transport.js.map +1 -1
  38. package/dist/streamable-http.d.ts +1 -1
  39. package/dist/streamable-http.d.ts.map +1 -1
  40. package/dist/streamable-http.js.map +1 -1
  41. package/dist/types.d.ts +8 -2
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/unknown-tool.d.ts +13 -4
  44. package/dist/unknown-tool.d.ts.map +1 -1
  45. package/dist/unknown-tool.js +1 -1
  46. package/dist/unknown-tool.js.map +1 -1
  47. package/package.json +4 -4
@@ -1,4 +1,4 @@
1
- import { isBatchResult, isPipelineResult } from '@lushly-dev/afd-core';
1
+ import { isBatchResult, isCommandError, isPipelineResult, withReadableRecovery, } from '@lushly-dev/afd-core';
2
2
  export function getTextContent(result) {
3
3
  return result.content
4
4
  .filter((content) => content.type === 'text')
@@ -114,4 +114,27 @@ export function createPipelineFailure(request, error) {
114
114
  };
115
115
  }
116
116
  export { isBatchResult, isPipelineResult };
117
+ /**
118
+ * A result as `spec/recovery.md` rule 7 says a reader sees it: every error's `recovery` that does
119
+ * not match the schema is dropped, on the result, on each batch item and on each pipeline step,
120
+ * and the rest of each error is kept. The wire is untrusted, so a `recovery` an agent may follow
121
+ * passes the same check as one built in code.
122
+ */
123
+ export function withReadableRecoveries(result) {
124
+ if (typeof result !== 'object' || result === null)
125
+ return result;
126
+ const record = result;
127
+ const read = (value) => (isCommandError(value) ? withReadableRecovery(value) : value);
128
+ const items = (list) => Array.isArray(list)
129
+ ? list.map((item) => typeof item === 'object' && item !== null && 'error' in item
130
+ ? { ...item, error: read(item.error) }
131
+ : item)
132
+ : list;
133
+ return {
134
+ ...record,
135
+ ...('error' in record ? { error: read(record.error) } : {}),
136
+ ...('results' in record ? { results: items(record.results) } : {}),
137
+ ...('steps' in record ? { steps: items(record.steps) } : {}),
138
+ };
139
+ }
117
140
  //# sourceMappingURL=result-parsing.js.map
@@ -1 +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,CA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,CAAC,SAAS,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClE,GAAG,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvD,CAAC;AACR,CAAC"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @fileoverview Browser-safe result-state normalisation for AFD command results.
3
+ *
4
+ * Turns a `CommandResult<T>` (or pending `null`/`undefined`) into a discriminated
5
+ * view-model state (`loading`, `ready`, `empty`, or `error`) without dropping any
6
+ * `CommandResult` field (`confidence`, `reasoning`, `sources`, `plan`, `alternatives`,
7
+ * `warnings`, `suggestions`, `metadata`, `undoCommand`, `undoArgs`, or `result`).
8
+ *
9
+ * Module-graph rule: type-only imports only so `@lushly-dev/afd-client/direct` stays
10
+ * browser-safe and within its minified bundle budget.
11
+ */
12
+ import type { CommandError, CommandResult } from '@lushly-dev/afd-core';
13
+ import type { UnknownToolFailureResult } from './unknown-tool.js';
14
+ /**
15
+ * UX, metadata, and undo fields preserved from `CommandResult<T>` across every settled state.
16
+ */
17
+ export type ResultEnvelopeFields<T = unknown> = Pick<CommandResult<T>, 'confidence' | 'reasoning' | 'sources' | 'plan' | 'alternatives' | 'warnings' | 'suggestions' | 'metadata' | 'undoCommand' | 'undoArgs'>;
18
+ /** Pending state before a command result settles. */
19
+ export interface LoadingResultState<T = unknown> {
20
+ readonly status: 'loading';
21
+ /** Previous settled state when refreshing in place, if supplied. */
22
+ readonly previous?: SettledResultState<T>;
23
+ }
24
+ /** Settled success state with non-empty data. */
25
+ export interface ReadyResultState<T = unknown> extends ResultEnvelopeFields<T> {
26
+ readonly status: 'ready';
27
+ readonly data: T;
28
+ readonly result: CommandResult<T>;
29
+ }
30
+ /** Settled success state whose data is empty (`null`, `undefined`, `[]`, or `isEmpty() === true`). */
31
+ export interface EmptyResultState<T = unknown> extends ResultEnvelopeFields<T> {
32
+ readonly status: 'empty';
33
+ readonly data: T | undefined;
34
+ readonly result: CommandResult<T>;
35
+ }
36
+ /** Settled failure state with normalised error fields and all preserved result metadata. */
37
+ export interface ErrorResultState<T = unknown> extends ResultEnvelopeFields<T> {
38
+ readonly status: 'error';
39
+ /** Machine-readable error code (`'UNKNOWN_ERROR'` if absent on a malformed failure). */
40
+ readonly code: string;
41
+ /** Human-readable error message (`'Command failed'` if absent on a malformed failure). */
42
+ readonly message: string;
43
+ /** Actionable recovery suggestion from `error.suggestion`, when non-empty. */
44
+ readonly suggestion?: string;
45
+ /** Whether retrying the same request may succeed (`false` when unset). */
46
+ readonly retryable: boolean;
47
+ /** Structured technical details from `error.details`, when present. */
48
+ readonly details?: Record<string, unknown>;
49
+ /** Underlying enumerable cause from `error.cause`, when present. */
50
+ readonly cause?: CommandError['cause'];
51
+ /** Original `CommandError` from `result.error`, when present. */
52
+ readonly error?: CommandError;
53
+ /** Optional data payload carried on a failure (for example, `UnknownToolError`). */
54
+ readonly data?: unknown;
55
+ readonly result: CommandResult<T> | UnknownToolFailureResult;
56
+ }
57
+ /** Any settled state produced from a `CommandResult<T>`. */
58
+ export type SettledResultState<T = unknown> = ReadyResultState<T> | EmptyResultState<T> | ErrorResultState<T>;
59
+ /** Discriminated UI state produced by {@link normalizeResultState} and {@link loadingResultState}. */
60
+ export type NormalizedResultState<T = unknown> = LoadingResultState<T> | SettledResultState<T>;
61
+ /** Status discriminant of {@link NormalizedResultState}. */
62
+ export type ResultStateStatus = NormalizedResultState['status'];
63
+ /** Options for {@link normalizeResultState}. */
64
+ export interface NormalizeResultOptions<T = unknown> {
65
+ /**
66
+ * Custom predicate deciding whether a successful result represents an empty state.
67
+ * Defaults to `data === undefined || data === null || (Array.isArray(data) && data.length === 0)`.
68
+ * For enveloped lists (such as `{ items: T[], total: number }`), pass
69
+ * `{ isEmpty: (data) => !data || data.items.length === 0 }`.
70
+ *
71
+ * Because a custom predicate may classify `data: undefined` as `'ready'`, passing `isEmpty`
72
+ * widens the returned state's `T` to `T | undefined`.
73
+ */
74
+ isEmpty?: (data: T | undefined, result: CommandResult<T>) => boolean;
75
+ /** Previous settled state carried when `result` is `null` or `undefined`. */
76
+ previous?: SettledResultState<T | undefined>;
77
+ }
78
+ /**
79
+ * Create a `'loading'` result state, optionally preserving the previous settled state
80
+ * for in-place refresh UIs.
81
+ */
82
+ export declare function loadingResultState<T = unknown>(previous?: SettledResultState<T>): LoadingResultState<T>;
83
+ /**
84
+ * Normalise a `CommandResult<T>` (including `DirectClient.call<T>()` results, or pending
85
+ * `null`/`undefined`) into a discriminated `loading`, `ready`, `empty`, or `error` state
86
+ * while preserving every `CommandResult` field.
87
+ */
88
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult, options?: {
89
+ previous?: SettledResultState<T>;
90
+ isEmpty?: undefined;
91
+ }): SettledResultState<T>;
92
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult, options: NormalizeResultOptions<T>): SettledResultState<T | undefined>;
93
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult | null | undefined, options?: {
94
+ previous?: SettledResultState<T>;
95
+ isEmpty?: undefined;
96
+ }): NormalizedResultState<T>;
97
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult | null | undefined, options: NormalizeResultOptions<T>): NormalizedResultState<T | undefined>;
98
+ //# sourceMappingURL=result-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-state.d.ts","sourceRoot":"","sources":["../src/result-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAElE;;GAEG;AACH,MAA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AO,EAC7C,QAAQ,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAC9B,kBAAkB,CAAC,CAAC,CAAC,CAEvB;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EACrC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,wBAAwB,EACnD,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,CAAA;CAAE,GACjE,kBAAkB,CAAC,CAAC,CAAC,CAAC;AACzB,wBAAgB,oBAAoB,CAAC,CAAC,EACrC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,wBAAwB,EACnD,OAAO,EAAE,sBAAsB,CAAC,CAAC,CAAC,GAChC,kBAAkB,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;AACrC,wBAAgB,oBAAoB,CAAC,CAAC,EACrC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,wBAAwB,GAAG,IAAI,GAAG,SAAS,EACtE,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,CAAA;CAAE,GACjE,qBAAqB,CAAC,CAAC,CAAC,CAAC;AAC5B,wBAAgB,oBAAoB,CAAC,CAAC,EACrC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,wBAAwB,GAAG,IAAI,GAAG,SAAS,EACtE,OAAO,EAAE,sBAAsB,CAAC,CAAC,CAAC,GAChC,qBAAqB,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC"}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @fileoverview Browser-safe result-state normalisation for AFD command results.
3
+ *
4
+ * Turns a `CommandResult<T>` (or pending `null`/`undefined`) into a discriminated
5
+ * view-model state (`loading`, `ready`, `empty`, or `error`) without dropping any
6
+ * `CommandResult` field (`confidence`, `reasoning`, `sources`, `plan`, `alternatives`,
7
+ * `warnings`, `suggestions`, `metadata`, `undoCommand`, `undoArgs`, or `result`).
8
+ *
9
+ * Module-graph rule: type-only imports only so `@lushly-dev/afd-client/direct` stays
10
+ * browser-safe and within its minified bundle budget.
11
+ */
12
+ const DEFAULT_ERROR_CODE = 'UNKNOWN_ERROR';
13
+ const DEFAULT_ERROR_MESSAGE = 'Command failed';
14
+ function defaultIsEmpty(data) {
15
+ return data === undefined || data === null || (Array.isArray(data) && data.length === 0);
16
+ }
17
+ function extractEnvelopeFields(result) {
18
+ return {
19
+ ...(result.confidence !== undefined && { confidence: result.confidence }),
20
+ ...(result.reasoning !== undefined && { reasoning: result.reasoning }),
21
+ ...(result.sources !== undefined && { sources: result.sources }),
22
+ ...(result.plan !== undefined && { plan: result.plan }),
23
+ ...(result.alternatives !== undefined && { alternatives: result.alternatives }),
24
+ ...(result.warnings !== undefined && { warnings: result.warnings }),
25
+ ...(result.suggestions !== undefined && { suggestions: result.suggestions }),
26
+ ...(result.metadata !== undefined && { metadata: result.metadata }),
27
+ ...(result.undoCommand !== undefined && { undoCommand: result.undoCommand }),
28
+ ...(result.undoArgs !== undefined && { undoArgs: result.undoArgs }),
29
+ };
30
+ }
31
+ /**
32
+ * Create a `'loading'` result state, optionally preserving the previous settled state
33
+ * for in-place refresh UIs.
34
+ */
35
+ export function loadingResultState(previous) {
36
+ return previous !== undefined ? { status: 'loading', previous } : { status: 'loading' };
37
+ }
38
+ export function normalizeResultState(result, options) {
39
+ if (result === null || result === undefined) {
40
+ return loadingResultState(options?.previous);
41
+ }
42
+ const envelope = extractEnvelopeFields(result);
43
+ if (result.success !== true) {
44
+ const rawError = result.error;
45
+ const errorObj = typeof rawError === 'object' && rawError !== null ? rawError : undefined;
46
+ const code = typeof errorObj?.code === 'string' && errorObj.code.trim().length > 0
47
+ ? errorObj.code
48
+ : DEFAULT_ERROR_CODE;
49
+ const message = typeof errorObj?.message === 'string' && errorObj.message.trim().length > 0
50
+ ? errorObj.message
51
+ : DEFAULT_ERROR_MESSAGE;
52
+ const suggestion = typeof errorObj?.suggestion === 'string' && errorObj.suggestion.trim().length > 0
53
+ ? errorObj.suggestion
54
+ : undefined;
55
+ const hasEnumerableCause = errorObj !== undefined &&
56
+ Object.prototype.propertyIsEnumerable.call(errorObj, 'cause') &&
57
+ errorObj.cause !== undefined;
58
+ return {
59
+ status: 'error',
60
+ code,
61
+ message,
62
+ ...(suggestion !== undefined && { suggestion }),
63
+ retryable: errorObj?.retryable === true,
64
+ ...(errorObj?.details !== undefined && { details: errorObj.details }),
65
+ ...(hasEnumerableCause && { cause: errorObj.cause }),
66
+ ...(errorObj !== undefined && { error: errorObj }),
67
+ ...(result.data !== undefined && { data: result.data }),
68
+ ...envelope,
69
+ result,
70
+ };
71
+ }
72
+ const successResult = result;
73
+ const isEmpty = options?.isEmpty
74
+ ? options.isEmpty(successResult.data, successResult)
75
+ : defaultIsEmpty(successResult.data);
76
+ if (isEmpty) {
77
+ return {
78
+ status: 'empty',
79
+ data: successResult.data,
80
+ ...envelope,
81
+ result: successResult,
82
+ };
83
+ }
84
+ return {
85
+ status: 'ready',
86
+ data: successResult.data,
87
+ ...envelope,
88
+ result: successResult,
89
+ };
90
+ }
91
+ //# sourceMappingURL=result-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-state.js","sourceRoot":"","sources":["../src/result-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AA6FH,MAAM,kBAAkB,GAAG,eAAe,CAAC;AAC3C,MAAM,qBAAqB,GAAG,gBAAgB,CAAC;AAE/C,SAAS,cAAc,CAAC,IAAa;IACpC,OAAO,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;AAC1F,CAAC;AAED,SAAS,qBAAqB,CAAI,MAAwB;IACzD,OAAO;QACN,GAA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speaks JSON-RPC to its transports, so `send()` maps the requests it makes
10
- * (`initialize`, `tools/list`, `tools/call`) onto the SDK client. `initialize` is answered
11
- * locally from what negotiation learned: there is no handshake on the modern protocol.
10
+ * (`initialize`, `tools/list`, `tools/call`, `tasks/*`, `resources/list`, `resources/read`,
11
+ * `skills/list`, `skills/get`) onto the SDK client. `initialize` is answered locally from what
12
+ * negotiation learned: there is no handshake on the modern protocol.
12
13
  */
13
- import type { McpRequest, McpResponse } from '@lushly-dev/afd-core';
14
+ import type { McpRequest, McpResponse, ServerContract } from '@lushly-dev/afd-core';
14
15
  import type { Transport } from './transport.js';
15
16
  import type { ElicitationHandler } from './types.js';
16
17
  /** How the transport negotiates the protocol revision. */
@@ -27,6 +28,13 @@ export interface StreamableHttpTransportOptions {
27
28
  onElicitation?: ElicitationHandler;
28
29
  /** Declare the MCP Tasks extension (`io.modelcontextprotocol/tasks`) on modern requests. */
29
30
  tasks?: boolean;
31
+ /**
32
+ * Send `tools/list` as a single raw JSON-RPC request without SDK auto-pagination, tool caching,
33
+ * or `outputSchema` validation on subsequent `tools/call` responses. Hosts talking to untrusted
34
+ * MCP servers (such as browser tabs) set this so an untrusted `outputSchema` cannot run on the
35
+ * main thread and pagination stays under the caller's own page cap (#713).
36
+ */
37
+ rawToolsList?: boolean;
30
38
  /**
31
39
  * The `fetch` every request goes through. A host that does not trust the server uses it to limit
32
40
  * what it reads, since the SDK reads a response whole and holds an event stream open with no deadline.
@@ -42,9 +50,16 @@ export declare class StreamableHttpTransport implements Transport {
42
50
  private errorHandler;
43
51
  private closeHandler;
44
52
  private readonly pendingTasks;
53
+ private handshakeMeta;
54
+ private serverContract;
45
55
  constructor(url: string, options: StreamableHttpTransportOptions);
46
56
  connect(signal?: AbortSignal): Promise<void>;
47
57
  disconnect(): void;
58
+ /**
59
+ * The AFD contract advertised by the server in `_meta["dev.afd/contract"]` on
60
+ * `server/discover` or `initialize` (`spec/tool-strategies.md#contract-advertisement`, #1927).
61
+ */
62
+ getServerContract(): ServerContract | undefined;
48
63
  /** The negotiated protocol revision, such as `2026-07-28` or `2025-11-25`. */
49
64
  get protocolVersion(): string | undefined;
50
65
  /** `modern` for 2026-07-28 and later, `legacy` for the `initialize` handshake. */
@@ -1 +1 @@
1
- {"version":3,"file":"streamable-http-transport.d.ts","sourceRoot":"","sources":["../src/streamable-http-transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAuB,UAAU,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAOzF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,0DAA0D;AAC1D,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE9D,kDAAkD;AAClD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AAkBpD,MAAM,WAAW,8BAA8B;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,0EAA0E;IAC1E,IAAI,CAAC,EAAE,kBAAkB,CAAC;IAC1B,2FAA2F;IAC3F,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC,4FAA4F;IAC5F,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACrB;AAyBD,qBAAa,uBAAwB,YAAW,SAAS;IASvD,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB,OAAO,CAAC,QAAQ,CAAC,OAAO;IATzB,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,cAAc,CAAkD;IACxE,OAAO,CAAC,YAAY,CAAyC;IAC7D,OAAO,CAAC,YAAY,CAA6B;I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AC,CAuG1E;IAED,WAAW,IAAI,OAAO,CAErB;IAED,SAAS,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI,CAExD;IAED,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAAG,IAAI,CAE7C;IAED,OAAO,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI,CAEjC;IAED,OAAO,CAAC,gBAAgB;CAaxB"}
@@ -7,8 +7,9 @@
7
7
  * an official MCP SDK.
8
8
  *
9
9
  * `McpClient` speaks JSON-RPC to its transports, so `send()` maps the requests it makes
10
- * (`initialize`, `tools/list`, `tools/call`) onto the SDK client. `initialize` is answered
11
- * locally from what negotiation learned: there is no handshake on the modern protocol.
10
+ * (`initialize`, `tools/list`, `tools/call`, `tasks/*`, `resources/list`, `resources/read`,
11
+ * `skills/list`, `skills/get`) onto the SDK client. `initialize` is answered locally from what
12
+ * negotiation learned: there is no handshake on the modern protocol.
12
13
  */
13
14
  import { Client, ProtocolError, StreamableHTTPClientTransport as SdkHttpTransport, } from '@modelcontextprotocol/client';
14
15
  import { raceWithAbort } from './request-abort.js';
@@ -21,6 +22,36 @@ export const MODERN_PROTOCOL_VERSION = '2026-07-28';
21
22
  const NO_SDK_TIMEOUT = 2_147_483_647;
22
23
  const TASKS_EXTENSION_ID = 'io.modelcontextprotocol/tasks';
23
24
  const TASK_SENTINEL = '__afd_mcp_task__';
25
+ const AFD_CONTRACT_META_KEY = 'dev.afd/contract';
26
+ function isPlainRecord(value) {
27
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ }
29
+ /**
30
+ * Browser-safe parser for `_meta["dev.afd/contract"]` (`spec/tool-strategies.md#contract-advertisement`,
31
+ * rules 3 and 4). Kept inline so `@lushly-dev/afd-client/streamable-http` adds no runtime dependency
32
+ * on `@lushly-dev/afd-core`.
33
+ */
34
+ function parseContractFromMeta(meta) {
35
+ if (!isPlainRecord(meta))
36
+ return undefined;
37
+ const raw = meta[AFD_CONTRACT_META_KEY];
38
+ if (!isPlainRecord(raw))
39
+ return undefined;
40
+ if (typeof raw.version !== 'string' || raw.version.length === 0)
41
+ return undefined;
42
+ if (!isPlainRecord(raw.profiles))
43
+ return undefined;
44
+ const entries = [];
45
+ for (const id of Object.keys(raw.profiles).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
46
+ const entry = raw.profiles[id];
47
+ if (!isPlainRecord(entry))
48
+ continue;
49
+ if (typeof entry.version !== 'string' || entry.version.length === 0)
50
+ continue;
51
+ entries.push([id, { version: entry.version }]);
52
+ }
53
+ return { version: raw.version, profiles: Object.fromEntries(entries) };
54
+ }
24
55
  const PASS_THROUGH_SCHEMA = {
25
56
  '~standard': {
26
57
  version: 1,
@@ -28,6 +59,140 @@ const PASS_THROUGH_SCHEMA = {
28
59
  validate: (value) => ({ value }),
29
60
  },
30
61
  };
62
+ /**
63
+ * Minimal page-envelope validator for `rawToolsList` `tools/list` responses (#713): validates
64
+ * `{ tools: unknown[], nextCursor?: string }` while keeping each tool's `outputSchema` inert.
65
+ */
66
+ const RAW_TOOLS_LIST_SCHEMA = {
67
+ '~standard': {
68
+ version: 1,
69
+ vendor: 'afd',
70
+ validate: (value) => {
71
+ if (!isPlainRecord(value) || !Array.isArray(value.tools)) {
72
+ return { issues: [{ message: 'Invalid tools/list response: expected tools array' }] };
73
+ }
74
+ if (value.nextCursor !== undefined && typeof value.nextCursor !== 'string') {
75
+ return {
76
+ issues: [{ message: 'Invalid tools/list response: nextCursor must be a string' }],
77
+ };
78
+ }
79
+ return { value };
80
+ },
81
+ },
82
+ };
83
+ const X_MCP_HEADER_KEY = 'x-mcp-header';
84
+ const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
85
+ const PERMITTED_X_MCP_HEADER_TYPES = new Set(['string', 'integer', 'boolean']);
86
+ const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [
87
+ 'items',
88
+ 'prefixItems',
89
+ 'contains',
90
+ 'additionalProperties',
91
+ 'unevaluatedProperties',
92
+ 'unevaluatedItems',
93
+ 'propertyNames',
94
+ 'patternProperties',
95
+ 'dependentSchemas',
96
+ 'oneOf',
97
+ 'anyOf',
98
+ 'allOf',
99
+ 'not',
100
+ 'if',
101
+ 'then',
102
+ 'else',
103
+ '$defs',
104
+ 'definitions',
105
+ ];
106
+ const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([
107
+ 'patternProperties',
108
+ 'dependentSchemas',
109
+ '$defs',
110
+ 'definitions',
111
+ ]);
112
+ const X_MCP_HEADER_MAX_NODES = 10_000;
113
+ /**
114
+ * SEP-2243 (protocol revision 2026-07-28): check whether a tool's `inputSchema` has only valid
115
+ * `x-mcp-header` declarations (statically reachable via `properties`, valid RFC 9110 token,
116
+ * primitive `string`/`integer`/`boolean`, case-insensitively unique). Mirrors the SDK's
117
+ * `_excludeInvalidXMcpHeaderTools` check on single raw pages (#713).
118
+ */
119
+ function hasValidXMcpHeaders(inputSchema) {
120
+ if (!isPlainRecord(inputSchema))
121
+ return true;
122
+ const seenLower = new Set();
123
+ const seenNodes = new Set();
124
+ const stack = [
125
+ { node: inputSchema, depth: 0, reachable: true },
126
+ ];
127
+ while (stack.length > 0) {
128
+ const frame = stack.pop();
129
+ if (!frame || !isPlainRecord(frame.node))
130
+ continue;
131
+ if (seenNodes.has(frame.node))
132
+ continue;
133
+ seenNodes.add(frame.node);
134
+ if (seenNodes.size > X_MCP_HEADER_MAX_NODES)
135
+ return false;
136
+ const schema = frame.node;
137
+ if (Object.hasOwn(schema, X_MCP_HEADER_KEY)) {
138
+ if (!frame.reachable || frame.depth === 0)
139
+ return false;
140
+ const raw = schema[X_MCP_HEADER_KEY];
141
+ if (typeof raw !== 'string' || raw.length === 0 || !RFC9110_TOKEN.test(raw))
142
+ return false;
143
+ if (typeof schema.type !== 'string' || !PERMITTED_X_MCP_HEADER_TYPES.has(schema.type)) {
144
+ return false;
145
+ }
146
+ const lower = raw.toLowerCase();
147
+ if (seenLower.has(lower))
148
+ return false;
149
+ seenLower.add(lower);
150
+ }
151
+ const props = schema.properties;
152
+ if (isPlainRecord(props)) {
153
+ for (const child of Object.values(props)) {
154
+ stack.push({ node: child, depth: frame.depth + 1, reachable: frame.reachable });
155
+ }
156
+ }
157
+ for (const key of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
158
+ if (!Object.hasOwn(schema, key))
159
+ continue;
160
+ const sub = schema[key];
161
+ if (sub === undefined)
162
+ continue;
163
+ const branches = Array.isArray(sub)
164
+ ? sub
165
+ : isPlainRecord(sub) && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(key)
166
+ ? Object.values(sub)
167
+ : [sub];
168
+ for (const branch of branches) {
169
+ stack.push({ node: branch, depth: frame.depth + 1, reachable: false });
170
+ }
171
+ }
172
+ }
173
+ return true;
174
+ }
175
+ function excludeInvalidXMcpHeaderTools(page) {
176
+ const filtered = page.tools.filter((tool) => {
177
+ if (!isPlainRecord(tool))
178
+ return true;
179
+ return hasValidXMcpHeaders(tool.inputSchema);
180
+ });
181
+ return filtered.length === page.tools.length ? page : { ...page, tools: filtered };
182
+ }
183
+ /**
184
+ * No-op JSON Schema validator passed to the MCP SDK when `rawToolsList` is enabled so untrusted
185
+ * server `outputSchema` definitions are never compiled or evaluated on the main thread (#713).
186
+ */
187
+ const NOOP_JSON_SCHEMA_VALIDATOR = {
188
+ getValidator() {
189
+ return (input) => ({
190
+ valid: true,
191
+ data: input,
192
+ errorMessage: undefined,
193
+ });
194
+ },
195
+ };
31
196
  /**
32
197
  * The tool result for an `input_required` answer the client cannot fulfil: an `INPUT_REQUIRED`
33
198
  * failure carrying what the server asked.
@@ -58,6 +223,8 @@ export class StreamableHttpTransport {
58
223
  errorHandler = null;
59
224
  closeHandler = null;
60
225
  pendingTasks = new Map();
226
+ handshakeMeta;
227
+ serverContract;
61
228
  constructor(url, options) {
62
229
  this.url = url;
63
230
  this.options = options;
@@ -77,6 +244,7 @@ export class StreamableHttpTransport {
77
244
  versionNegotiation: { mode: mode === 'modern' ? { pin: MODERN_PROTOCOL_VERSION } : mode },
78
245
  // Without a handler, an input_required answer is returned to `send` as is.
79
246
  ...(!onElicitation && { inputRequired: { autoFulfill: false } }),
247
+ ...(this.options.rawToolsList && { jsonSchemaValidator: NOOP_JSON_SCHEMA_VALIDATOR }),
80
248
  });
81
249
  if (onElicitation) {
82
250
  client.setRequestHandler('elicitation/create', async (request) => {
@@ -91,6 +259,35 @@ export class StreamableHttpTransport {
91
259
  ...(this.options.headers && { requestInit: { headers: this.options.headers } }),
92
260
  ...(this.options.fetch && { fetch: this.options.fetch }),
93
261
  });
262
+ // Capture handshake `_meta` on the wire before the SDK processes it: `@modelcontextprotocol/client`
263
+ // v2.4.0 discards `InitializeResult._meta` during legacy negotiation (#1927).
264
+ let capturedHandshakeMeta;
265
+ let sdkOnMessage = transport.onmessage;
266
+ Object.defineProperty(transport, 'onmessage', {
267
+ configurable: true,
268
+ enumerable: true,
269
+ get: () => sdkOnMessage,
270
+ set: (handler) => {
271
+ if (!handler) {
272
+ sdkOnMessage = handler;
273
+ return;
274
+ }
275
+ sdkOnMessage = (message) => {
276
+ const msg = message;
277
+ if (!capturedHandshakeMeta &&
278
+ msg &&
279
+ typeof msg === 'object' &&
280
+ 'result' in msg &&
281
+ isPlainRecord(msg.result) &&
282
+ isPlainRecord(msg.result._meta) &&
283
+ ('supportedVersions' in msg.result ||
284
+ ('protocolVersion' in msg.result && 'serverInfo' in msg.result))) {
285
+ capturedHandshakeMeta = msg.result._meta;
286
+ }
287
+ handler(message);
288
+ };
289
+ },
290
+ });
94
291
  client.onerror = (error) => {
95
292
  if (this.client === client)
96
293
  this.errorHandler?.(error);
@@ -99,6 +296,8 @@ export class StreamableHttpTransport {
99
296
  if (this.client !== client || !this.connected)
100
297
  return;
101
298
  this.connected = false;
299
+ this.handshakeMeta = undefined;
300
+ this.serverContract = undefined;
102
301
  this.closeHandler?.();
103
302
  };
104
303
  this.client = client;
@@ -155,6 +354,10 @@ export class StreamableHttpTransport {
155
354
  deliver?.(message);
156
355
  };
157
356
  }
357
+ const discoverMeta = client.getDiscoverResult?.()?._meta;
358
+ const resolvedHandshakeMeta = capturedHandshakeMeta ?? (isPlainRecord(discoverMeta) ? discoverMeta : undefined);
359
+ this.handshakeMeta = resolvedHandshakeMeta;
360
+ this.serverContract = parseContractFromMeta(resolvedHandshakeMeta);
158
361
  this.connected = true;
159
362
  }
160
363
  disconnect() {
@@ -162,11 +365,20 @@ export class StreamableHttpTransport {
162
365
  const wasConnected = this.connected;
163
366
  this.client = null;
164
367
  this.connected = false;
368
+ this.handshakeMeta = undefined;
369
+ this.serverContract = undefined;
165
370
  this.pendingTasks.clear();
166
371
  client?.close().catch(() => { });
167
372
  if (wasConnected)
168
373
  this.closeHandler?.();
169
374
  }
375
+ /**
376
+ * The AFD contract advertised by the server in `_meta["dev.afd/contract"]` on
377
+ * `server/discover` or `initialize` (`spec/tool-strategies.md#contract-advertisement`, #1927).
378
+ */
379
+ getServerContract() {
380
+ return this.connected ? this.serverContract : undefined;
381
+ }
170
382
  /** The negotiated protocol revision, such as `2026-07-28` or `2025-11-25`. */
171
383
  get protocolVersion() {
172
384
  return this.client?.getNegotiatedProtocolVersion();
@@ -187,13 +399,38 @@ export class StreamableHttpTransport {
187
399
  result = this.initializeResult(client);
188
400
  break;
189
401
  case 'tools/list':
190
- result = await client.listTools(request.params, options);
402
+ if (this.options.rawToolsList) {
403
+ const rawPage = (await client.request({
404
+ method: 'tools/list',
405
+ ...(request.params !== undefined && {
406
+ params: request.params,
407
+ }),
408
+ }, RAW_TOOLS_LIST_SCHEMA, options));
409
+ result =
410
+ client.getProtocolEra() === 'modern'
411
+ ? excludeInvalidXMcpHeaderTools(rawPage)
412
+ : rawPage;
413
+ }
414
+ else {
415
+ result = await client.listTools(request.params, options);
416
+ }
191
417
  break;
192
418
  case 'tools/call': {
193
- const called = (await client.callTool(request.params, {
419
+ const callOptions = {
194
420
  ...options,
195
421
  ...(!this.options.onElicitation && { allowInputRequired: true }),
196
- }));
422
+ };
423
+ // In rawToolsList mode, send tools/call directly through client.request so SDK
424
+ // callTool() neither invokes outputSchema validation nor triggers -32020
425
+ // HEADER_MISMATCH listTools() auto-pagination and caching (#713).
426
+ const called = (this.options.rawToolsList
427
+ ? await client.request({
428
+ method: 'tools/call',
429
+ ...(request.params !== undefined && {
430
+ params: request.params,
431
+ }),
432
+ }, callOptions)
433
+ : await client.callTool(request.params, callOptions));
197
434
  const taskToken = called._meta?.[TASK_SENTINEL];
198
435
  if (typeof taskToken === 'string') {
199
436
  const taskResult = this.pendingTasks.get(taskToken);
@@ -208,6 +445,12 @@ export class StreamableHttpTransport {
208
445
  case 'tasks/get':
209
446
  case 'tasks/update':
210
447
  case 'tasks/cancel':
448
+ // Resources (spec/mcp-resources.md, R3 and R4), such as an MCP Apps `ui://` view.
449
+ case 'resources/list':
450
+ case 'resources/read':
451
+ // The Skills extension (spec/mcp-resources.md, S3 and S4).
452
+ case 'skills/list':
453
+ case 'skills/get':
211
454
  result = await client.request({ method: request.method, params: request.params }, PASS_THROUGH_SCHEMA, options);
212
455
  break;
213
456
  default:
@@ -261,6 +504,7 @@ export class StreamableHttpTransport {
261
504
  version: client.getServerVersion()?.version ?? '',
262
505
  },
263
506
  ...(instructions && { instructions }),
507
+ ...(this.handshakeMeta && { _meta: this.handshakeMeta }),
264
508
  };
265
509
  }
266
510
  }