fascicle 0.13.0 → 0.14.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 (43) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +20 -1
  3. package/dist/acp.d.ts +226 -0
  4. package/dist/acp.js +1886 -0
  5. package/dist/acp.js.map +1 -0
  6. package/dist/adapters.js +1 -2
  7. package/dist/agents.d.ts +1 -1
  8. package/dist/agents.js +1 -1
  9. package/dist/{core-B-M7nAkg.js → core-CDrz0NM1.js} +184 -53
  10. package/dist/core-CDrz0NM1.js.map +1 -0
  11. package/dist/diagram_bin.js +5 -2
  12. package/dist/diagram_bin.js.map +1 -1
  13. package/dist/{engine-BRzVcTBB.js → engine-BDWB2jdn.js} +12 -333
  14. package/dist/engine-BDWB2jdn.js.map +1 -0
  15. package/dist/index.d.ts +485 -623
  16. package/dist/index.js +20 -12
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-CIdhjChw.js → invoke-tjTjZLHj.js} +3 -3
  19. package/dist/{invoke-CIdhjChw.js.map → invoke-tjTjZLHj.js.map} +1 -1
  20. package/dist/json_schema_to_standard-r21kW2LI.js +288 -0
  21. package/dist/json_schema_to_standard-r21kW2LI.js.map +1 -0
  22. package/dist/leading_system-BQe_405V.js +330 -0
  23. package/dist/leading_system-BQe_405V.js.map +1 -0
  24. package/dist/mcp.d.ts +17 -16
  25. package/dist/mcp.js +2 -266
  26. package/dist/mcp.js.map +1 -1
  27. package/dist/search-CqH5hmuF.js +563 -0
  28. package/dist/search-CqH5hmuF.js.map +1 -0
  29. package/dist/search_worker.d.ts +1 -0
  30. package/dist/search_worker.js +19 -0
  31. package/dist/search_worker.js.map +1 -0
  32. package/dist/stdio.js +1 -1
  33. package/dist/testing.d.ts +1 -1
  34. package/dist/testing.js +3 -2
  35. package/dist/testing.js.map +1 -1
  36. package/dist/{types-CZ83Q5nm.d.ts → types-C_Rmcgck.d.ts} +7 -1
  37. package/dist/viewer-app/assets/index-Fnh5HKSU.js +2 -0
  38. package/dist/viewer-app/index.html +1 -1
  39. package/dist/viewer.js +1 -1
  40. package/package.json +30 -19
  41. package/dist/core-B-M7nAkg.js.map +0 -1
  42. package/dist/engine-BRzVcTBB.js.map +0 -1
  43. package/dist/viewer-app/assets/index-DXsB0byD.js +0 -2
package/dist/mcp.js CHANGED
@@ -1,4 +1,5 @@
1
- import { E as run } from "./core-B-M7nAkg.js";
1
+ import { E as run } from "./core-CDrz0NM1.js";
2
+ import { n as as_record, r as is_record, t as json_schema_to_standard } from "./json_schema_to_standard-r21kW2LI.js";
2
3
  //#region src/mcp/errors.ts
3
4
  /**
4
5
  * Typed errors for the MCP adapter.
@@ -24,24 +25,6 @@ var mcp_error = class extends Error {
24
25
  }
25
26
  };
26
27
  //#endregion
27
- //#region src/mcp/internal.ts
28
- /**
29
- * Small shared guards for the MCP adapter. Kept in one place so the client,
30
- * schema bridge, and result mapping do not each carry a copy.
31
- */
32
- /**
33
- * Narrows a value to a plain object: non-null, `typeof` object, not an array.
34
- */
35
- function is_record(value) {
36
- return typeof value === "object" && value !== null && !Array.isArray(value);
37
- }
38
- /**
39
- * Returns the value when it is a plain object, otherwise `undefined`.
40
- */
41
- function as_record(value) {
42
- return is_record(value) ? value : void 0;
43
- }
44
- //#endregion
45
28
  //#region src/mcp/result_mapping.ts
