fascicle 0.18.1 → 0.19.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.
- package/CHANGELOG.md +59 -0
- package/README.md +27 -1
- package/dist/AGENTS.md +11 -10
- package/dist/a2a.d.ts +358 -0
- package/dist/a2a.js +2234 -0
- package/dist/a2a.js.map +1 -0
- package/dist/acp.d.ts +120 -9
- package/dist/acp.js +927 -154
- package/dist/acp.js.map +1 -1
- package/dist/adapters-DYFauXE1.js +1147 -0
- package/dist/adapters-DYFauXE1.js.map +1 -0
- package/dist/adapters.d.ts +124 -36
- package/dist/adapters.js +1 -1
- package/dist/agents.d.ts +2 -2
- package/dist/agents.js +1 -1
- package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
- package/dist/core-xTtRZqdb.js.map +1 -0
- package/dist/diagram_bin.js +1 -1
- package/dist/durable-CgU0kO2H.d.ts +144 -0
- package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
- package/dist/engine-B_Yl7acj.js.map +1 -0
- package/dist/index.d.ts +9 -136
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
- package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
- package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
- package/dist/leading_system-m-x7HzbQ.js.map +1 -0
- package/dist/mcp-D1hN5ywq.js +662 -0
- package/dist/mcp-D1hN5ywq.js.map +1 -0
- package/dist/mcp.d.ts +115 -5
- package/dist/mcp.js +2 -2
- package/dist/otel.d.ts +1 -1
- package/dist/stdio.d.ts +1 -1
- package/dist/stdio.js +2 -2
- package/dist/testing.d.ts +7 -5
- package/dist/testing.js +618 -318
- package/dist/testing.js.map +1 -1
- package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
- package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
- package/dist/ui.d.ts +2 -2
- package/dist/viewer.js +2 -2
- package/dist/web.d.ts +1 -1
- package/package.json +17 -5
- package/dist/adapters-CpKpDk7r.js +0 -461
- package/dist/adapters-CpKpDk7r.js.map +0 -1
- package/dist/core-BH7sWpEG.js.map +0 -1
- package/dist/engine-fOjYHcv6.js.map +0 -1
- package/dist/leading_system-BeQUSAim.js.map +0 -1
- package/dist/mcp-CHJ88HiG.js +0 -262
- package/dist/mcp-CHJ88HiG.js.map +0 -1
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
import { n as is_record, t as as_record } from "./records-Btlmvunj.js";
|
|
2
|
+
import { t as json_schema_to_standard } from "./json_schema_to_standard-BstoXjM8.js";
|
|
3
|
+
import { w as run } from "./core-xTtRZqdb.js";
|
|
4
|
+
// 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, and
|
|
11
|
+
* either of those from a server that wants credentials.
|
|
12
|
+
*/
|
|
13
|
+
var mcp_sdk_missing_error = class extends Error {
|
|
14
|
+
kind = "mcp_sdk_missing_error";
|
|
15
|
+
constructor(message = "@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk") {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "mcp_sdk_missing_error";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var mcp_error = class extends Error {
|
|
21
|
+
kind = "mcp_error";
|
|
22
|
+
tool_name;
|
|
23
|
+
constructor(message, metadata = {}) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = "mcp_error";
|
|
26
|
+
this.tool_name = metadata.tool_name;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* An HTTP MCP server answered that the caller isn't authorized, while
|
|
31
|
+
* connecting or on a later request once a token has expired. `url` is the
|
|
32
|
+
* server's address without its query string or any credentials written into
|
|
33
|
+
* it, and `cause` is the SDK's own error.
|
|
34
|
+
*/
|
|
35
|
+
var mcp_auth_required_error = class extends Error {
|
|
36
|
+
kind = "mcp_auth_required_error";
|
|
37
|
+
url;
|
|
38
|
+
constructor(url, cause) {
|
|
39
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
40
|
+
super(`MCP server at ${url} requires authorization (${detail}): pass \`auth_provider\` in the http config with a token the server accepts, or finish an interactive OAuth flow on a transport of your own and pass its client as \`transport: 'client'\``, { cause });
|
|
41
|
+
this.name = "mcp_auth_required_error";
|
|
42
|
+
this.url = url;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
// src/mcp/sdk_loader.ts
|
|
46
|
+
/**
|
|
47
|
+
* Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
|
|
48
|
+
*
|
|
49
|
+
* `mcp_client` needs SDK values (the Client and transport constructors, and
|
|
50
|
+
* the error classes it tells an auth failure by, the schemas a handler is
|
|
51
|
+
* registered under), so it imports them dynamically rather than statically: a consumer can import
|
|
52
|
+
* `fascicle/mcp` without the SDK installed and only pays the cost when they
|
|
53
|
+
* actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`
|
|
54
|
+
* with install guidance, mirroring the engine's `load_optional_peer`.
|
|
55
|
+
*
|
|
56
|
+
* `serve_flow` is not covered here: it operates on a caller-constructed
|
|
57
|
+
* `McpServer`, so it needs only a type-only import and no runtime SDK load.
|
|
58
|
+
*/
|
|
59
|
+
/**
|
|
60
|
+
* Dynamically imports the `@modelcontextprotocol/sdk` client modules,
|
|
61
|
+
* throwing a typed `mcp_sdk_missing_error` when the optional peer is not
|
|
62
|
+
* installed.
|
|
63
|
+
*/
|
|
64
|
+
async function load_client_sdk() {
|
|
65
|
+
try {
|
|
66
|
+
const [client_mod, stdio_mod, http_mod, auth_mod, types_mod] = await Promise.all([
|
|
67
|
+
import("@modelcontextprotocol/sdk/client/index.js"),
|
|
68
|
+
import("@modelcontextprotocol/sdk/client/stdio.js"),
|
|
69
|
+
import("@modelcontextprotocol/sdk/client/streamableHttp.js"),
|
|
70
|
+
import("@modelcontextprotocol/sdk/client/auth.js"),
|
|
71
|
+
import("@modelcontextprotocol/sdk/types.js")
|
|
72
|
+
]);
|
|
73
|
+
return {
|
|
74
|
+
Client: client_mod.Client,
|
|
75
|
+
StdioClientTransport: stdio_mod.StdioClientTransport,
|
|
76
|
+
StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport,
|
|
77
|
+
StreamableHTTPError: http_mod.StreamableHTTPError,
|
|
78
|
+
UnauthorizedError: auth_mod.UnauthorizedError,
|
|
79
|
+
McpError: types_mod.McpError,
|
|
80
|
+
CreateMessageRequestSchema: types_mod.CreateMessageRequestSchema,
|
|
81
|
+
ResourceUpdatedNotificationSchema: types_mod.ResourceUpdatedNotificationSchema,
|
|
82
|
+
ResourceListChangedNotificationSchema: types_mod.ResourceListChangedNotificationSchema
|
|
83
|
+
};
|
|
84
|
+
} catch (err) {
|
|
85
|
+
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)})`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// src/mcp/resources.ts
|
|
89
|
+
const REMEDIES = {
|
|
90
|
+
resources: "connect to a server that lists `resources` among its capabilities",
|
|
91
|
+
subscribe: "call resources.read when you need the current content",
|
|
92
|
+
listChanged: "call resources.list when you need the current listing"
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Builds the `resources` namespace of an `mcp_client` handle over a connected
|
|
96
|
+
* client.
|
|
97
|
+
*
|
|
98
|
+
* Nothing is registered on the client until the first `subscribe` or
|
|
99
|
+
* `on_list_changed`, so a caller who only wants tools pays nothing for this.
|
|
100
|
+
* Every failed request goes through `translate`, which is how an expired
|
|
101
|
+
* token on an HTTP connection reads the same here as it does on a tool call.
|
|
102
|
+
*/
|
|
103
|
+
function create_resources(client, translate) {
|
|
104
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
105
|
+
const list_listeners = /* @__PURE__ */ new Set();
|
|
106
|
+
let update_handler;
|
|
107
|
+
let list_handler;
|
|
108
|
+
const request = async (send) => send().catch((err) => {
|
|
109
|
+
throw translate(err);
|
|
110
|
+
});
|
|
111
|
+
const listen_for_updates = async () => {
|
|
112
|
+
update_handler ??= load_client_sdk().then((sdk) => {
|
|
113
|
+
client.setNotificationHandler(sdk.ResourceUpdatedNotificationSchema, (notification) => {
|
|
114
|
+
const uri = notification.params.uri;
|
|
115
|
+
notify_all(subscriptions.get(uri)?.callbacks ?? [], (on_update) => on_update(uri));
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
return update_handler;
|
|
119
|
+
};
|
|
120
|
+
const listen_for_list_changes = async () => {
|
|
121
|
+
list_handler ??= load_client_sdk().then((sdk) => {
|
|
122
|
+
client.setNotificationHandler(sdk.ResourceListChangedNotificationSchema, () => {
|
|
123
|
+
notify_all(list_listeners, (on_change) => on_change());
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
return list_handler;
|
|
127
|
+
};
|
|
128
|
+
return {
|
|
129
|
+
list: async () => {
|
|
130
|
+
require_capability(client, "resources", "resources.list");
|
|
131
|
+
const found = [];
|
|
132
|
+
let cursor;
|
|
133
|
+
do {
|
|
134
|
+
const params = cursor !== void 0 ? { cursor } : void 0;
|
|
135
|
+
const page = await request(() => client.listResources(params));
|
|
136
|
+
for (const resource of page.resources) found.push({
|
|
137
|
+
uri: resource.uri,
|
|
138
|
+
name: resource.name,
|
|
139
|
+
...described(resource)
|
|
140
|
+
});
|
|
141
|
+
cursor = page.nextCursor;
|
|
142
|
+
} while (cursor !== void 0);
|
|
143
|
+
return found;
|
|
144
|
+
},
|
|
145
|
+
templates: async () => {
|
|
146
|
+
require_capability(client, "resources", "resources.templates");
|
|
147
|
+
const found = [];
|
|
148
|
+
let cursor;
|
|
149
|
+
do {
|
|
150
|
+
const params = cursor !== void 0 ? { cursor } : void 0;
|
|
151
|
+
const page = await request(() => client.listResourceTemplates(params));
|
|
152
|
+
for (const template of page.resourceTemplates) found.push({
|
|
153
|
+
uri_template: template.uriTemplate,
|
|
154
|
+
name: template.name,
|
|
155
|
+
...described(template)
|
|
156
|
+
});
|
|
157
|
+
cursor = page.nextCursor;
|
|
158
|
+
} while (cursor !== void 0);
|
|
159
|
+
return found;
|
|
160
|
+
},
|
|
161
|
+
read: async (uri) => {
|
|
162
|
+
require_capability(client, "resources", "resources.read");
|
|
163
|
+
return (await request(() => client.readResource({ uri }))).contents.map((part) => ({
|
|
164
|
+
uri: part.uri,
|
|
165
|
+
...part.mimeType !== void 0 ? { mime_type: part.mimeType } : {},
|
|
166
|
+
..."text" in part ? { text: part.text } : { blob: part.blob }
|
|
167
|
+
}));
|
|
168
|
+
},
|
|
169
|
+
subscribe: async (uri, on_update) => {
|
|
170
|
+
require_capability(client, "subscribe", "resources.subscribe");
|
|
171
|
+
await listen_for_updates();
|
|
172
|
+
const existing = subscriptions.get(uri);
|
|
173
|
+
if (existing !== void 0) {
|
|
174
|
+
existing.callbacks.add(on_update);
|
|
175
|
+
return existing.ready;
|
|
176
|
+
}
|
|
177
|
+
const subscription = {
|
|
178
|
+
callbacks: /* @__PURE__ */ new Set([on_update]),
|
|
179
|
+
ready: request(async () => {
|
|
180
|
+
await client.subscribeResource({ uri });
|
|
181
|
+
})
|
|
182
|
+
};
|
|
183
|
+
subscriptions.set(uri, subscription);
|
|
184
|
+
return subscription.ready.catch((err) => {
|
|
185
|
+
if (subscriptions.get(uri) === subscription) subscriptions.delete(uri);
|
|
186
|
+
throw err;
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
unsubscribe: async (uri) => {
|
|
190
|
+
if (!subscriptions.delete(uri)) return;
|
|
191
|
+
await request(() => client.unsubscribeResource({ uri }));
|
|
192
|
+
},
|
|
193
|
+
on_list_changed: async (on_change) => {
|
|
194
|
+
require_capability(client, "listChanged", "resources.on_list_changed");
|
|
195
|
+
await listen_for_list_changes();
|
|
196
|
+
list_listeners.add(on_change);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Throws `mcp_error` when the server's handshake left out the capability a
|
|
202
|
+
* resources call depends on.
|
|
203
|
+
*
|
|
204
|
+
* The SDK sends the request regardless, and the server's refusal comes back
|
|
205
|
+
* as a bare JSON-RPC error (or, for a list-changed listener, as silence), so
|
|
206
|
+
* the check happens here where the message can say what is missing. A session
|
|
207
|
+
* rejoined by `session_id` skipped the handshake and has no capabilities to
|
|
208
|
+
* read, so its requests go to the server unchecked.
|
|
209
|
+
*/
|
|
210
|
+
function require_capability(client, feature, action) {
|
|
211
|
+
const capabilities = client.getServerCapabilities();
|
|
212
|
+
if (capabilities === void 0) return;
|
|
213
|
+
const resources = capabilities.resources;
|
|
214
|
+
if (resources === void 0) throw new mcp_error(`MCP server does not advertise the \`resources\` capability, so ${action} has nothing to ask it: ${REMEDIES.resources}`);
|
|
215
|
+
if (feature === "resources" || resources[feature] === true) return;
|
|
216
|
+
throw new mcp_error(`MCP server does not advertise the \`resources.${feature}\` capability, so ${action} would never hear from it: ${REMEDIES[feature]}`);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The optional fields a resource and a resource template share, under
|
|
220
|
+
* Fascicle's names and absent when the server sent none.
|
|
221
|
+
*/
|
|
222
|
+
function described(entry) {
|
|
223
|
+
return {
|
|
224
|
+
...entry.description !== void 0 ? { description: entry.description } : {},
|
|
225
|
+
...entry.mimeType !== void 0 ? { mime_type: entry.mimeType } : {}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Calls every callback, then rethrows the first failure.
|
|
230
|
+
*
|
|
231
|
+
* One subscriber that throws does not keep the rest from hearing the
|
|
232
|
+
* notification. The rethrown failure lands in the SDK's notification
|
|
233
|
+
* dispatch, which hands it to the client's `onerror`.
|
|
234
|
+
*/
|
|
235
|
+
function notify_all(callbacks, call) {
|
|
236
|
+
const failures = [];
|
|
237
|
+
for (const callback of callbacks) try {
|
|
238
|
+
call(callback);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
failures.push(err);
|
|
241
|
+
}
|
|
242
|
+
if (failures.length > 0) throw failures[0];
|
|
243
|
+
}
|
|
244
|
+
// src/mcp/result_mapping.ts
|
|
245
|
+
/**
|
|
246
|
+
* Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
|
|
247
|
+
* both directions: inbound results from `mcp_client` tools, outbound results
|
|
248
|
+
* for `serve_flow`.
|
|
249
|
+
*/
|
|
250
|
+
/**
|
|
251
|
+
* Converts a remote tool's `CallToolResult` into the value a Fascicle
|
|
252
|
+
* `Tool.execute` returns.
|
|
253
|
+
*
|
|
254
|
+
* `isError: true` marks a tool-level failure, so it throws `mcp_error` rather
|
|
255
|
+
* than returning, letting the tool loop's error policy feed it back to the
|
|
256
|
+
* model. `structuredContent` is preferred over joined text parts when present;
|
|
257
|
+
* with neither, the raw `content` (or `null`) is returned.
|
|
258
|
+
*/
|
|
259
|
+
function call_result_to_output(result, tool_name) {
|
|
260
|
+
const record = as_record(result) ?? {};
|
|
261
|
+
if (record["isError"] === true) throw new mcp_error(join_text(record["content"]) ?? "MCP tool returned an error", tool_name !== void 0 ? { tool_name } : {});
|
|
262
|
+
if (is_record(record["structuredContent"])) return record["structuredContent"];
|
|
263
|
+
const text = join_text(record["content"]);
|
|
264
|
+
if (text !== void 0) return text;
|
|
265
|
+
return record["content"] ?? null;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.
|
|
269
|
+
*
|
|
270
|
+
* A `to_result` override takes precedence over the default mapping. By
|
|
271
|
+
* default, objects are emitted as both a JSON text part (every MCP host can
|
|
272
|
+
* read text) and `structuredContent` (typed hosts get the object); everything
|
|
273
|
+
* else becomes a single text part.
|
|
274
|
+
*/
|
|
275
|
+
function output_to_call_result(output, to_result) {
|
|
276
|
+
if (to_result !== void 0) {
|
|
277
|
+
const shaped = to_result(output);
|
|
278
|
+
return build_result(shaped.text, shaped.structured);
|
|
279
|
+
}
|
|
280
|
+
if (typeof output === "string") return build_result(output);
|
|
281
|
+
if (is_record(output)) return build_result(stringify(output), output);
|
|
282
|
+
if (Array.isArray(output)) return build_result(stringify(output));
|
|
283
|
+
return build_result(String(output));
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Assembles a `CallToolResult` with one text part and, when given, structured
|
|
287
|
+
* content.
|
|
288
|
+
*/
|
|
289
|
+
function build_result(text, structured) {
|
|
290
|
+
return structured !== void 0 ? {
|
|
291
|
+
content: [{
|
|
292
|
+
type: "text",
|
|
293
|
+
text
|
|
294
|
+
}],
|
|
295
|
+
structuredContent: structured
|
|
296
|
+
} : { content: [{
|
|
297
|
+
type: "text",
|
|
298
|
+
text
|
|
299
|
+
}] };
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Joins the `text` parts of an MCP content array with newlines, skipping
|
|
303
|
+
* non-text parts; `undefined` when there is nothing to join.
|
|
304
|
+
*/
|
|
305
|
+
function join_text(content) {
|
|
306
|
+
if (!Array.isArray(content)) return void 0;
|
|
307
|
+
const parts = [];
|
|
308
|
+
for (const part of content) if (is_record(part) && part["type"] === "text" && typeof part["text"] === "string") parts.push(part["text"]);
|
|
309
|
+
return parts.length > 0 ? parts.join("\n") : void 0;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* `JSON.stringify` that falls back to `String` instead of throwing on
|
|
313
|
+
* unserializable values (circular references, BigInt).
|
|
314
|
+
*/
|
|
315
|
+
function stringify(value) {
|
|
316
|
+
try {
|
|
317
|
+
return JSON.stringify(value);
|
|
318
|
+
} catch {
|
|
319
|
+
return String(value);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// src/mcp/sampling.ts
|
|
323
|
+
const INVALID_PARAMS = -32602;
|
|
324
|
+
const REJECTED = -1;
|
|
325
|
+
const DEFAULT_SAMPLING_MAX_TOKENS = 4096;
|
|
326
|
+
/**
|
|
327
|
+
* Registers the sampling handler on a client that declared the `sampling`
|
|
328
|
+
* capability.
|
|
329
|
+
*
|
|
330
|
+
* The SDK checks the capability when a handler is registered, and a client
|
|
331
|
+
* constructed without it throws there. For a client the caller constructed
|
|
332
|
+
* that is the caller's to fix, so the failure is rethrown as an `mcp_error`
|
|
333
|
+
* that says how.
|
|
334
|
+
*/
|
|
335
|
+
function register_sampling(sdk, client, config) {
|
|
336
|
+
const handler = create_sampling_handler(config, (code, message) => new sdk.McpError(code, message));
|
|
337
|
+
try {
|
|
338
|
+
client.setRequestHandler(sdk.CreateMessageRequestSchema, handler);
|
|
339
|
+
} catch (err) {
|
|
340
|
+
throw new mcp_error(`sampling can't be served on the client passed as \`transport: 'client'\` (${err instanceof Error ? err.message : String(err)}): construct that Client with \`capabilities: { sampling: {} }\`, or drop the \`sampling\` option`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Builds the handler that turns one `sampling/createMessage` request into one
|
|
345
|
+
* `engine.generate` call and its result.
|
|
346
|
+
*
|
|
347
|
+
* `refuse` makes the error the server is answered with when a request is
|
|
348
|
+
* declined. A request carrying `tools` or `toolChoice` is declined outright:
|
|
349
|
+
* the server would be choosing which of the host's tools run, which is the
|
|
350
|
+
* decision tool approval exists to keep with the host. `stopSequences`,
|
|
351
|
+
* `includeContext`, and `metadata` are dropped. A failure inside the engine is
|
|
352
|
+
* left to the SDK, which answers the server with the error's message.
|
|
353
|
+
*/
|
|
354
|
+
function create_sampling_handler(config, refuse) {
|
|
355
|
+
return async (request, extra) => {
|
|
356
|
+
const params = request.params;
|
|
357
|
+
if (params.tools !== void 0 || params.toolChoice !== void 0) throw refuse(INVALID_PARAMS, "sampling with tools is not supported by this client: send the request without `tools` and `toolChoice`");
|
|
358
|
+
const messages = params.messages.map((message) => to_message(message, refuse));
|
|
359
|
+
const max_tokens = Math.min(params.maxTokens, config.max_tokens ?? DEFAULT_SAMPLING_MAX_TOKENS);
|
|
360
|
+
if (!await config.on_request({
|
|
361
|
+
messages,
|
|
362
|
+
...params.systemPrompt !== void 0 ? { system: params.systemPrompt } : {},
|
|
363
|
+
max_tokens,
|
|
364
|
+
...params.modelPreferences !== void 0 ? { model_preferences: params.modelPreferences } : {}
|
|
365
|
+
})) throw refuse(REJECTED, "sampling request rejected by the client");
|
|
366
|
+
const result = await config.engine.generate({
|
|
367
|
+
model: config.model,
|
|
368
|
+
...config.provider !== void 0 ? { provider: config.provider } : {},
|
|
369
|
+
prompt: messages,
|
|
370
|
+
...params.systemPrompt !== void 0 ? { system: params.systemPrompt } : {},
|
|
371
|
+
max_tokens,
|
|
372
|
+
...params.temperature !== void 0 ? { temperature: params.temperature } : {},
|
|
373
|
+
abort: extra.signal,
|
|
374
|
+
...config.trajectory !== void 0 ? { trajectory: config.trajectory } : {}
|
|
375
|
+
});
|
|
376
|
+
return {
|
|
377
|
+
model: result.model_resolved.model_id,
|
|
378
|
+
role: "assistant",
|
|
379
|
+
content: {
|
|
380
|
+
type: "text",
|
|
381
|
+
text: result.content
|
|
382
|
+
},
|
|
383
|
+
stopReason: to_stop_reason(result.finish_reason)
|
|
384
|
+
};
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Maps the engine's finish reason onto MCP's `stopReason`. The two MCP names
|
|
389
|
+
* with an engine counterpart are translated, and any other reason goes out
|
|
390
|
+
* as the engine spelled it, which MCP allows.
|
|
391
|
+
*/
|
|
392
|
+
function to_stop_reason(finish_reason) {
|
|
393
|
+
if (finish_reason === "stop") return "endTurn";
|
|
394
|
+
if (finish_reason === "length") return "maxTokens";
|
|
395
|
+
return finish_reason;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Converts one MCP sampling message into an engine `Message`. A message that
|
|
399
|
+
* is a single text block becomes plain string content, the form every
|
|
400
|
+
* provider transport takes.
|
|
401
|
+
*/
|
|
402
|
+
function to_message(message, refuse) {
|
|
403
|
+
const blocks = Array.isArray(message.content) ? message.content : [message.content];
|
|
404
|
+
const [only] = blocks;
|
|
405
|
+
if (blocks.length === 1 && only?.type === "text") return message.role === "user" ? {
|
|
406
|
+
role: "user",
|
|
407
|
+
content: only.text
|
|
408
|
+
} : {
|
|
409
|
+
role: "assistant",
|
|
410
|
+
content: only.text
|
|
411
|
+
};
|
|
412
|
+
return message.role === "user" ? {
|
|
413
|
+
role: "user",
|
|
414
|
+
content: blocks.map((block) => to_user_part(block, refuse))
|
|
415
|
+
} : {
|
|
416
|
+
role: "assistant",
|
|
417
|
+
content: blocks.map((block) => to_assistant_part(block, refuse))
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
/** Converts one block of a user message: text, or an image as base64. */
|
|
421
|
+
function to_user_part(block, refuse) {
|
|
422
|
+
if (block.type === "text") return {
|
|
423
|
+
type: "text",
|
|
424
|
+
text: block.text
|
|
425
|
+
};
|
|
426
|
+
if (block.type === "image") return {
|
|
427
|
+
type: "image",
|
|
428
|
+
image: block.data,
|
|
429
|
+
media_type: block.mimeType
|
|
430
|
+
};
|
|
431
|
+
throw unsupported(block.type, "user", refuse);
|
|
432
|
+
}
|
|
433
|
+
/** Converts one block of an assistant message, which may only be text. */
|
|
434
|
+
function to_assistant_part(block, refuse) {
|
|
435
|
+
if (block.type === "text") return {
|
|
436
|
+
type: "text",
|
|
437
|
+
text: block.text
|
|
438
|
+
};
|
|
439
|
+
throw unsupported(block.type, "assistant", refuse);
|
|
440
|
+
}
|
|
441
|
+
/** The refusal for a content block this client has no engine shape for. */
|
|
442
|
+
function unsupported(type, role, refuse) {
|
|
443
|
+
return refuse(INVALID_PARAMS, `sampling content of type '${type}' in a ${role} message is not supported by this client: send text, or an image in a user message`);
|
|
444
|
+
}
|
|
445
|
+
// src/mcp/client.ts
|
|
446
|
+
const DEFAULT_CLIENT_INFO = {
|
|
447
|
+
name: "fascicle",
|
|
448
|
+
version: "0.0.0"
|
|
449
|
+
};
|
|
450
|
+
/**
|
|
451
|
+
* Connects to an MCP server and surfaces its advertised tools as Fascicle
|
|
452
|
+
* `Tool[]`, plus a `close` handle for the connection.
|
|
453
|
+
*
|
|
454
|
+
* Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
|
|
455
|
+
* do not have to import SDK transport classes themselves. Each advertised MCP
|
|
456
|
+
* tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`
|
|
457
|
+
* the loop validates against and the provider receives back unchanged, and
|
|
458
|
+
* `execute` forwards to `callTool`, propagating the run's abort signal. For the
|
|
459
|
+
* `client` transport variant the caller keeps ownership of the connection, so
|
|
460
|
+
* `close` is a no-op. A connection this call opened is closed again when
|
|
461
|
+
* listing its tools fails. A server that advertises no tools is not asked
|
|
462
|
+
* for any, and its handle carries an empty `tools` beside its `resources`.
|
|
463
|
+
*/
|
|
464
|
+
async function mcp_client(config, options = {}) {
|
|
465
|
+
const { client, owned, translate } = await open_connection(config, options);
|
|
466
|
+
const include = options.include !== void 0 ? new Set(options.include) : void 0;
|
|
467
|
+
const listed = advertises_no_tools(client) ? { tools: [] } : await client.listTools().catch(async (err) => {
|
|
468
|
+
if (owned) await client.close().catch(() => void 0);
|
|
469
|
+
throw translate(err);
|
|
470
|
+
});
|
|
471
|
+
const tools = [];
|
|
472
|
+
for (const advertised of listed.tools) {
|
|
473
|
+
if (include !== void 0 && !include.has(advertised.name)) continue;
|
|
474
|
+
tools.push(to_fascicle_tool(client, advertised, options, translate));
|
|
475
|
+
}
|
|
476
|
+
return {
|
|
477
|
+
tools,
|
|
478
|
+
close: async () => {
|
|
479
|
+
if (owned) await client.close();
|
|
480
|
+
},
|
|
481
|
+
resources: create_resources(client, translate)
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* True when the handshake said the server has no tools at all, as a server
|
|
486
|
+
* that only publishes resources does. Asking such a server to list its tools
|
|
487
|
+
* is answered with a JSON-RPC error, so the handle carries an empty `tools`
|
|
488
|
+
* instead. A connection with no handshake to read (a session rejoined by
|
|
489
|
+
* `session_id`) is asked.
|
|
490
|
+
*/
|
|
491
|
+
function advertises_no_tools(client) {
|
|
492
|
+
const capabilities = client.getServerCapabilities();
|
|
493
|
+
return capabilities !== void 0 && capabilities.tools === void 0;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Returns the caller's already-connected client as-is, or lazily loads the
|
|
497
|
+
* SDK and connects a fresh client over the configured transport.
|
|
498
|
+
*
|
|
499
|
+
* An `http` connection carries a translator that turns the SDK's auth
|
|
500
|
+
* failures into `mcp_auth_required_error`, for the handshake and for every
|
|
501
|
+
* later request. A client the caller connected keeps the SDK's errors as they
|
|
502
|
+
* are, since the caller built its transport and already holds the SDK.
|
|
503
|
+
*
|
|
504
|
+
* With `sampling` set, a fresh client declares the capability and has its
|
|
505
|
+
* handler in place before it connects. A client the caller connected gets
|
|
506
|
+
* the handler only, since its capabilities were declared when it was built.
|
|
507
|
+
*/
|
|
508
|
+
async function open_connection(config, options) {
|
|
509
|
+
const sampling = options.sampling;
|
|
510
|
+
if (config.transport === "client") {
|
|
511
|
+
if (sampling !== void 0) register_sampling(await load_client_sdk(), config.client, sampling);
|
|
512
|
+
return {
|
|
513
|
+
client: config.client,
|
|
514
|
+
owned: false,
|
|
515
|
+
translate: same_error
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
const sdk = await load_client_sdk();
|
|
519
|
+
const translate = config.transport === "http" ? auth_translator(sdk, config.url) : same_error;
|
|
520
|
+
const info = options.client_info ?? DEFAULT_CLIENT_INFO;
|
|
521
|
+
const client = sampling !== void 0 ? new sdk.Client(info, { capabilities: { sampling: {} } }) : new sdk.Client(info);
|
|
522
|
+
if (sampling !== void 0) register_sampling(sdk, client, sampling);
|
|
523
|
+
await client.connect(build_transport(sdk, config)).catch((err) => {
|
|
524
|
+
throw translate(err);
|
|
525
|
+
});
|
|
526
|
+
return {
|
|
527
|
+
client,
|
|
528
|
+
owned: true,
|
|
529
|
+
translate
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
/** The translator for a connection whose errors pass through untouched. */
|
|
533
|
+
function same_error(err) {
|
|
534
|
+
return err;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Builds the translator for one HTTP server: an auth failure becomes
|
|
538
|
+
* `mcp_auth_required_error`, and anything else passes through.
|
|
539
|
+
*
|
|
540
|
+
* The SDK reports an auth failure two ways. With an `authProvider` whose
|
|
541
|
+
* flow ends short of a usable token it throws `UnauthorizedError`, from the
|
|
542
|
+
* handshake or from any later request. With no provider, or when the server
|
|
543
|
+
* still answers 401 to a fresh token, the POST fails as a
|
|
544
|
+
* `StreamableHTTPError` whose `code` is 401. The error names the server by
|
|
545
|
+
* origin and path only, since a query string or userinfo can hold a secret.
|
|
546
|
+
*/
|
|
547
|
+
function auth_translator(sdk, url) {
|
|
548
|
+
const parsed = new URL(url);
|
|
549
|
+
const shown = `${parsed.origin}${parsed.pathname}`;
|
|
550
|
+
return (err) => {
|
|
551
|
+
return err instanceof sdk.UnauthorizedError || err instanceof sdk.StreamableHTTPError && err.code === 401 ? new mcp_auth_required_error(shown, err) : err;
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Constructs the SDK transport matching the config: a spawned child process
|
|
556
|
+
* for `stdio`, a Streamable HTTP connection for `http`. Each option reaches
|
|
557
|
+
* the SDK only when the config sets it, so the SDK's own defaults hold for
|
|
558
|
+
* the rest.
|
|
559
|
+
*/
|
|
560
|
+
function build_transport(sdk, config) {
|
|
561
|
+
if (config.transport === "stdio") return new sdk.StdioClientTransport({
|
|
562
|
+
command: config.command,
|
|
563
|
+
...config.args !== void 0 ? { args: config.args } : {},
|
|
564
|
+
...config.env !== void 0 ? { env: config.env } : {},
|
|
565
|
+
...config.cwd !== void 0 ? { cwd: config.cwd } : {}
|
|
566
|
+
});
|
|
567
|
+
const reconnection = config.reconnection;
|
|
568
|
+
return new sdk.StreamableHTTPClientTransport(new URL(config.url), {
|
|
569
|
+
...config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {},
|
|
570
|
+
...config.auth_provider !== void 0 ? { authProvider: config.auth_provider } : {},
|
|
571
|
+
...config.fetch !== void 0 ? { fetch: config.fetch } : {},
|
|
572
|
+
...config.session_id !== void 0 ? { sessionId: config.session_id } : {},
|
|
573
|
+
...reconnection !== void 0 ? { reconnectionOptions: {
|
|
574
|
+
maxRetries: reconnection.max_retries,
|
|
575
|
+
initialReconnectionDelay: reconnection.initial_delay_ms,
|
|
576
|
+
maxReconnectionDelay: reconnection.max_delay_ms,
|
|
577
|
+
reconnectionDelayGrowFactor: reconnection.delay_grow_factor
|
|
578
|
+
} } : {}
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Settles the approval policy for one advertised tool into the value its
|
|
583
|
+
* `Tool.needs_approval` carries, or undefined when no policy is set.
|
|
584
|
+
*
|
|
585
|
+
* A function policy runs here, once, with the server's own name for the tool
|
|
586
|
+
* and the annotations it advertised. Nothing in this module reads the
|
|
587
|
+
* annotations: they are the server's claims about itself, and whether to
|
|
588
|
+
* believe them is the policy's decision.
|
|
589
|
+
*/
|
|
590
|
+
function resolve_needs_approval(policy, advertised) {
|
|
591
|
+
if (typeof policy !== "function") return policy;
|
|
592
|
+
return policy({
|
|
593
|
+
name: advertised.name,
|
|
594
|
+
...advertised.annotations !== void 0 ? { annotations: advertised.annotations } : {}
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards
|
|
599
|
+
* to `callTool` on the shared client. Only the `Tool`'s name carries
|
|
600
|
+
* `name_prefix`; the call, the fallback description, and the errors use the
|
|
601
|
+
* server's own name.
|
|
602
|
+
*
|
|
603
|
+
* An already-aborted signal short-circuits before the wire call; otherwise the
|
|
604
|
+
* signal is passed through so cancelling the run cancels the remote call. A
|
|
605
|
+
* failed call goes through `translate`, so a token that expired mid-session
|
|
606
|
+
* reads the same as one that was refused at connect.
|
|
607
|
+
*/
|
|
608
|
+
function to_fascicle_tool(client, advertised, options, translate) {
|
|
609
|
+
const name = advertised.name;
|
|
610
|
+
const description = advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`;
|
|
611
|
+
const needs_approval = resolve_needs_approval(options.needs_approval, advertised);
|
|
612
|
+
return {
|
|
613
|
+
name: `${options.name_prefix ?? ""}${name}`,
|
|
614
|
+
description,
|
|
615
|
+
input_schema: json_schema_to_standard(advertised.inputSchema),
|
|
616
|
+
...needs_approval !== void 0 ? { needs_approval } : {},
|
|
617
|
+
execute: async (input, ctx) => {
|
|
618
|
+
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 });
|
|
619
|
+
return call_result_to_output(await client.callTool({
|
|
620
|
+
name,
|
|
621
|
+
arguments: is_record(input) ? input : void 0
|
|
622
|
+
}, void 0, { signal: ctx.abort }).catch((err) => {
|
|
623
|
+
throw translate(err);
|
|
624
|
+
}), name);
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
// src/mcp/serve.ts
|
|
629
|
+
/**
|
|
630
|
+
* Registers a Fascicle flow as a tool on a caller-owned MCP server.
|
|
631
|
+
*
|
|
632
|
+
* Drives the flow with `run`, threading the per-request abort signal so an
|
|
633
|
+
* MCP client cancellation aborts the in-flight flow, and maps the result
|
|
634
|
+
* into a `CallToolResult`. A thrown flow becomes an `isError` result rather
|
|
635
|
+
* than a JSON-RPC protocol error.
|
|
636
|
+
*/
|
|
637
|
+
function serve_flow(config) {
|
|
638
|
+
const { server, flow, name, description, input_schema, trajectory, to_result } = config;
|
|
639
|
+
server.registerTool(name, {
|
|
640
|
+
description,
|
|
641
|
+
inputSchema: input_schema
|
|
642
|
+
}, async (input, extra) => {
|
|
643
|
+
try {
|
|
644
|
+
return output_to_call_result(await run(flow, input, {
|
|
645
|
+
install_signal_handlers: false,
|
|
646
|
+
abort: extra.signal,
|
|
647
|
+
...trajectory !== void 0 ? { trajectory } : {}
|
|
648
|
+
}), to_result);
|
|
649
|
+
} catch (err) {
|
|
650
|
+
return {
|
|
651
|
+
isError: true,
|
|
652
|
+
content: [{
|
|
653
|
+
type: "text",
|
|
654
|
+
text: err instanceof Error ? err.message : String(err)
|
|
655
|
+
}]
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
export { mcp_sdk_missing_error as a, mcp_error as i, mcp_client as n, mcp_auth_required_error as r, serve_flow as t };
|
|
661
|
+
|
|
662
|
+
//# sourceMappingURL=mcp-D1hN5ywq.js.map
|