fascicle 0.17.4 → 0.17.6
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.
- package/CHANGELOG.md +42 -0
- package/dist/AGENTS.md +9 -8
- package/dist/acp.d.ts +123 -1
- package/dist/acp.js +756 -89
- package/dist/acp.js.map +1 -1
- package/dist/{engine-CbVdzplI.js → engine-BTijBDlY.js} +194 -51
- package/dist/engine-BTijBDlY.js.map +1 -0
- package/dist/index.d.ts +149 -147
- package/dist/index.js +2 -2
- package/dist/{invoke-x5SNh9DV.js → invoke-DnmWf8gE.js} +2 -2
- package/dist/{invoke-x5SNh9DV.js.map → invoke-DnmWf8gE.js.map} +1 -1
- package/dist/{leading_system-C23TJ9OQ.js → leading_system-CHSYz0h9.js} +168 -19
- package/dist/leading_system-CHSYz0h9.js.map +1 -0
- package/dist/mcp-8mKK7eDY.js +267 -0
- package/dist/mcp-8mKK7eDY.js.map +1 -0
- package/dist/mcp.js +1 -265
- package/dist/testing.js +2 -2
- package/dist/viewer-app/assets/index-YrQFld-l.js +4 -0
- package/dist/viewer-app/index.html +1 -1
- package/package.json +6 -5
- package/dist/engine-CbVdzplI.js.map +0 -1
- package/dist/leading_system-C23TJ9OQ.js.map +0 -1
- package/dist/mcp.js.map +0 -1
- package/dist/viewer-app/assets/index-BkS2ZQu0.js +0 -4
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { w as run } from "./core-Bfzt55Fl.js";
|
|
2
|
+
import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
|
|
3
|
+
import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
|
|
4
|
+
//#region src/mcp/errors.ts
|
|
5
|
+
/**
|
|
6
|
+
* Typed errors for the MCP adapter.
|
|
7
|
+
*
|
|
8
|
+
* Listed alongside src/core/errors.ts and src/engine/errors.ts in the
|
|
9
|
+
* `no-class` rule ignores: `instanceof` branching is how callers distinguish a
|
|
10
|
+
* missing optional peer from a tool-level failure surfaced over the wire.
|
|
11
|
+
*/
|
|
12
|
+
var mcp_sdk_missing_error = class extends Error {
|
|
13
|
+
kind = "mcp_sdk_missing_error";
|
|
14
|
+
constructor(message = "@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk") {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "mcp_sdk_missing_error";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var mcp_error = class extends Error {
|
|
20
|
+
kind = "mcp_error";
|
|
21
|
+
tool_name;
|
|
22
|
+
constructor(message, metadata = {}) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "mcp_error";
|
|
25
|
+
this.tool_name = metadata.tool_name;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/mcp/result_mapping.ts
|
|
30
|
+
/**
|
|
31
|
+
* Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
|
|
32
|
+
* both directions: inbound results from `mcp_client` tools, outbound results
|
|
33
|
+
* for `serve_flow`.
|
|
34
|
+
*/
|
|
35
|
+
/**
|
|
36
|
+
* Converts a remote tool's `CallToolResult` into the value a Fascicle
|
|
37
|
+
* `Tool.execute` returns.
|
|
38
|
+
*
|
|
39
|
+
* `isError: true` marks a tool-level failure, so it throws `mcp_error` rather
|
|
40
|
+
* than returning, letting the tool loop's error policy feed it back to the
|
|
41
|
+
* model. `structuredContent` is preferred over joined text parts when present;
|
|
42
|
+
* with neither, the raw `content` (or `null`) is returned.
|
|
43
|
+
*/
|
|
44
|
+
function call_result_to_output(result, tool_name) {
|
|
45
|
+
const record = as_record(result) ?? {};
|
|
46
|
+
if (record["isError"] === true) throw new mcp_error(join_text(record["content"]) ?? "MCP tool returned an error", tool_name !== void 0 ? { tool_name } : {});
|
|
47
|
+
if (is_record(record["structuredContent"])) return record["structuredContent"];
|
|
48
|
+
const text = join_text(record["content"]);
|
|
49
|
+
if (text !== void 0) return text;
|
|
50
|
+
return record["content"] ?? null;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.
|
|
54
|
+
*
|
|
55
|
+
* A `to_result` override takes precedence over the default mapping. By
|
|
56
|
+
* default, objects are emitted as both a JSON text part (every MCP host can
|
|
57
|
+
* read text) and `structuredContent` (typed hosts get the object); everything
|
|
58
|
+
* else becomes a single text part.
|
|
59
|
+
*/
|
|
60
|
+
function output_to_call_result(output, to_result) {
|
|
61
|
+
if (to_result !== void 0) {
|
|
62
|
+
const shaped = to_result(output);
|
|
63
|
+
return build_result(shaped.text, shaped.structured);
|
|
64
|
+
}
|
|
65
|
+
if (typeof output === "string") return build_result(output);
|
|
66
|
+
if (is_record(output)) return build_result(stringify(output), output);
|
|
67
|
+
if (Array.isArray(output)) return build_result(stringify(output));
|
|
68
|
+
return build_result(String(output));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Assembles a `CallToolResult` with one text part and, when given, structured
|
|
72
|
+
* content.
|
|
73
|
+
*/
|
|
74
|
+
function build_result(text, structured) {
|
|
75
|
+
return structured !== void 0 ? {
|
|
76
|
+
content: [{
|
|
77
|
+
type: "text",
|
|
78
|
+
text
|
|
79
|
+
}],
|
|
80
|
+
structuredContent: structured
|
|
81
|
+
} : { content: [{
|
|
82
|
+
type: "text",
|
|
83
|
+
text
|
|
84
|
+
}] };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Joins the `text` parts of an MCP content array with newlines, skipping
|
|
88
|
+
* non-text parts; `undefined` when there is nothing to join.
|
|
89
|
+
*/
|
|
90
|
+
function join_text(content) {
|
|
91
|
+
if (!Array.isArray(content)) return void 0;
|
|
92
|
+
const parts = [];
|
|
93
|
+
for (const part of content) if (is_record(part) && part["type"] === "text" && typeof part["text"] === "string") parts.push(part["text"]);
|
|
94
|
+
return parts.length > 0 ? parts.join("\n") : void 0;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* `JSON.stringify` that falls back to `String` instead of throwing on
|
|
98
|
+
* unserializable values (circular references, BigInt).
|
|
99
|
+
*/
|
|
100
|
+
function stringify(value) {
|
|
101
|
+
try {
|
|
102
|
+
return JSON.stringify(value);
|
|
103
|
+
} catch {
|
|
104
|
+
return String(value);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/mcp/sdk_loader.ts
|
|
109
|
+
/**
|
|
110
|
+
* Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
|
|
111
|
+
*
|
|
112
|
+
* `mcp_client` needs SDK values (the Client and transport constructors), so it
|
|
113
|
+
* imports them dynamically rather than statically: a consumer can import
|
|
114
|
+
* `fascicle/mcp` without the SDK installed and only pays the cost when they
|
|
115
|
+
* actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`
|
|
116
|
+
* with install guidance, mirroring the engine's `load_optional_peer`.
|
|
117
|
+
*
|
|
118
|
+
* `serve_flow` is not covered here: it operates on a caller-constructed
|
|
119
|
+
* `McpServer`, so it needs only a type-only import and no runtime SDK load.
|
|
120
|
+
*/
|
|
121
|
+
/**
|
|
122
|
+
* Dynamically imports the `@modelcontextprotocol/sdk` client modules,
|
|
123
|
+
* throwing a typed `mcp_sdk_missing_error` when the optional peer is not
|
|
124
|
+
* installed.
|
|
125
|
+
*/
|
|
126
|
+
async function load_client_sdk() {
|
|
127
|
+
try {
|
|
128
|
+
const [client_mod, stdio_mod, http_mod] = await Promise.all([
|
|
129
|
+
import("@modelcontextprotocol/sdk/client/index.js"),
|
|
130
|
+
import("@modelcontextprotocol/sdk/client/stdio.js"),
|
|
131
|
+
import("@modelcontextprotocol/sdk/client/streamableHttp.js")
|
|
132
|
+
]);
|
|
133
|
+
return {
|
|
134
|
+
Client: client_mod.Client,
|
|
135
|
+
StdioClientTransport: stdio_mod.StdioClientTransport,
|
|
136
|
+
StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport
|
|
137
|
+
};
|
|
138
|
+
} catch (err) {
|
|
139
|
+
throw new mcp_sdk_missing_error(`@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${err instanceof Error ? err.message : String(err)})`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/mcp/client.ts
|
|
144
|
+
const DEFAULT_CLIENT_INFO = {
|
|
145
|
+
name: "fascicle",
|
|
146
|
+
version: "0.0.0"
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Connects to an MCP server and surfaces its advertised tools as Fascicle
|
|
150
|
+
* `Tool[]`, plus a `close` handle for the connection.
|
|
151
|
+
*
|
|
152
|
+
* Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
|
|
153
|
+
* do not have to import SDK transport classes themselves. Each advertised MCP
|
|
154
|
+
* tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`
|
|
155
|
+
* the loop validates against and the provider receives back unchanged, and
|
|
156
|
+
* `execute` forwards to `callTool`, propagating the run's abort signal. For the
|
|
157
|
+
* `client` transport variant the caller keeps ownership of the connection, so
|
|
158
|
+
* `close` is a no-op. A connection this call opened is closed again when
|
|
159
|
+
* listing its tools fails.
|
|
160
|
+
*/
|
|
161
|
+
async function mcp_client(config, options = {}) {
|
|
162
|
+
const owns_client = config.transport !== "client";
|
|
163
|
+
const client = await connect_client(config, options);
|
|
164
|
+
const include = options.include !== void 0 ? new Set(options.include) : void 0;
|
|
165
|
+
const listed = await client.listTools().catch(async (err) => {
|
|
166
|
+
if (owns_client) await client.close().catch(() => void 0);
|
|
167
|
+
throw err;
|
|
168
|
+
});
|
|
169
|
+
const tools = [];
|
|
170
|
+
for (const advertised of listed.tools) {
|
|
171
|
+
if (include !== void 0 && !include.has(advertised.name)) continue;
|
|
172
|
+
tools.push(to_fascicle_tool(client, advertised, options));
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
tools,
|
|
176
|
+
close: async () => {
|
|
177
|
+
if (owns_client) await client.close();
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Returns the caller's already-connected client as-is, or lazily loads the
|
|
183
|
+
* SDK and connects a fresh client over the configured transport.
|
|
184
|
+
*/
|
|
185
|
+
async function connect_client(config, options) {
|
|
186
|
+
if (config.transport === "client") return config.client;
|
|
187
|
+
const sdk = await load_client_sdk();
|
|
188
|
+
const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO);
|
|
189
|
+
await client.connect(build_transport(sdk, config));
|
|
190
|
+
return client;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Constructs the SDK transport matching the config: a spawned child process
|
|
194
|
+
* for `stdio`, a Streamable HTTP connection for `http`.
|
|
195
|
+
*/
|
|
196
|
+
function build_transport(sdk, config) {
|
|
197
|
+
if (config.transport === "stdio") return new sdk.StdioClientTransport({
|
|
198
|
+
command: config.command,
|
|
199
|
+
...config.args !== void 0 ? { args: config.args } : {},
|
|
200
|
+
...config.env !== void 0 ? { env: config.env } : {},
|
|
201
|
+
...config.cwd !== void 0 ? { cwd: config.cwd } : {}
|
|
202
|
+
});
|
|
203
|
+
const opts = config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {};
|
|
204
|
+
return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards
|
|
208
|
+
* to `callTool` on the shared client. Only the `Tool`'s name carries
|
|
209
|
+
* `name_prefix`; the call, the fallback description, and the errors use the
|
|
210
|
+
* server's own name.
|
|
211
|
+
*
|
|
212
|
+
* An already-aborted signal short-circuits before the wire call; otherwise the
|
|
213
|
+
* signal is passed through so cancelling the run cancels the remote call.
|
|
214
|
+
*/
|
|
215
|
+
function to_fascicle_tool(client, advertised, options) {
|
|
216
|
+
const name = advertised.name;
|
|
217
|
+
const description = advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`;
|
|
218
|
+
return {
|
|
219
|
+
name: `${options.name_prefix ?? ""}${name}`,
|
|
220
|
+
description,
|
|
221
|
+
input_schema: json_schema_to_standard(advertised.inputSchema),
|
|
222
|
+
execute: async (input, ctx) => {
|
|
223
|
+
if (ctx.abort.aborted) throw ctx.abort.reason instanceof Error ? ctx.abort.reason : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name });
|
|
224
|
+
return call_result_to_output(await client.callTool({
|
|
225
|
+
name,
|
|
226
|
+
arguments: is_record(input) ? input : void 0
|
|
227
|
+
}, void 0, { signal: ctx.abort }), name);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
//#region src/mcp/serve.ts
|
|
233
|
+
/**
|
|
234
|
+
* Registers a Fascicle flow as a tool on a caller-owned MCP server.
|
|
235
|
+
*
|
|
236
|
+
* Drives the flow with `run`, threading the per-request abort signal so an
|
|
237
|
+
* MCP client cancellation aborts the in-flight flow, and maps the result
|
|
238
|
+
* into a `CallToolResult`. A thrown flow becomes an `isError` result rather
|
|
239
|
+
* than a JSON-RPC protocol error.
|
|
240
|
+
*/
|
|
241
|
+
function serve_flow(config) {
|
|
242
|
+
const { server, flow, name, description, input_schema, trajectory, to_result } = config;
|
|
243
|
+
server.registerTool(name, {
|
|
244
|
+
description,
|
|
245
|
+
inputSchema: input_schema
|
|
246
|
+
}, async (input, extra) => {
|
|
247
|
+
try {
|
|
248
|
+
return output_to_call_result(await run(flow, input, {
|
|
249
|
+
install_signal_handlers: false,
|
|
250
|
+
abort: extra.signal,
|
|
251
|
+
...trajectory !== void 0 ? { trajectory } : {}
|
|
252
|
+
}), to_result);
|
|
253
|
+
} catch (err) {
|
|
254
|
+
return {
|
|
255
|
+
isError: true,
|
|
256
|
+
content: [{
|
|
257
|
+
type: "text",
|
|
258
|
+
text: err instanceof Error ? err.message : String(err)
|
|
259
|
+
}]
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
export { mcp_sdk_missing_error as i, mcp_client as n, mcp_error as r, serve_flow as t };
|
|
266
|
+
|
|
267
|
+
//# sourceMappingURL=mcp-8mKK7eDY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-8mKK7eDY.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 // Prepended, as written, to each surfaced tool's name, so two servers'\n // tools can share a call without colliding. The server is still called by\n // its own name, and `include` and `default_description` see that name too.\n name_prefix?: 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. A connection this call opened is closed again when\n * listing its tools fails.\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().catch(async (err: unknown) => {\n // A client this call connected has no other owner yet, so it closes here,\n // taking a spawned stdio server with it. The listing failure is the one\n // the caller sees, even if the close fails too.\n if (owns_client) await client.close().catch(() => undefined)\n throw err\n })\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. Only the `Tool`'s name carries\n * `name_prefix`; the call, the fallback description, and the errors use the\n * server's own name.\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: `${options.name_prefix ?? ''}${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 ServeFlowConfig<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>(config: ServeFlowConfig<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = config\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,QACA,WACe;CACf,IAAI,cAAc,KAAA,GAAW;EAC3B,MAAM,SAAS,UAAU,MAAM;EAC/B,OAAO,aAAa,OAAO,MAAM,OAAO,UAAU;CACpD;CACA,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,MAAM;CAC1D,IAAI,UAAU,MAAM,GAAG,OAAO,aAAa,UAAU,M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
-
import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
|
|
3
1
|
import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Typed errors for the MCP adapter.
|
|
7
|
-
*
|
|
8
|
-
* Listed alongside src/core/errors.ts and src/engine/errors.ts in the
|
|
9
|
-
* `no-class` rule ignores: `instanceof` branching is how callers distinguish a
|
|
10
|
-
* missing optional peer from a tool-level failure surfaced over the wire.
|
|
11
|
-
*/
|
|
12
|
-
var mcp_sdk_missing_error = class extends Error {
|
|
13
|
-
kind = "mcp_sdk_missing_error";
|
|
14
|
-
constructor(message = "@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk") {
|
|
15
|
-
super(message);
|
|
16
|
-
this.name = "mcp_sdk_missing_error";
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
var mcp_error = class extends Error {
|
|
20
|
-
kind = "mcp_error";
|
|
21
|
-
tool_name;
|
|
22
|
-
constructor(message, metadata = {}) {
|
|
23
|
-
super(message);
|
|
24
|
-
this.name = "mcp_error";
|
|
25
|
-
this.tool_name = metadata.tool_name;
|
|
26
|
-
}
|
|
27
|
-
};
|
|
28
|
-
//#endregion
|
|
29
|
-
//#region src/mcp/result_mapping.ts
|
|
30
|
-
/**
|
|
31
|
-
* Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
|
|
32
|
-
* both directions: inbound results from `mcp_client` tools, outbound results
|
|
33
|
-
* for `serve_flow`.
|
|
34
|
-
*/
|
|
35
|
-
/**
|
|
36
|
-
* Converts a remote tool's `CallToolResult` into the value a Fascicle
|
|
37
|
-
* `Tool.execute` returns.
|
|
38
|
-
*
|
|
39
|
-
* `isError: true` marks a tool-level failure, so it throws `mcp_error` rather
|
|
40
|
-
* than returning, letting the tool loop's error policy feed it back to the
|
|
41
|
-
* model. `structuredContent` is preferred over joined text parts when present;
|
|
42
|
-
* with neither, the raw `content` (or `null`) is returned.
|
|
43
|
-
*/
|
|
44
|
-
function call_result_to_output(result, tool_name) {
|
|
45
|
-
const record = as_record(result) ?? {};
|
|
46
|
-
if (record["isError"] === true) throw new mcp_error(join_text(record["content"]) ?? "MCP tool returned an error", tool_name !== void 0 ? { tool_name } : {});
|
|
47
|
-
if (is_record(record["structuredContent"])) return record["structuredContent"];
|
|
48
|
-
const text = join_text(record["content"]);
|
|
49
|
-
if (text !== void 0) return text;
|
|
50
|
-
return record["content"] ?? null;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.
|
|
54
|
-
*
|
|
55
|
-
* A `to_result` override takes precedence over the default mapping. By
|
|
56
|
-
* default, objects are emitted as both a JSON text part (every MCP host can
|
|
57
|
-
* read text) and `structuredContent` (typed hosts get the object); everything
|
|
58
|
-
* else becomes a single text part.
|
|
59
|
-
*/
|
|
60
|
-
function output_to_call_result(output, to_result) {
|
|
61
|
-
if (to_result !== void 0) {
|
|
62
|
-
const shaped = to_result(output);
|
|
63
|
-
return build_result(shaped.text, shaped.structured);
|
|
64
|
-
}
|
|
65
|
-
if (typeof output === "string") return build_result(output);
|
|
66
|
-
if (is_record(output)) return build_result(stringify(output), output);
|
|
67
|
-
if (Array.isArray(output)) return build_result(stringify(output));
|
|
68
|
-
return build_result(String(output));
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Assembles a `CallToolResult` with one text part and, when given, structured
|
|
72
|
-
* content.
|
|
73
|
-
*/
|
|
74
|
-
function build_result(text, structured) {
|
|
75
|
-
return structured !== void 0 ? {
|
|
76
|
-
content: [{
|
|
77
|
-
type: "text",
|
|
78
|
-
text
|
|
79
|
-
}],
|
|
80
|
-
structuredContent: structured
|
|
81
|
-
} : { content: [{
|
|
82
|
-
type: "text",
|
|
83
|
-
text
|
|
84
|
-
}] };
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Joins the `text` parts of an MCP content array with newlines, skipping
|
|
88
|
-
* non-text parts; `undefined` when there is nothing to join.
|
|
89
|
-
*/
|
|
90
|
-
function join_text(content) {
|
|
91
|
-
if (!Array.isArray(content)) return void 0;
|
|
92
|
-
const parts = [];
|
|
93
|
-
for (const part of content) if (is_record(part) && part["type"] === "text" && typeof part["text"] === "string") parts.push(part["text"]);
|
|
94
|
-
return parts.length > 0 ? parts.join("\n") : void 0;
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* `JSON.stringify` that falls back to `String` instead of throwing on
|
|
98
|
-
* unserializable values (circular references, BigInt).
|
|
99
|
-
*/
|
|
100
|
-
function stringify(value) {
|
|
101
|
-
try {
|
|
102
|
-
return JSON.stringify(value);
|
|
103
|
-
} catch {
|
|
104
|
-
return String(value);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
//#endregion
|
|
108
|
-
//#region src/mcp/sdk_loader.ts
|
|
109
|
-
/**
|
|
110
|
-
* Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
|
|
111
|
-
*
|
|
112
|
-
* `mcp_client` needs SDK values (the Client and transport constructors), so it
|
|
113
|
-
* imports them dynamically rather than statically: a consumer can import
|
|
114
|
-
* `fascicle/mcp` without the SDK installed and only pays the cost when they
|
|
115
|
-
* actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`
|
|
116
|
-
* with install guidance, mirroring the engine's `load_optional_peer`.
|
|
117
|
-
*
|
|
118
|
-
* `serve_flow` is not covered here: it operates on a caller-constructed
|
|
119
|
-
* `McpServer`, so it needs only a type-only import and no runtime SDK load.
|
|
120
|
-
*/
|
|
121
|
-
/**
|
|
122
|
-
* Dynamically imports the `@modelcontextprotocol/sdk` client modules,
|
|
123
|
-
* throwing a typed `mcp_sdk_missing_error` when the optional peer is not
|
|
124
|
-
* installed.
|
|
125
|
-
*/
|
|
126
|
-
async function load_client_sdk() {
|
|
127
|
-
try {
|
|
128
|
-
const [client_mod, stdio_mod, http_mod] = await Promise.all([
|
|
129
|
-
import("@modelcontextprotocol/sdk/client/index.js"),
|
|
130
|
-
import("@modelcontextprotocol/sdk/client/stdio.js"),
|
|
131
|
-
import("@modelcontextprotocol/sdk/client/streamableHttp.js")
|
|
132
|
-
]);
|
|
133
|
-
return {
|
|
134
|
-
Client: client_mod.Client,
|
|
135
|
-
StdioClientTransport: stdio_mod.StdioClientTransport,
|
|
136
|
-
StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport
|
|
137
|
-
};
|
|
138
|
-
} catch (err) {
|
|
139
|
-
throw new mcp_sdk_missing_error(`@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${err instanceof Error ? err.message : String(err)})`);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region src/mcp/client.ts
|
|
144
|
-
const DEFAULT_CLIENT_INFO = {
|
|
145
|
-
name: "fascicle",
|
|
146
|
-
version: "0.0.0"
|
|
147
|
-
};
|
|
148
|
-
/**
|
|
149
|
-
* Connects to an MCP server and surfaces its advertised tools as Fascicle
|
|
150
|
-
* `Tool[]`, plus a `close` handle for the connection.
|
|
151
|
-
*
|
|
152
|
-
* Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
|
|
153
|
-
* do not have to import SDK transport classes themselves. Each advertised MCP
|
|
154
|
-
* tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`
|
|
155
|
-
* the loop validates against and the provider receives back unchanged, and
|
|
156
|
-
* `execute` forwards to `callTool`, propagating the run's abort signal. For the
|
|
157
|
-
* `client` transport variant the caller keeps ownership of the connection, so
|
|
158
|
-
* `close` is a no-op. A connection this call opened is closed again when
|
|
159
|
-
* listing its tools fails.
|
|
160
|
-
*/
|
|
161
|
-
async function mcp_client(config, options = {}) {
|
|
162
|
-
const owns_client = config.transport !== "client";
|
|
163
|
-
const client = await connect_client(config, options);
|
|
164
|
-
const include = options.include !== void 0 ? new Set(options.include) : void 0;
|
|
165
|
-
const listed = await client.listTools().catch(async (err) => {
|
|
166
|
-
if (owns_client) await client.close().catch(() => void 0);
|
|
167
|
-
throw err;
|
|
168
|
-
});
|
|
169
|
-
const tools = [];
|
|
170
|
-
for (const advertised of listed.tools) {
|
|
171
|
-
if (include !== void 0 && !include.has(advertised.name)) continue;
|
|
172
|
-
tools.push(to_fascicle_tool(client, advertised, options));
|
|
173
|
-
}
|
|
174
|
-
return {
|
|
175
|
-
tools,
|
|
176
|
-
close: async () => {
|
|
177
|
-
if (owns_client) await client.close();
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Returns the caller's already-connected client as-is, or lazily loads the
|
|
183
|
-
* SDK and connects a fresh client over the configured transport.
|
|
184
|
-
*/
|
|
185
|
-
async function connect_client(config, options) {
|
|
186
|
-
if (config.transport === "client") return config.client;
|
|
187
|
-
const sdk = await load_client_sdk();
|
|
188
|
-
const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO);
|
|
189
|
-
await client.connect(build_transport(sdk, config));
|
|
190
|
-
return client;
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* Constructs the SDK transport matching the config: a spawned child process
|
|
194
|
-
* for `stdio`, a Streamable HTTP connection for `http`.
|
|
195
|
-
*/
|
|
196
|
-
function build_transport(sdk, config) {
|
|
197
|
-
if (config.transport === "stdio") return new sdk.StdioClientTransport({
|
|
198
|
-
command: config.command,
|
|
199
|
-
...config.args !== void 0 ? { args: config.args } : {},
|
|
200
|
-
...config.env !== void 0 ? { env: config.env } : {},
|
|
201
|
-
...config.cwd !== void 0 ? { cwd: config.cwd } : {}
|
|
202
|
-
});
|
|
203
|
-
const opts = config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {};
|
|
204
|
-
return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts);
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards
|
|
208
|
-
* to `callTool` on the shared client. Only the `Tool`'s name carries
|
|
209
|
-
* `name_prefix`; the call, the fallback description, and the errors use the
|
|
210
|
-
* server's own name.
|
|
211
|
-
*
|
|
212
|
-
* An already-aborted signal short-circuits before the wire call; otherwise the
|
|
213
|
-
* signal is passed through so cancelling the run cancels the remote call.
|
|
214
|
-
*/
|
|
215
|
-
function to_fascicle_tool(client, advertised, options) {
|
|
216
|
-
const name = advertised.name;
|
|
217
|
-
const description = advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`;
|
|
218
|
-
return {
|
|
219
|
-
name: `${options.name_prefix ?? ""}${name}`,
|
|
220
|
-
description,
|
|
221
|
-
input_schema: json_schema_to_standard(advertised.inputSchema),
|
|
222
|
-
execute: async (input, ctx) => {
|
|
223
|
-
if (ctx.abort.aborted) throw ctx.abort.reason instanceof Error ? ctx.abort.reason : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name });
|
|
224
|
-
return call_result_to_output(await client.callTool({
|
|
225
|
-
name,
|
|
226
|
-
arguments: is_record(input) ? input : void 0
|
|
227
|
-
}, void 0, { signal: ctx.abort }), name);
|
|
228
|
-
}
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
//#endregion
|
|
232
|
-
//#region src/mcp/serve.ts
|
|
233
|
-
/**
|
|
234
|
-
* Registers a Fascicle flow as a tool on a caller-owned MCP server.
|
|
235
|
-
*
|
|
236
|
-
* Drives the flow with `run`, threading the per-request abort signal so an
|
|
237
|
-
* MCP client cancellation aborts the in-flight flow, and maps the result
|
|
238
|
-
* into a `CallToolResult`. A thrown flow becomes an `isError` result rather
|
|
239
|
-
* than a JSON-RPC protocol error.
|
|
240
|
-
*/
|
|
241
|
-
function serve_flow(config) {
|
|
242
|
-
const { server, flow, name, description, input_schema, trajectory, to_result } = config;
|
|
243
|
-
server.registerTool(name, {
|
|
244
|
-
description,
|
|
245
|
-
inputSchema: input_schema
|
|
246
|
-
}, async (input, extra) => {
|
|
247
|
-
try {
|
|
248
|
-
return output_to_call_result(await run(flow, input, {
|
|
249
|
-
install_signal_handlers: false,
|
|
250
|
-
abort: extra.signal,
|
|
251
|
-
...trajectory !== void 0 ? { trajectory } : {}
|
|
252
|
-
}), to_result);
|
|
253
|
-
} catch (err) {
|
|
254
|
-
return {
|
|
255
|
-
isError: true,
|
|
256
|
-
content: [{
|
|
257
|
-
type: "text",
|
|
258
|
-
text: err instanceof Error ? err.message : String(err)
|
|
259
|
-
}]
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
//#endregion
|
|
2
|
+
import { i as mcp_sdk_missing_error, n as mcp_client, r as mcp_error, t as serve_flow } from "./mcp-8mKK7eDY.js";
|
|
265
3
|
export { json_schema_to_standard, mcp_client, mcp_error, mcp_sdk_missing_error, serve_flow };
|
|
266
|
-
|
|
267
|
-
//# sourceMappingURL=mcp.js.map
|
package/dist/testing.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as validate_schema, S as format_schema_issues, j as aborted_error } from "./core-Bfzt55Fl.js";
|
|
2
|
-
import { n as to_json_schema, t as create_engine } from "./engine-
|
|
3
|
-
import {
|
|
2
|
+
import { n as to_json_schema, t as create_engine } from "./engine-BTijBDlY.js";
|
|
3
|
+
import { I as schema_validation_error } from "./leading_system-CHSYz0h9.js";
|
|
4
4
|
//#region src/testing/assert_prefix_stable.ts
|
|
5
5
|
const ONE_AT_A_TIME = "the check reads calls that ran one at a time, so a parallel flow takes one double per branch";
|
|
6
6
|
/** A tool list as its names, in order, the way a message prints it. */
|