46
29
  /**
47
30
  * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
@@ -121,253 +104,6 @@ function stringify(value) {
121
104
  }
122
105
  }
123
106
  //#endregion
124
- //#region src/mcp/schema_bridge.ts
125
- /**
126
- * Builds a `ToolSchema` over an MCP server's advertised JSON Schema.
127
- *
128
- * The advertised schema is snapshotted once, deeply, and both faces of the
129
- * returned object read that snapshot. A malformed or hostile schema degrades to
130
- * the empty schema during the snapshot rather than propagating an error, since
131
- * an arbitrary remote server's advertisement must never crash tool discovery,
132
- * and it leaves both faces describing the same thing: accept anything, emit
133
- * nothing.
134
- */
135
- function json_schema_to_standard(schema) {
136
- const advertised = snapshot(schema);
137
- return { "~standard": {
138
- version: 1,
139
- vendor: "fascicle-mcp",
140
- validate: (value) => {
141
- const issues = check(advertised, value, []);
142
- return issues.length === 0 ? { value } : { issues };
143
- },
144
- jsonSchema: {
145
- input: () => clone_schema(advertised),
146
- output: () => clone_schema(advertised)
147
- }
148
- } };
149
- }
150
- /**
151
- * Deep-copies the advertised schema, or yields the empty schema when it is not
152
- * an object or cannot be read.
153
- *
154
- * Copying here means every later read walks plain data: a schema with throwing
155
- * accessors or a cycle fails once, at discovery, instead of on some later call.
156
- */
157
- function snapshot(schema) {
158
- try {
159
- const record = as_record(schema);
160
- return record === void 0 ? {} : clone_schema(record);
161
- } catch {
162
- return {};
163
- }
164
- }
165
- /**
166
- * Deep-copies one JSON Schema node.
167
- */
168
- function clone_schema(schema) {
169
- const copy = {};
170
- for (const [key, value] of Object.entries(schema)) copy[key] = clone_value(value);
171
- return copy;
172
- }
173
- /**
174
- * Deep-copies a value inside a schema, recursing through arrays and objects and
175
- * returning every other value as is.
176
- */
177
- function clone_value(value) {
178
- if (Array.isArray(value)) return value.map(clone_value);
179
- return is_record(value) ? clone_schema(value) : value;
180
- }
181
- /**
182
- * Checks one value against one JSON Schema node, returning the issues it
183
- * violated, or an empty array when it passes.
184
- *
185
- * A node that is not an object constrains nothing and accepts, which is what
186
- * makes a construct this bridge does not model degrade rather than reject.
187
- */
188
- function check(node, value, path) {
189
- const schema = as_record(node);
190
- if (schema === void 0) return [];
191
- return check_keywords(schema, value, path) ?? check_shape(schema, value, path);
192
- }
193
- /**
194
- * Checks the keywords that stand on their own, returning `undefined` when the
195
- * node carries none of them.
196
- *
197
- * These are checked before `type` because they can appear without one and take
198
- * precedence when they do: a node with both `enum` and `type` is constrained by
199
- * the enum, which is the narrower of the two.
200
- */
201
- function check_keywords(schema, value, path) {
202
- if ("const" in schema) return check_const(schema["const"], value, path);
203
- if (Array.isArray(schema["enum"])) return check_enum(schema["enum"], value, path);
204
- if (Array.isArray(schema["anyOf"])) return check_any_of(schema["anyOf"], value, path);
205
- if (Array.isArray(schema["oneOf"])) return check_any_of(schema["oneOf"], value, path);
206
- if (Array.isArray(schema["allOf"])) return check_all_of(schema["allOf"], value, path);
207
- }
208
- /**
209
- * Checks the node's declared shape: its `type`, in either the single or the
210
- * array form.
211
- *
212
- * A node with no `type` but declared `properties` is still an object; a node
213
- * with neither says nothing structural and accepts.
214
- */
215
- function check_shape(schema, value, path) {
216
- const type = schema["type"];
217
- if (Array.isArray(type)) return check_type_union(type, schema, value, path);
218
- if (typeof type === "string") return check_type(type, schema, value, path);
219
- if (is_record(schema["properties"])) return check_object(schema, value, path);
220
- return [];
221
- }
222
- /**
223
- * Checks a `const`, which pins the value to one JSON literal.
224
- *
225
- * An object or array `const` accepts anything: matching it would mean a deep
226
- * comparison the server performs itself, and rejecting a valid argument is the
227
- * one failure mode this bridge must not have.
228
- */
229
- function check_const(expected, value, path) {
230
- if (expected === null) return value === null ? [] : [issue("expected null", path)];
231
- if (typeof expected === "string" || typeof expected === "number" || typeof expected === "boolean") return value === expected ? [] : [issue(`expected ${JSON.stringify(expected)}`, path)];
232
- return [];
233
- }
234
- /**
235
- * Checks an `enum`, which pins the value to one of a list of JSON literals.
236
- * An empty enum constrains nothing and accepts.
237
- */
238
- function check_enum(values, value, path) {
239
- if (values.length === 0) return [];
240
- if (values.some((candidate) => check_const(candidate, value, path).length === 0)) return [];
241
- return [issue(`expected one of ${values.map((v) => JSON.stringify(v)).join(", ")}`, path)];
242
- }
243
- /**
244
- * Checks an `anyOf` or `oneOf`, which passes when any branch passes.
245
- *
246
- * `oneOf` demands one match and only one; the bridge deliberately relaxes that
247
- * to at least one, since the distinction only ever rejects a value the server
248
- * would accept.
249
- *
250
- * A single-branch union reports that branch's own issues rather than a generic
251
- * "no variant matched", since with one variant there is no ambiguity about
252
- * which one failed.
253
- */
254
- function check_any_of(nodes, value, path) {
255
- if (nodes.length === 0) return [];
256
- if (nodes.length === 1) return check(nodes[0], value, path);
257
- if (nodes.some((node) => check(node, value, path).length === 0)) return [];
258
- return [issue(`expected one of ${nodes.length} variants`, path)];
259
- }
260
- /**
261
- * Checks an `allOf`, which passes only when every branch passes.
262
- */
263
- function check_all_of(nodes, value, path) {
264
- return nodes.flatMap((node) => check(node, value, path));
265
- }
266
- /**
267
- * Checks the array form of `type` (`["string", "null"]`), which passes when the
268
- * value matches any listed type. The other keywords on the node apply to
269
- * whichever type matched, so each branch sees the whole node.
270
- */
271
- function check_type_union(types, schema, value, path) {
272
- if (types.length === 0) return [];
273
- if (types.length === 1) return check_type(String(types[0]), schema, value, path);
274
- if (types.some((type) => check_type(String(type), schema, value, path).length === 0)) return [];
275
- return [issue(`expected one of ${types.map(String).join(", ")}`, path)];
276
- }
277
- /**
278
- * The scalar `type` keywords, as predicates over the value.
279
- *
280
- * `number` rejects `NaN` and infinities because neither survives JSON, and
281
- * `integer` is the same check narrowed to whole values.
282
- */
283
- const SCALAR_TYPES = {
284
- string: (value) => typeof value === "string",
285
- number: (value) => typeof value === "number" && Number.isFinite(value),
286
- integer: (value) => Number.isInteger(value),
287
- boolean: (value) => typeof value === "boolean",
288
- null: (value) => value === null
289
- };
290
- /**
291
- * Checks one `type` keyword. `object` and `array` recurse into the node's own
292
- * `properties` and `items`; everything else is a scalar predicate.
293
- *
294
- * An unrecognized type accepts, so a vendor extension cannot reject an argument
295
- * the server would take.
296
- */
297
- function check_type(type, schema, value, path) {
298
- if (type === "object") return check_object(schema, value, path);
299
- if (type === "array") return check_array(schema, value, path);
300
- const matches = SCALAR_TYPES[type];
301
- if (matches === void 0) return [];
302
- return matches(value) ? [] : [type_issue(type, value, path)];
303
- }
304
- /**
305
- * Checks an object against its `properties` and `required`.
306
- *
307
- * Keys the schema does not declare are left alone rather than rejected, so an
308
- * argument this bridge did not anticipate still reaches the server, which
309
- * re-validates and is the real authority. A `required` name with no entry in
310
- * `properties` is likewise not enforced: there is nothing to check it against.
311
- */
312
- function check_object(schema, value, path) {
313
- if (!is_record(value)) return [type_issue("object", value, path)];
314
- const properties = as_record(schema["properties"]) ?? {};
315
- const required = new Set(string_array(schema["required"]));
316
- const issues = [];
317
- for (const [key, property] of Object.entries(properties)) {
318
- const child = value[key];
319
- if (child === void 0) {
320
- if (required.has(key)) issues.push(issue("required", [...path, key]));
321
- continue;
322
- }
323
- issues.push(...check(property, child, [...path, key]));
324
- }
325
- return issues;
326
- }
327
- /**
328
- * Checks an array against its `items`.
329
- *
330
- * A positional-tuple `items` (an array rather than a node) is not a record, so
331
- * every element accepts. Tuple schemas are rare in MCP tools and the server
332
- * re-validates them anyway.
333
- */
334
- function check_array(schema, value, path) {
335
- if (!Array.isArray(value)) return [type_issue("array", value, path)];
336
- return value.flatMap((item, index) => check(schema["items"], item, [...path, index]));
337
- }
338
- /**
339
- * Builds a type-mismatch issue naming what was expected and what arrived.
340
- */
341
- function type_issue(expected, value, path) {
342
- return issue(`expected ${expected}, received ${describe(value)}`, path);
343
- }
344
- /**
345
- * Names a value's type the way a JSON Schema reader would, separating `null`
346
- * and arrays out of `typeof`'s `object`.
347
- */
348
- function describe(value) {
349
- if (value === null) return "null";
350
- if (Array.isArray(value)) return "array";
351
- return typeof value;
352
- }
353
- /**
354
- * Builds one issue, omitting the path entirely at the root so a failure about
355
- * the value as a whole does not report an empty path.
356
- */
357
- function issue(message, path) {
358
- return path.length === 0 ? { message } : {
359
- message,
360
- path: [...path]
361
- };
362
- }
363
- /**
364
- * Filters a value down to the strings it contains, or an empty array when it
365
- * is not an array at all.
366
- */
367
- function string_array(value) {
368
- return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
369
- }
370
- //#endregion
371
107
  //#region src/mcp/sdk_loader.ts
372
108
  /**
373
109
  * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/internal.ts","../src/mcp/result_mapping.ts","../src/mcp/schema_bridge.ts","../src/mcp/sdk_loader.ts","../src/mcp/client.ts","../src/mcp/serve.ts"],"sourcesContent":["/**\n * Typed errors for the MCP adapter.\n *\n * Listed alongside src/core/errors.ts and src/engine/errors.ts in the\n * `no-class` rule ignores: `instanceof` branching is how callers distinguish a\n * missing optional peer from a tool-level failure surfaced over the wire.\n */\n\nexport class mcp_sdk_missing_error extends Error {\n readonly kind = 'mcp_sdk_missing_error' as const;\n constructor(\n message = '@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk',\n ) {\n super(message)\n this.name = 'mcp_sdk_missing_error'\n }\n}\n\nexport class mcp_error extends Error {\n readonly kind = 'mcp_error' as const;\n readonly tool_name: string | undefined;\n constructor(message: string, metadata: { tool_name?: string } = {}) {\n super(message)\n this.name = 'mcp_error'\n this.tool_name = metadata.tool_name\n }\n}\n","/**\n * Small shared guards for the MCP adapter. Kept in one place so the client,\n * schema bridge, and result mapping do not each carry a copy.\n */\n\n/**\n * Narrows a value to a plain object: non-null, `typeof` object, not an array.\n */\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Returns the value when it is a plain object, otherwise `undefined`.\n */\nexport function as_record(value: unknown): Record<string, unknown> | undefined {\n return is_record(value) ? value : undefined\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in\n * both directions: inbound results from `mcp_client` tools, outbound results\n * for `serve_flow`.\n */\n\nimport { mcp_error } from './errors.js'\nimport { as_record, is_record } from './internal.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\n\n/**\n * Converts a remote tool's `CallToolResult` into the value a Fascicle\n * `Tool.execute` returns.\n *\n * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather\n * than returning, letting the tool loop's error policy feed it back to the\n * model. `structuredContent` is preferred over joined text parts when present;\n * with neither, the raw `content` (or `null`) is returned.\n */\nexport function call_result_to_output(result: unknown, tool_name?: string): unknown {\n const record = as_record(result) ?? {}\n\n if (record['isError'] === true) {\n const detail = join_text(record['content']) ?? 'MCP tool returned an error'\n throw new mcp_error(detail, tool_name !== undefined ? { tool_name } : {})\n }\n\n if (is_record(record['structuredContent'])) return record['structuredContent']\n\n const text = join_text(record['content'])\n if (text !== undefined) return text\n\n return record['content'] ?? null\n}\n\n/**\n * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.\n *\n * A `to_result` override takes precedence over the default mapping. By\n * default, objects are emitted as both a JSON text part (every MCP host can\n * read text) and `structuredContent` (typed hosts get the object); everything\n * else becomes a single text part.\n */\nexport function output_to_call_result<o>(\n output: o,\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> },\n): McpToolResult {\n if (to_result !== undefined) {\n const shaped = to_result(output)\n return build_result(shaped.text, shaped.structured)\n }\n if (typeof output === 'string') return build_result(output)\n if (is_record(output)) return build_result(stringify(output), output)\n if (Array.isArray(output)) return build_result(stringify(output))\n return build_result(String(output))\n}\n\n/**\n * Assembles a `CallToolResult` with one text part and, when given, structured\n * content.\n */\nfunction build_result(text: string, structured?: Record<string, unknown>): McpToolResult {\n return structured !== undefined\n ? { content: [{ type: 'text', text }], structuredContent: structured }\n : { content: [{ type: 'text', text }] }\n}\n\n/**\n * Joins the `text` parts of an MCP content array with newlines, skipping\n * non-text parts; `undefined` when there is nothing to join.\n */\nfunction join_text(content: unknown): string | undefined {\n if (!Array.isArray(content)) return undefined\n const parts: string[] = []\n for (const part of content) {\n if (is_record(part) && part['type'] === 'text' && typeof part['text'] === 'string') {\n parts.push(part['text'])\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined\n}\n\n/**\n * `JSON.stringify` that falls back to `String` instead of throwing on\n * unserializable values (circular references, BigInt).\n */\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * A Standard Schema over an inbound MCP tool's advertised JSON Schema.\n *\n * An MCP tool advertises its input as JSON Schema, and a Fascicle `Tool` carries\n * a `ToolSchema` that the tool loop validates before `execute` and the engine\n * emits back to the provider as JSON Schema. Those are two faces of one object,\n * so this bridge builds both directly over the schema the server sent: emission\n * hands the advertised schema back unchanged, and validation walks it.\n *\n * The old bridge converted the advertised schema into Zod so the provider path\n * could convert it back, a round trip that was lossy by construction. Verbatim\n * emission is strictly higher fidelity: whatever the server declared is what the\n * model is told, including the constraints (`minLength`, `format`, `pattern`)\n * the Zod conversion dropped.\n *\n * Validation stays deliberately loose, unchanged from the Zod bridge's reach:\n * structure, types, enums, const, unions, and required keys are checked, value\n * constraints are not, extra keys pass through to the server, and anything\n * unrecognized accepts. The remote server re-validates its own arguments and is\n * the authority on them, so this check is a guard against an obviously wrong\n * call, not the contract.\n */\n\nimport type { SchemaIssue, ToolSchema } from '#schema'\nimport { as_record, is_record } from './internal.js'\n\n/**\n * Builds a `ToolSchema` over an MCP server's advertised JSON Schema.\n *\n * The advertised schema is snapshotted once, deeply, and both faces of the\n * returned object read that snapshot. A malformed or hostile schema degrades to\n * the empty schema during the snapshot rather than propagating an error, since\n * an arbitrary remote server's advertisement must never crash tool discovery,\n * and it leaves both faces describing the same thing: accept anything, emit\n * nothing.\n */\nexport function json_schema_to_standard(schema: unknown): ToolSchema {\n const advertised = snapshot(schema)\n return {\n '~standard': {\n version: 1,\n vendor: 'fascicle-mcp',\n validate: (value: unknown) => {\n const issues = check(advertised, value, [])\n return issues.length === 0 ? { value } : { issues }\n },\n jsonSchema: {\n // `target` is ignored in both directions: fascicle applies no transform,\n // so there is no re-targeting to do, and the dialect on the wire is\n // whichever one the server chose to advertise. Each call returns a fresh\n // copy because consumers mutate what they are handed (the AI SDK stamps\n // `additionalProperties` onto it in place), and a shared snapshot would\n // stop being verbatim after the first turn.\n input: () => clone_schema(advertised),\n output: () => clone_schema(advertised),\n },\n },\n }\n}\n\n/**\n * Deep-copies the advertised schema, or yields the empty schema when it is not\n * an object or cannot be read.\n *\n * Copying here means every later read walks plain data: a schema with throwing\n * accessors or a cycle fails once, at discovery, instead of on some later call.\n */\nfunction snapshot(schema: unknown): Record<string, unknown> {\n try {\n const record = as_record(schema)\n return record === undefined ? {} : clone_schema(record)\n } catch {\n return {}\n }\n}\n\n/**\n * Deep-copies one JSON Schema node.\n */\nfunction clone_schema(schema: Record<string, unknown>): Record<string, unknown> {\n const copy: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) copy[key] = clone_value(value)\n return copy\n}\n\n/**\n * Deep-copies a value inside a schema, recursing through arrays and objects and\n * returning every other value as is.\n */\nfunction clone_value(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(clone_value)\n return is_record(value) ? clone_schema(value) : value\n}\n\n/**\n * Checks one value against one JSON Schema node, returning the issues it\n * violated, or an empty array when it passes.\n *\n * A node that is not an object constrains nothing and accepts, which is what\n * makes a construct this bridge does not model degrade rather than reject.\n */\nfunction check(node: unknown, value: unknown, path: ReadonlyArray<PropertyKey>): SchemaIssue[] {\n const schema = as_record(node)\n if (schema === undefined) return []\n return check_keywords(schema, value, path) ?? check_shape(schema, value, path)\n}\n\n/**\n * Checks the keywords that stand on their own, returning `undefined` when the\n * node carries none of them.\n *\n * These are checked before `type` because they can appear without one and take\n * precedence when they do: a node with both `enum` and `type` is constrained by\n * the enum, which is the narrower of the two.\n */\nfunction check_keywords(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] | undefined {\n if ('const' in schema) return check_const(schema['const'], value, path)\n if (Array.isArray(schema['enum'])) return check_enum(schema['enum'], value, path)\n if (Array.isArray(schema['anyOf'])) return check_any_of(schema['anyOf'], value, path)\n if (Array.isArray(schema['oneOf'])) return check_any_of(schema['oneOf'], value, path)\n if (Array.isArray(schema['allOf'])) return check_all_of(schema['allOf'], value, path)\n return undefined\n}\n\n/**\n * Checks the node's declared shape: its `type`, in either the single or the\n * array form.\n *\n * A node with no `type` but declared `properties` is still an object; a node\n * with neither says nothing structural and accepts.\n */\nfunction check_shape(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n const type = schema['type']\n if (Array.isArray(type)) return check_type_union(type, schema, value, path)\n if (typeof type === 'string') return check_type(type, schema, value, path)\n if (is_record(schema['properties'])) return check_object(schema, value, path)\n return []\n}\n\n/**\n * Checks a `const`, which pins the value to one JSON literal.\n *\n * An object or array `const` accepts anything: matching it would mean a deep\n * comparison the server performs itself, and rejecting a valid argument is the\n * one failure mode this bridge must not have.\n */\nfunction check_const(\n expected: unknown,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (expected === null) return value === null ? [] : [issue('expected null', path)]\n if (\n typeof expected === 'string' ||\n typeof expected === 'number' ||\n typeof expected === 'boolean'\n ) {\n return value === expected ? [] : [issue(`expected ${JSON.stringify(expected)}`, path)]\n }\n return []\n}\n\n/**\n * Checks an `enum`, which pins the value to one of a list of JSON literals.\n * An empty enum constrains nothing and accepts.\n */\nfunction check_enum(\n values: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (values.length === 0) return []\n if (values.some((candidate) => check_const(candidate, value, path).length === 0)) return []\n return [issue(`expected one of ${values.map((v) => JSON.stringify(v)).join(', ')}`, path)]\n}\n\n/**\n * Checks an `anyOf` or `oneOf`, which passes when any branch passes.\n *\n * `oneOf` demands one match and only one; the bridge deliberately relaxes that\n * to at least one, since the distinction only ever rejects a value the server\n * would accept.\n *\n * A single-branch union reports that branch's own issues rather than a generic\n * \"no variant matched\", since with one variant there is no ambiguity about\n * which one failed.\n */\nfunction check_any_of(\n nodes: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (nodes.length === 0) return []\n if (nodes.length === 1) return check(nodes[0], value, path)\n if (nodes.some((node) => check(node, value, path).length === 0)) return []\n return [issue(`expected one of ${nodes.length} variants`, path)]\n}\n\n/**\n * Checks an `allOf`, which passes only when every branch passes.\n */\nfunction check_all_of(\n nodes: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n return nodes.flatMap((node) => check(node, value, path))\n}\n\n/**\n * Checks the array form of `type` (`[\"string\", \"null\"]`), which passes when the\n * value matches any listed type. The other keywords on the node apply to\n * whichever type matched, so each branch sees the whole node.\n */\nfunction check_type_union(\n types: unknown[],\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (types.length === 0) return []\n if (types.length === 1) return check_type(String(types[0]), schema, value, path)\n if (types.some((type) => check_type(String(type), schema, value, path).length === 0)) return []\n return [issue(`expected one of ${types.map(String).join(', ')}`, path)]\n}\n\n/**\n * The scalar `type` keywords, as predicates over the value.\n *\n * `number` rejects `NaN` and infinities because neither survives JSON, and\n * `integer` is the same check narrowed to whole values.\n */\nconst SCALAR_TYPES: Record<string, (value: unknown) => boolean> = {\n string: (value) => typeof value === 'string',\n number: (value) => typeof value === 'number' && Number.isFinite(value),\n integer: (value) => Number.isInteger(value),\n boolean: (value) => typeof value === 'boolean',\n null: (value) => value === null,\n}\n\n/**\n * Checks one `type` keyword. `object` and `array` recurse into the node's own\n * `properties` and `items`; everything else is a scalar predicate.\n *\n * An unrecognized type accepts, so a vendor extension cannot reject an argument\n * the server would take.\n */\nfunction check_type(\n type: string,\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (type === 'object') return check_object(schema, value, path)\n if (type === 'array') return check_array(schema, value, path)\n const matches = SCALAR_TYPES[type]\n if (matches === undefined) return []\n return matches(value) ? [] : [type_issue(type, value, path)]\n}\n\n/**\n * Checks an object against its `properties` and `required`.\n *\n * Keys the schema does not declare are left alone rather than rejected, so an\n * argument this bridge did not anticipate still reaches the server, which\n * re-validates and is the real authority. A `required` name with no entry in\n * `properties` is likewise not enforced: there is nothing to check it against.\n */\nfunction check_object(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (!is_record(value)) return [type_issue('object', value, path)]\n const properties = as_record(schema['properties']) ?? {}\n const required = new Set(string_array(schema['required']))\n const issues: SchemaIssue[] = []\n for (const [key, property] of Object.entries(properties)) {\n const child = value[key]\n if (child === undefined) {\n if (required.has(key)) issues.push(issue('required', [...path, key]))\n continue\n }\n issues.push(...check(property, child, [...path, key]))\n }\n return issues\n}\n\n/**\n * Checks an array against its `items`.\n *\n * A positional-tuple `items` (an array rather than a node) is not a record, so\n * every element accepts. Tuple schemas are rare in MCP tools and the server\n * re-validates them anyway.\n */\nfunction check_array(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (!Array.isArray(value)) return [type_issue('array', value, path)]\n return value.flatMap((item, index) => check(schema['items'], item, [...path, index]))\n}\n\n/**\n * Builds a type-mismatch issue naming what was expected and what arrived.\n */\nfunction type_issue(\n expected: string,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue {\n return issue(`expected ${expected}, received ${describe(value)}`, path)\n}\n\n/**\n * Names a value's type the way a JSON Schema reader would, separating `null`\n * and arrays out of `typeof`'s `object`.\n */\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'array'\n return typeof value\n}\n\n/**\n * Builds one issue, omitting the path entirely at the root so a failure about\n * the value as a whole does not report an empty path.\n */\nfunction issue(message: string, path: ReadonlyArray<PropertyKey>): SchemaIssue {\n return path.length === 0 ? { message } : { message, path: [...path] }\n}\n\n/**\n * Filters a value down to the strings it contains, or an empty array when it\n * is not an array at all.\n */\nfunction string_array(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\n}\n","/**\n * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.\n *\n * `mcp_client` needs SDK values (the Client and transport constructors), so it\n * imports them dynamically rather than statically: a consumer can import\n * `fascicle/mcp` without the SDK installed and only pays the cost when they\n * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`\n * with install guidance, mirroring the engine's `load_optional_peer`.\n *\n * `serve_flow` is not covered here: it operates on a caller-constructed\n * `McpServer`, so it needs only a type-only import and no runtime SDK load.\n */\n\nimport { mcp_sdk_missing_error } from './errors.js'\n\nexport type McpClientSdk = Awaited<ReturnType<typeof load_client_sdk>>\n\n/**\n * Dynamically imports the `@modelcontextprotocol/sdk` client modules,\n * throwing a typed `mcp_sdk_missing_error` when the optional peer is not\n * installed.\n */\nexport async function load_client_sdk() {\n try {\n const [client_mod, stdio_mod, http_mod] = await Promise.all([\n import('@modelcontextprotocol/sdk/client/index.js'),\n import('@modelcontextprotocol/sdk/client/stdio.js'),\n import('@modelcontextprotocol/sdk/client/streamableHttp.js'),\n ])\n return {\n Client: client_mod.Client,\n StdioClientTransport: stdio_mod.StdioClientTransport,\n StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport,\n }\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new mcp_sdk_missing_error(\n `@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${detail})`,\n )\n }\n}\n","/**\n * Inbound MCP: connect to an external MCP server and surface its tools as plain\n * Fascicle `Tool[]`.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'\nimport type { Tool, ToolExecContext } from '#engine'\nimport { mcp_error } from './errors.js'\nimport { is_record } from './internal.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { json_schema_to_standard } from './schema_bridge.js'\nimport { load_client_sdk, type McpClientSdk } from './sdk_loader.js'\n\nconst DEFAULT_CLIENT_INFO = { name: 'fascicle', version: '0.0.0' }\n\nexport type McpStdioConfig = {\n transport: 'stdio'\n command: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n}\n\nexport type McpStreamableHttpConfig = {\n transport: 'http'\n url: string\n headers?: Record<string, string>\n}\n\n// Escape hatch: hand in an already-connected Client (a transport the adapter\n// does not build, a test harness, a shared connection). Its lifecycle stays\n// with the caller, so the returned `close` is a no-op for this variant.\nexport type McpExistingClientConfig = {\n transport: 'client'\n client: Client\n}\n\nexport type McpClientConfig =\n | McpStdioConfig\n | McpStreamableHttpConfig\n | McpExistingClientConfig\n\nexport type McpClientOptions = {\n // Identity sent in the MCP handshake; defaults to Fascicle.\n client_info?: { name: string; version: string }\n // When set, only tools whose name is listed are surfaced.\n include?: ReadonlyArray<string>\n // Supplies a description for tools that advertise none.\n default_description?: (tool_name: string) => string\n}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\n\n/**\n * Connects to an MCP server and surfaces its advertised tools as Fascicle\n * `Tool[]`, plus a `close` handle for the connection.\n *\n * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers\n * do not have to import SDK transport classes themselves. Each advertised MCP\n * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`\n * the loop validates against and the provider receives back unchanged, and\n * `execute` forwards to `callTool`, propagating the run's abort signal. For the\n * `client` transport variant the caller keeps ownership of the connection, so\n * `close` is a no-op.\n */\nexport async function mcp_client(\n config: McpClientConfig,\n options: McpClientOptions = {},\n): Promise<McpClientHandle> {\n const owns_client = config.transport !== 'client'\n const client = await connect_client(config, options)\n\n const include = options.include !== undefined ? new Set(options.include) : undefined\n const listed = await client.listTools()\n const tools: Tool[] = []\n for (const advertised of listed.tools) {\n if (include !== undefined && !include.has(advertised.name)) continue\n tools.push(to_fascicle_tool(client, advertised, options))\n }\n\n return {\n tools,\n close: async () => {\n if (owns_client) await client.close()\n },\n }\n}\n\n/**\n * Returns the caller's already-connected client as-is, or lazily loads the\n * SDK and connects a fresh client over the configured transport.\n */\nasync function connect_client(\n config: McpClientConfig,\n options: McpClientOptions,\n): Promise<Client> {\n if (config.transport === 'client') return config.client\n const sdk = await load_client_sdk()\n const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO)\n await client.connect(build_transport(sdk, config))\n return client\n}\n\n/**\n * Constructs the SDK transport matching the config: a spawned child process\n * for `stdio`, a Streamable HTTP connection for `http`.\n */\nfunction build_transport(\n sdk: McpClientSdk,\n config: McpStdioConfig | McpStreamableHttpConfig,\n): Transport {\n if (config.transport === 'stdio') {\n return new sdk.StdioClientTransport({\n command: config.command,\n ...(config.args !== undefined ? { args: config.args } : {}),\n ...(config.env !== undefined ? { env: config.env } : {}),\n ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),\n })\n }\n const opts = config.headers !== undefined ? { requestInit: { headers: config.headers } } : {}\n // The SDK declares this class `implements Transport`, but its `onmessage`\n // overload is narrower than the interface's, which only strict mode flags.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts) as Transport\n}\n\n/**\n * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards\n * to `callTool` on the shared client.\n *\n * An already-aborted signal short-circuits before the wire call; otherwise the\n * signal is passed through so cancelling the run cancels the remote call.\n */\nfunction to_fascicle_tool(\n client: Client,\n advertised: { name: string; description?: string | undefined; inputSchema: unknown },\n options: McpClientOptions,\n): Tool {\n const name = advertised.name\n const description =\n advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`\n return {\n name,\n description,\n input_schema: json_schema_to_standard(advertised.inputSchema),\n execute: async (input: unknown, ctx: ToolExecContext) => {\n if (ctx.abort.aborted) {\n throw ctx.abort.reason instanceof Error\n ? ctx.abort.reason\n : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name })\n }\n const result = await client.callTool(\n { name, arguments: is_record(input) ? input : undefined },\n undefined,\n { signal: ctx.abort },\n )\n return call_result_to_output(result, name)\n },\n }\n}\n","/**\n * Outbound MCP: expose a composed Fascicle flow as an MCP tool.\n *\n * `serve_flow` registers onto a caller-constructed `McpServer` (the caller owns\n * the transport, identity, and lifecycle, and can host many flows on one\n * server), so it needs only a type-only SDK import. The registered handler\n * drives the existing `run`, threading the per-request abort signal so an MCP\n * client cancellation aborts the in-flight flow, and maps the result into a\n * `CallToolResult`. A thrown flow becomes an `isError` result rather than a\n * JSON-RPC protocol error.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { output_to_call_result } from './result_mapping.js'\n\nexport type ServeFlowOptions<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\n /**\n * Stays zod rather than joining the rest of the surface on `ToolSchema`.\n * `McpServer.registerTool` types `inputSchema` as a zod schema and offers no\n * JSON Schema entry point, and the SDK carries zod as a hard runtime\n * dependency, so a `serve_flow` caller already has zod resolved. Widening\n * this to a neutral schema would typecheck and then fail inside the SDK.\n */\n input_schema: z.ZodType<i>\n trajectory?: TrajectoryLogger\n // Overrides the default value-to-CallToolResult mapping.\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> }\n}\n\n/**\n * Registers a Fascicle flow as a tool on a caller-owned MCP server.\n *\n * Drives the flow with `run`, threading the per-request abort signal so an\n * MCP client cancellation aborts the in-flight flow, and maps the result\n * into a `CallToolResult`. A thrown flow becomes an `isError` result rather\n * than a JSON-RPC protocol error.\n */\nexport function serve_flow<i, o>(options: ServeFlowOptions<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = options\n server.registerTool(\n name,\n { description, inputSchema: input_schema },\n async (input: i, extra) => {\n try {\n const output = await run(flow, input, {\n install_signal_handlers: false,\n abort: extra.signal,\n ...(trajectory !== undefined ? { trajectory } : {}),\n })\n return output_to_call_result(output, to_result)\n } catch (err: unknown) {\n return {\n isError: true,\n content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],\n }\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,OAAgB;CAChB,YACE,U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AM,SACZ,MAAM,IAAI,MAAM,kBAAkB,QAC9B,IAAI,MAAM,SACV,IAAI,UAAU,YAAY,KAAK,6BAA6B,EAAE,WAAW,KAAK,CAAC;GAOrF,OAAO,sBAAsB,MALR,OAAO,SAC1B;IAAE;IAAM,WAAW,UAAU,KAAK,IAAI,QAAQ,KAAA;GAAU,GACxD,KAAA,GACA,EAAE,QAAQ,IAAI,MAAM,CACtB,GACqC,IAAI;EAC3C;CACF;AACF;;;;;;;;;;;ACvHA,SAAgB,WAAiB,SAAuC;CACtE,MAAM,EAAE,QAAQ,MAAM,MAAM,aAAa,cAAc,YAAY,cAAc;CACjF,OAAO,aACL,MACA;EAAE;EAAa,aAAa;CAAa,GACzC,OAAO,OAAU,UAAU;EACzB,IAAI;GAMF,OAAO,sBAAsB,MALR,IAAI,MAAM,OAAO;IACpC,yBAAyB;IACzB,OAAO,MAAM;IACb,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;GACnD,CAAC,GACoC,SAAS;EAChD,SAAS,KAAc;GACrB,OAAO;IACL,SAAS;IACT,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;IAAE,CAAC;GACpF;EACF;CACF,CACF;AACF"}
1
+ {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/result_mapping.ts","../src/mcp/sdk_loader.ts","../src/mcp/client.ts","../src/mcp/serve.ts"],"sourcesContent":["/**\n * Typed errors for the MCP adapter.\n *\n * Listed alongside src/core/errors.ts and src/engine/errors.ts in the\n * `no-class` rule ignores: `instanceof` branching is how callers distinguish a\n * missing optional peer from a tool-level failure surfaced over the wire.\n */\n\nexport class mcp_sdk_missing_error extends Error {\n readonly kind = 'mcp_sdk_missing_error' as const;\n constructor(\n message = '@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk',\n ) {\n super(message)\n this.name = 'mcp_sdk_missing_error'\n }\n}\n\nexport class mcp_error extends Error {\n readonly kind = 'mcp_error' as const;\n readonly tool_name: string | undefined;\n constructor(message: string, metadata: { tool_name?: string } = {}) {\n super(message)\n this.name = 'mcp_error'\n this.tool_name = metadata.tool_name\n }\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in\n * both directions: inbound results from `mcp_client` tools, outbound results\n * for `serve_flow`.\n */\n\nimport { as_record, is_record } from '#schema'\nimport { mcp_error } from './errors.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\n\n/**\n * Converts a remote tool's `CallToolResult` into the value a Fascicle\n * `Tool.execute` returns.\n *\n * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather\n * than returning, letting the tool loop's error policy feed it back to the\n * model. `structuredContent` is preferred over joined text parts when present;\n * with neither, the raw `content` (or `null`) is returned.\n */\nexport function call_result_to_output(result: unknown, tool_name?: string): unknown {\n const record = as_record(result) ?? {}\n\n if (record['isError'] === true) {\n const detail = join_text(record['content']) ?? 'MCP tool returned an error'\n throw new mcp_error(detail, tool_name !== undefined ? { tool_name } : {})\n }\n\n if (is_record(record['structuredContent'])) return record['structuredContent']\n\n const text = join_text(record['content'])\n if (text !== undefined) return text\n\n return record['content'] ?? null\n}\n\n/**\n * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.\n *\n * A `to_result` override takes precedence over the default mapping. By\n * default, objects are emitted as both a JSON text part (every MCP host can\n * read text) and `structuredContent` (typed hosts get the object); everything\n * else becomes a single text part.\n */\nexport function output_to_call_result<o>(\n output: o,\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> },\n): McpToolResult {\n if (to_result !== undefined) {\n const shaped = to_result(output)\n return build_result(shaped.text, shaped.structured)\n }\n if (typeof output === 'string') return build_result(output)\n if (is_record(output)) return build_result(stringify(output), output)\n if (Array.isArray(output)) return build_result(stringify(output))\n return build_result(String(output))\n}\n\n/**\n * Assembles a `CallToolResult` with one text part and, when given, structured\n * content.\n */\nfunction build_result(text: string, structured?: Record<string, unknown>): McpToolResult {\n return structured !== undefined\n ? { content: [{ type: 'text', text }], structuredContent: structured }\n : { content: [{ type: 'text', text }] }\n}\n\n/**\n * Joins the `text` parts of an MCP content array with newlines, skipping\n * non-text parts; `undefined` when there is nothing to join.\n */\nfunction join_text(content: unknown): string | undefined {\n if (!Array.isArray(content)) return undefined\n const parts: string[] = []\n for (const part of content) {\n if (is_record(part) && part['type'] === 'text' && typeof part['text'] === 'string') {\n parts.push(part['text'])\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined\n}\n\n/**\n * `JSON.stringify` that falls back to `String` instead of throwing on\n * unserializable values (circular references, BigInt).\n */\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.\n *\n * `mcp_client` needs SDK values (the Client and transport constructors), so it\n * imports them dynamically rather than statically: a consumer can import\n * `fascicle/mcp` without the SDK installed and only pays the cost when they\n * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`\n * with install guidance, mirroring the engine's `load_optional_peer`.\n *\n * `serve_flow` is not covered here: it operates on a caller-constructed\n * `McpServer`, so it needs only a type-only import and no runtime SDK load.\n */\n\nimport { mcp_sdk_missing_error } from './errors.js'\n\nexport type McpClientSdk = Awaited<ReturnType<typeof load_client_sdk>>\n\n/**\n * Dynamically imports the `@modelcontextprotocol/sdk` client modules,\n * throwing a typed `mcp_sdk_missing_error` when the optional peer is not\n * installed.\n */\nexport async function load_client_sdk() {\n try {\n const [client_mod, stdio_mod, http_mod] = await Promise.all([\n import('@modelcontextprotocol/sdk/client/index.js'),\n import('@modelcontextprotocol/sdk/client/stdio.js'),\n import('@modelcontextprotocol/sdk/client/streamableHttp.js'),\n ])\n return {\n Client: client_mod.Client,\n StdioClientTransport: stdio_mod.StdioClientTransport,\n StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport,\n }\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new mcp_sdk_missing_error(\n `@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${detail})`,\n )\n }\n}\n","/**\n * Inbound MCP: connect to an external MCP server and surface its tools as plain\n * Fascicle `Tool[]`.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'\nimport type { Tool, ToolExecContext } from '#engine'\nimport { is_record, json_schema_to_standard } from '#schema'\nimport { mcp_error } from './errors.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { load_client_sdk, type McpClientSdk } from './sdk_loader.js'\n\nconst DEFAULT_CLIENT_INFO = { name: 'fascicle', version: '0.0.0' }\n\nexport type McpStdioConfig = {\n transport: 'stdio'\n command: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n}\n\nexport type McpStreamableHttpConfig = {\n transport: 'http'\n url: string\n headers?: Record<string, string>\n}\n\n// Escape hatch: hand in an already-connected Client (a transport the adapter\n// does not build, a test harness, a shared connection). Its lifecycle stays\n// with the caller, so the returned `close` is a no-op for this variant.\nexport type McpExistingClientConfig = {\n transport: 'client'\n client: Client\n}\n\nexport type McpClientConfig =\n | McpStdioConfig\n | McpStreamableHttpConfig\n | McpExistingClientConfig\n\nexport type McpClientOptions = {\n // Identity sent in the MCP handshake; defaults to Fascicle.\n client_info?: { name: string; version: string }\n // When set, only tools whose name is listed are surfaced.\n include?: ReadonlyArray<string>\n // Supplies a description for tools that advertise none.\n default_description?: (tool_name: string) => string\n}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\n\n/**\n * Connects to an MCP server and surfaces its advertised tools as Fascicle\n * `Tool[]`, plus a `close` handle for the connection.\n *\n * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers\n * do not have to import SDK transport classes themselves. Each advertised MCP\n * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`\n * the loop validates against and the provider receives back unchanged, and\n * `execute` forwards to `callTool`, propagating the run's abort signal. For the\n * `client` transport variant the caller keeps ownership of the connection, so\n * `close` is a no-op.\n */\nexport async function mcp_client(\n config: McpClientConfig,\n options: McpClientOptions = {},\n): Promise<McpClientHandle> {\n const owns_client = config.transport !== 'client'\n const client = await connect_client(config, options)\n\n const include = options.include !== undefined ? new Set(options.include) : undefined\n const listed = await client.listTools()\n const tools: Tool[] = []\n for (const advertised of listed.tools) {\n if (include !== undefined && !include.has(advertised.name)) continue\n tools.push(to_fascicle_tool(client, advertised, options))\n }\n\n return {\n tools,\n close: async () => {\n if (owns_client) await client.close()\n },\n }\n}\n\n/**\n * Returns the caller's already-connected client as-is, or lazily loads the\n * SDK and connects a fresh client over the configured transport.\n */\nasync function connect_client(\n config: McpClientConfig,\n options: McpClientOptions,\n): Promise<Client> {\n if (config.transport === 'client') return config.client\n const sdk = await load_client_sdk()\n const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO)\n await client.connect(build_transport(sdk, config))\n return client\n}\n\n/**\n * Constructs the SDK transport matching the config: a spawned child process\n * for `stdio`, a Streamable HTTP connection for `http`.\n */\nfunction build_transport(\n sdk: McpClientSdk,\n config: McpStdioConfig | McpStreamableHttpConfig,\n): Transport {\n if (config.transport === 'stdio') {\n return new sdk.StdioClientTransport({\n command: config.command,\n ...(config.args !== undefined ? { args: config.args } : {}),\n ...(config.env !== undefined ? { env: config.env } : {}),\n ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),\n })\n }\n const opts = config.headers !== undefined ? { requestInit: { headers: config.headers } } : {}\n // The SDK declares this class `implements Transport`, but its `onmessage`\n // overload is narrower than the interface's, which only strict mode flags.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts) as Transport\n}\n\n/**\n * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards\n * to `callTool` on the shared client.\n *\n * An already-aborted signal short-circuits before the wire call; otherwise the\n * signal is passed through so cancelling the run cancels the remote call.\n */\nfunction to_fascicle_tool(\n client: Client,\n advertised: { name: string; description?: string | undefined; inputSchema: unknown },\n options: McpClientOptions,\n): Tool {\n const name = advertised.name\n const description =\n advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`\n return {\n name,\n description,\n input_schema: json_schema_to_standard(advertised.inputSchema),\n execute: async (input: unknown, ctx: ToolExecContext) => {\n if (ctx.abort.aborted) {\n throw ctx.abort.reason instanceof Error\n ? ctx.abort.reason\n : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name })\n }\n const result = await client.callTool(\n { name, arguments: is_record(input) ? input : undefined },\n undefined,\n { signal: ctx.abort },\n )\n return call_result_to_output(result, name)\n },\n }\n}\n","/**\n * Outbound MCP: expose a composed Fascicle flow as an MCP tool.\n *\n * `serve_flow` registers onto a caller-constructed `McpServer` (the caller owns\n * the transport, identity, and lifecycle, and can host many flows on one\n * server), so it needs only a type-only SDK import. The registered handler\n * drives the existing `run`, threading the per-request abort signal so an MCP\n * client cancellation aborts the in-flight flow, and maps the result into a\n * `CallToolResult`. A thrown flow becomes an `isError` result rather than a\n * JSON-RPC protocol error.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { output_to_call_result } from './result_mapping.js'\n\nexport type ServeFlowOptions<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\n /**\n * Stays zod rather than joining the rest of the surface on `ToolSchema`.\n * `McpServer.registerTool` types `inputSchema` as a zod schema and offers no\n * JSON Schema entry point, and the SDK carries zod as a hard runtime\n * dependency, so a `serve_flow` caller already has zod resolved. Widening\n * this to a neutral schema would typecheck and then fail inside the SDK.\n */\n input_schema: z.ZodType<i>\n trajectory?: TrajectoryLogger\n // Overrides the default value-to-CallToolResult mapping.\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> }\n}\n\n/**\n * Registers a Fascicle flow as a tool on a caller-owned MCP server.\n *\n * Drives the flow with `run`, threading the per-request abort signal so an\n * MCP client cancellation aborts the in-flight flow, and maps the result\n * into a `CallToolResult`. A thrown flow becomes an `isError` result rather\n * than a JSON-RPC protocol error.\n */\nexport function serve_flow<i, o>(options: ServeFlowOptions<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = options\n server.registerTool(\n name,\n { description, inputSchema: input_schema },\n async (input: i, extra) => {\n try {\n const output = await run(flow, input, {\n install_signal_handlers: false,\n abort: extra.signal,\n ...(trajectory !== undefined ? { trajectory } : {}),\n })\n return output_to_call_result(output, to_result)\n } catch (err: unknown) {\n return {\n isError: true,\n content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],\n }\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,OAAgB;CAChB,YACE,UAAU,0GACV;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAa,YAAb,cAA+B,MAAM;CACnC,OAAgB;CAChB;CACA,YAAY,SAAiB,WAAmC,CAAC,GAAG;EAClE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS;CAC5B;AACF;;;;;;;;;;;;;;;;;ACHA,SAAgB,sBAAsB,QAAiB,WAA6B;CAClF,MAAM,SAAS,UAAU,MAAM,KAAK,CAAC;CAErC,IAAI,OAAO,eAAe,MAExB,MAAM,IAAI,UADK,UAAU,OAAO,UAAU,KAAK,8BACnB,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC,CAAC;CAG1E,IAAI,UAAU,OAAO,oBAAoB,GAAG,OAAO,OAAO;CAE1D,MAAM,OAAO,UAAU,OAAO,UAAU;CACxC,IAAI,SAAS,KAAA,GAAW,OAAO;CAE/B,OAAO,OAAO,cAAc;AAC9B;;;;;;;;;AAUA,SAAgB,sBACd,QAC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