fascicle 0.9.8 → 0.9.10
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 +31 -0
- package/dist/{adapters-Dbx3M8m-.js → adapters-CJnu1687.js} +44 -5
- package/dist/adapters-CJnu1687.js.map +1 -0
- package/dist/adapters.d.ts +26 -1
- package/dist/adapters.js +1 -1
- package/dist/agents.d.ts +10 -2
- package/dist/agents.js +35 -3
- package/dist/agents.js.map +1 -1
- package/dist/{core-CYpxskeT.js → core-DNH8ddMT.js} +340 -45
- package/dist/core-DNH8ddMT.js.map +1 -0
- package/dist/{index-DyjXGal_.d.ts → index-Bfjpd_3o.d.ts} +33 -18
- package/dist/{index-JhJahQNi.d.ts → index-SkPG_Rew.d.ts} +140 -5
- package/dist/index.d.ts +186 -2
- package/dist/index.js +1438 -276
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +28 -2
- package/dist/mcp.js +136 -11
- package/dist/mcp.js.map +1 -1
- package/dist/otel.d.ts +8 -1
- package/dist/otel.js +29 -4
- package/dist/otel.js.map +1 -1
- package/dist/stdio.d.ts +18 -1
- package/dist/stdio.js +53 -2
- package/dist/stdio.js.map +1 -1
- package/dist/ui.d.ts +12 -2
- package/dist/ui.js +39 -2
- package/dist/ui.js.map +1 -1
- package/package.json +10 -7
- package/dist/adapters-Dbx3M8m-.js.map +0 -1
- package/dist/core-CYpxskeT.js.map +0 -1
package/dist/mcp.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as Step, J as TrajectoryLogger } from "./index-
|
|
2
|
-
import { R as Tool } from "./index-
|
|
1
|
+
import { G as Step, J as TrajectoryLogger } from "./index-SkPG_Rew.js";
|
|
2
|
+
import { R as Tool } from "./index-Bfjpd_3o.js";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
5
5
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -34,6 +34,17 @@ type McpClientHandle = {
|
|
|
34
34
|
readonly tools: ReadonlyArray<Tool>;
|
|
35
35
|
readonly close: () => Promise<void>;
|
|
36
36
|
};
|
|
37
|
+
/**
|
|
38
|
+
* Connects to an MCP server and surfaces its advertised tools as fascicle
|
|
39
|
+
* `Tool[]`, plus a `close` handle for the connection.
|
|
40
|
+
*
|
|
41
|
+
* Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
|
|
42
|
+
* do not have to import SDK transport classes themselves. Each advertised MCP
|
|
43
|
+
* tool becomes an ordinary `Tool`: its JSON Schema is bridged to Zod for the
|
|
44
|
+
* loop's `safeParse` and the provider, and `execute` forwards to `callTool`,
|
|
45
|
+
* propagating the run's abort signal. For the `client` transport variant the
|
|
46
|
+
* caller keeps ownership of the connection, so `close` is a no-op.
|
|
47
|
+
*/
|
|
37
48
|
declare function mcp_client(config: McpClientConfig, options?: McpClientOptions): Promise<McpClientHandle>;
|
|
38
49
|
//#endregion
|
|
39
50
|
//#region src/mcp/serve.d.ts
|
|
@@ -49,9 +60,24 @@ type ServeFlowOptions<i, o> = {
|
|
|
49
60
|
structured?: Record<string, unknown>;
|
|
50
61
|
};
|
|
51
62
|
};
|
|
63
|
+
/**
|
|
64
|
+
* Registers a fascicle flow as a tool on a caller-owned MCP server.
|
|
65
|
+
*
|
|
66
|
+
* Drives the flow with `run`, threading the per-request abort signal so an
|
|
67
|
+
* MCP client cancellation aborts the in-flight flow, and maps the result
|
|
68
|
+
* into a `CallToolResult`. A thrown flow becomes an `isError` result rather
|
|
69
|
+
* than a JSON-RPC protocol error.
|
|
70
|
+
*/
|
|
52
71
|
declare function serve_flow<i, o>(options: ServeFlowOptions<i, o>): void;
|
|
53
72
|
//#endregion
|
|
54
73
|
//#region src/mcp/schema_bridge.d.ts
|
|
74
|
+
/**
|
|
75
|
+
* Converts a JSON Schema node into a Zod type, never throwing.
|
|
76
|
+
*
|
|
77
|
+
* A malformed or unrecognized schema falls back to `z.unknown()` instead of
|
|
78
|
+
* propagating an error, since an arbitrary remote MCP server's schema must
|
|
79
|
+
* never crash tool discovery.
|
|
80
|
+
*/
|
|
55
81
|
declare function json_schema_to_zod(schema: unknown): z.ZodType;
|
|
56
82
|
//#endregion
|
|
57
83
|
//#region src/mcp/errors.d.ts
|
package/dist/mcp.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as run } from "./core-
|
|
1
|
+
import { T as run } from "./core-DNH8ddMT.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
//#region src/mcp/errors.ts
|
|
4
4
|
/**
|
|
@@ -30,26 +30,33 @@ var mcp_error = class extends Error {
|
|
|
30
30
|
* Small shared guards for the MCP adapter. Kept in one place so the client,
|
|
31
31
|
* schema bridge, and result mapping do not each carry a copy.
|
|
32
32
|
*/
|
|
33
|
+
/**
|
|
34
|
+
* Narrows a value to a plain object: non-null, `typeof` object, not an array.
|
|
35
|
+
*/
|
|
33
36
|
function is_record(value) {
|
|
34
37
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
35
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Returns the value when it is a plain object, otherwise `undefined`.
|
|
41
|
+
*/
|
|
36
42
|
function as_record(value) {
|
|
37
43
|
return is_record(value) ? value : void 0;
|
|
38
44
|
}
|
|
39
45
|
//#endregion
|
|
40
46
|
//#region src/mcp/result_mapping.ts
|
|
41
47
|
/**
|
|
42
|
-
* Mapping between MCP `CallToolResult` payloads and fascicle tool values
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
*
|
|
48
|
+
* Mapping between MCP `CallToolResult` payloads and fascicle tool values, in
|
|
49
|
+
* both directions: inbound results from `mcp_client` tools, outbound results
|
|
50
|
+
* for `serve_flow`.
|
|
51
|
+
*/
|
|
52
|
+
/**
|
|
53
|
+
* Converts a remote tool's `CallToolResult` into the value a fascicle
|
|
54
|
+
* `Tool.execute` returns.
|
|
48
55
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* the
|
|
56
|
+
* `isError: true` marks a tool-level failure, so it throws `mcp_error` rather
|
|
57
|
+
* than returning, letting the tool loop's error policy feed it back to the
|
|
58
|
+
* model. `structuredContent` is preferred over joined text parts when present;
|
|
59
|
+
* with neither, the raw `content` (or `null`) is returned.
|
|
53
60
|
*/
|
|
54
61
|
function call_result_to_output(result, tool_name) {
|
|
55
62
|
const record = as_record(result) ?? {};
|
|
@@ -59,6 +66,14 @@ function call_result_to_output(result, tool_name) {
|
|
|
59
66
|
if (text !== void 0) return text;
|
|
60
67
|
return record["content"] ?? null;
|
|
61
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Converts a fascicle flow's output into a `CallToolResult` for `serve_flow`.
|
|
71
|
+
*
|
|
72
|
+
* A `to_result` override takes precedence over the default mapping. By
|
|
73
|
+
* default, objects are emitted as both a JSON text part (every MCP host can
|
|
74
|
+
* read text) and `structuredContent` (typed hosts get the object); everything
|
|
75
|
+
* else becomes a single text part.
|
|
76
|
+
*/
|
|
62
77
|
function output_to_call_result(output, to_result) {
|
|
63
78
|
if (to_result !== void 0) {
|
|
64
79
|
const shaped = to_result(output);
|
|
@@ -69,6 +84,10 @@ function output_to_call_result(output, to_result) {
|
|
|
69
84
|
if (Array.isArray(output)) return build_result(stringify(output));
|
|
70
85
|
return build_result(String(output));
|
|
71
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* Assembles a `CallToolResult` with one text part and, when given, structured
|
|
89
|
+
* content.
|
|
90
|
+
*/
|
|
72
91
|
function build_result(text, structured) {
|
|
73
92
|
return structured !== void 0 ? {
|
|
74
93
|
content: [{
|
|
@@ -81,12 +100,20 @@ function build_result(text, structured) {
|
|
|
81
100
|
text
|
|
82
101
|
}] };
|
|
83
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Joins the `text` parts of an MCP content array with newlines, skipping
|
|
105
|
+
* non-text parts; `undefined` when there is nothing to join.
|
|
106
|
+
*/
|
|
84
107
|
function join_text(content) {
|
|
85
108
|
if (!Array.isArray(content)) return void 0;
|
|
86
109
|
const parts = [];
|
|
87
110
|
for (const part of content) if (is_record(part) && part["type"] === "text" && typeof part["text"] === "string") parts.push(part["text"]);
|
|
88
111
|
return parts.length > 0 ? parts.join("\n") : void 0;
|
|
89
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* `JSON.stringify` that falls back to `String` instead of throwing on
|
|
115
|
+
* unserializable values (circular references, BigInt).
|
|
116
|
+
*/
|
|
90
117
|
function stringify(value) {
|
|
91
118
|
try {
|
|
92
119
|
return JSON.stringify(value);
|
|
@@ -115,6 +142,13 @@ function stringify(value) {
|
|
|
115
142
|
* them anyway. Structure, types, enums, const, unions, and descriptions are
|
|
116
143
|
* preserved; anything unrecognized degrades to `z.unknown()`.
|
|
117
144
|
*/
|
|
145
|
+
/**
|
|
146
|
+
* Converts a JSON Schema node into a Zod type, never throwing.
|
|
147
|
+
*
|
|
148
|
+
* A malformed or unrecognized schema falls back to `z.unknown()` instead of
|
|
149
|
+
* propagating an error, since an arbitrary remote MCP server's schema must
|
|
150
|
+
* never crash tool discovery.
|
|
151
|
+
*/
|
|
118
152
|
function json_schema_to_zod(schema) {
|
|
119
153
|
try {
|
|
120
154
|
return convert(schema);
|
|
@@ -122,6 +156,13 @@ function json_schema_to_zod(schema) {
|
|
|
122
156
|
return z.unknown();
|
|
123
157
|
}
|
|
124
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Converts one JSON Schema node to a Zod type, recursing into nested schemas.
|
|
161
|
+
*
|
|
162
|
+
* Checks `const`, `enum`, `anyOf`, `oneOf`, and `allOf` before `type`, since
|
|
163
|
+
* those keywords can appear without a `type` and take precedence when they
|
|
164
|
+
* do. A `description` on the node carries through to the returned Zod type.
|
|
165
|
+
*/
|
|
125
166
|
function convert(node) {
|
|
126
167
|
const schema = as_record(node);
|
|
127
168
|
if (schema === void 0) return z.unknown();
|
|
@@ -140,6 +181,10 @@ function convert(node) {
|
|
|
140
181
|
if (is_record(schema["properties"])) return described(build_object(schema));
|
|
141
182
|
return described(z.unknown());
|
|
142
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* Maps a single JSON Schema `type` keyword to the matching Zod primitive or
|
|
186
|
+
* container, falling back to `z.unknown()` for an unrecognized type.
|
|
187
|
+
*/
|
|
143
188
|
function for_type(type, schema) {
|
|
144
189
|
switch (type) {
|
|
145
190
|
case "object": return build_object(schema);
|
|
@@ -152,6 +197,14 @@ function for_type(type, schema) {
|
|
|
152
197
|
default: return z.unknown();
|
|
153
198
|
}
|
|
154
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Builds a Zod object type from a JSON Schema object's `properties` and
|
|
202
|
+
* `required`, marking any key absent from `required` as optional.
|
|
203
|
+
*
|
|
204
|
+
* Uses `z.looseObject` rather than `z.object` so keys the remote server
|
|
205
|
+
* accepts but this conversion did not anticipate still pass through instead
|
|
206
|
+
* of being stripped or rejected.
|
|
207
|
+
*/
|
|
155
208
|
function build_object(schema) {
|
|
156
209
|
const properties = as_record(schema["properties"]) ?? {};
|
|
157
210
|
const required = new Set(string_array(schema["required"]));
|
|
@@ -162,25 +215,50 @@ function build_object(schema) {
|
|
|
162
215
|
}
|
|
163
216
|
return z.looseObject(shape);
|
|
164
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* Builds a Zod array type from a JSON Schema array's `items`.
|
|
220
|
+
*/
|
|
165
221
|
function build_array(schema) {
|
|
166
222
|
return z.array(convert(schema["items"]));
|
|
167
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Converts a JSON Schema `enum` array to a Zod type.
|
|
226
|
+
*
|
|
227
|
+
* An all-string enum maps to `z.enum`; a mixed-type enum maps to a union of
|
|
228
|
+
* literals instead, since `z.enum` only accepts strings.
|
|
229
|
+
*/
|
|
168
230
|
function enum_of(values) {
|
|
169
231
|
if (values.length === 0) return z.unknown();
|
|
170
232
|
if (values.every((v) => typeof v === "string")) return z.enum(values);
|
|
171
233
|
return combine_union(values.map(literal_of));
|
|
172
234
|
}
|
|
235
|
+
/**
|
|
236
|
+
* Converts a JSON Schema `anyOf` or `oneOf` array to a Zod union, converting
|
|
237
|
+
* each branch independently.
|
|
238
|
+
*/
|
|
173
239
|
function union_of(nodes) {
|
|
174
240
|
return combine_union(nodes.map(convert));
|
|
175
241
|
}
|
|
242
|
+
/**
|
|
243
|
+
* Converts a JSON Schema `type` array (e.g. `["string", "null"]`) to a Zod
|
|
244
|
+
* union of the matching primitive types.
|
|
245
|
+
*/
|
|
176
246
|
function union_of_types(types, schema) {
|
|
177
247
|
return combine_union(types.map((t) => for_type(String(t), schema)));
|
|
178
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* Converts a JSON Schema `allOf` array to a Zod intersection of every branch.
|
|
251
|
+
*/
|
|
179
252
|
function intersection_of(nodes) {
|
|
180
253
|
const parts = nodes.map(convert);
|
|
181
254
|
if (parts.length === 0) return z.unknown();
|
|
182
255
|
return parts.reduce((acc, part) => z.intersection(acc, part));
|
|
183
256
|
}
|
|
257
|
+
/**
|
|
258
|
+
* Builds a Zod union from a list of variants, collapsing the degenerate
|
|
259
|
+
* cases: zero variants becomes `z.unknown()`, one variant is returned as is,
|
|
260
|
+
* since `z.union` requires at least two.
|
|
261
|
+
*/
|
|
184
262
|
function combine_union(variants) {
|
|
185
263
|
const [first, second, ...rest] = variants;
|
|
186
264
|
if (first === void 0) return z.unknown();
|
|
@@ -191,11 +269,19 @@ function combine_union(variants) {
|
|
|
191
269
|
...rest
|
|
192
270
|
]);
|
|
193
271
|
}
|
|
272
|
+
/**
|
|
273
|
+
* Converts a single JSON value, as used in a `const` or an `enum` entry, to
|
|
274
|
+
* a Zod literal.
|
|
275
|
+
*/
|
|
194
276
|
function literal_of(value) {
|
|
195
277
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return z.literal(value);
|
|
196
278
|
if (value === null) return z.null();
|
|
197
279
|
return z.unknown();
|
|
198
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Filters a value down to the strings it contains, or an empty array when it
|
|
283
|
+
* is not an array at all.
|
|
284
|
+
*/
|
|
199
285
|
function string_array(value) {
|
|
200
286
|
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
201
287
|
}
|
|
@@ -213,6 +299,11 @@ function string_array(value) {
|
|
|
213
299
|
* `serve_flow` is not covered here: it operates on a caller-constructed
|
|
214
300
|
* `McpServer`, so it needs only a type-only import and no runtime SDK load.
|
|
215
301
|
*/
|
|
302
|
+
/**
|
|
303
|
+
* Dynamically imports the `@modelcontextprotocol/sdk` client modules,
|
|
304
|
+
* throwing a typed `mcp_sdk_missing_error` when the optional peer is not
|
|
305
|
+
* installed.
|
|
306
|
+
*/
|
|
216
307
|
async function load_client_sdk() {
|
|
217
308
|
try {
|
|
218
309
|
const [client_mod, stdio_mod, http_mod] = await Promise.all([
|
|
@@ -235,6 +326,17 @@ const DEFAULT_CLIENT_INFO = {
|
|
|
235
326
|
name: "fascicle",
|
|
236
327
|
version: "0.0.0"
|
|
237
328
|
};
|
|
329
|
+
/**
|
|
330
|
+
* Connects to an MCP server and surfaces its advertised tools as fascicle
|
|
331
|
+
* `Tool[]`, plus a `close` handle for the connection.
|
|
332
|
+
*
|
|
333
|
+
* Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
|
|
334
|
+
* do not have to import SDK transport classes themselves. Each advertised MCP
|
|
335
|
+
* tool becomes an ordinary `Tool`: its JSON Schema is bridged to Zod for the
|
|
336
|
+
* loop's `safeParse` and the provider, and `execute` forwards to `callTool`,
|
|
337
|
+
* propagating the run's abort signal. For the `client` transport variant the
|
|
338
|
+
* caller keeps ownership of the connection, so `close` is a no-op.
|
|
339
|
+
*/
|
|
238
340
|
async function mcp_client(config, options = {}) {
|
|
239
341
|
const owns_client = config.transport !== "client";
|
|
240
342
|
const client = await connect_client(config, options);
|
|
@@ -252,6 +354,10 @@ async function mcp_client(config, options = {}) {
|
|
|
252
354
|
}
|
|
253
355
|
};
|
|
254
356
|
}
|
|
357
|
+
/**
|
|
358
|
+
* Returns the caller's already-connected client as-is, or lazily loads the
|
|
359
|
+
* SDK and connects a fresh client over the configured transport.
|
|
360
|
+
*/
|
|
255
361
|
async function connect_client(config, options) {
|
|
256
362
|
if (config.transport === "client") return config.client;
|
|
257
363
|
const sdk = await load_client_sdk();
|
|
@@ -259,6 +365,10 @@ async function connect_client(config, options) {
|
|
|
259
365
|
await client.connect(build_transport(sdk, config));
|
|
260
366
|
return client;
|
|
261
367
|
}
|
|
368
|
+
/**
|
|
369
|
+
* Constructs the SDK transport matching the config: a spawned child process
|
|
370
|
+
* for `stdio`, a Streamable HTTP connection for `http`.
|
|
371
|
+
*/
|
|
262
372
|
function build_transport(sdk, config) {
|
|
263
373
|
if (config.transport === "stdio") return new sdk.StdioClientTransport({
|
|
264
374
|
command: config.command,
|
|
@@ -269,6 +379,13 @@ function build_transport(sdk, config) {
|
|
|
269
379
|
const opts = config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {};
|
|
270
380
|
return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts);
|
|
271
381
|
}
|
|
382
|
+
/**
|
|
383
|
+
* Wraps one advertised MCP tool as a fascicle `Tool` whose `execute` forwards
|
|
384
|
+
* to `callTool` on the shared client.
|
|
385
|
+
*
|
|
386
|
+
* An already-aborted signal short-circuits before the wire call; otherwise the
|
|
387
|
+
* signal is passed through so cancelling the run cancels the remote call.
|
|
388
|
+
*/
|
|
272
389
|
function to_fascicle_tool(client, advertised, options) {
|
|
273
390
|
const name = advertised.name;
|
|
274
391
|
return {
|
|
@@ -286,6 +403,14 @@ function to_fascicle_tool(client, advertised, options) {
|
|
|
286
403
|
}
|
|
287
404
|
//#endregion
|
|
288
405
|
//#region src/mcp/serve.ts
|
|
406
|
+
/**
|
|
407
|
+
* Registers a fascicle flow as a tool on a caller-owned MCP server.
|
|
408
|
+
*
|
|
409
|
+
* Drives the flow with `run`, threading the per-request abort signal so an
|
|
410
|
+
* MCP client cancellation aborts the in-flight flow, and maps the result
|
|
411
|
+
* into a `CallToolResult`. A thrown flow becomes an `isError` result rather
|
|
412
|
+
* than a JSON-RPC protocol error.
|
|
413
|
+
*/
|
|
289
414
|
function serve_flow(options) {
|
|
290
415
|
const { server, flow, name, description, input_schema, trajectory, to_result } = options;
|
|
291
416
|
server.registerTool(name, {
|
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\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\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.\n *\n * Inbound (`call_result_to_output`): a remote tool result becomes the value a\n * fascicle `Tool.execute` returns. `isError: true` is a tool-level failure, so\n * it throws rather than returns, letting the tool loop's error policy feed it\n * back to the model. Structured output is preferred over text when present.\n *\n * Outbound (`output_to_call_result`): a fascicle flow's output becomes a\n * `CallToolResult` for `serve_flow`. Objects are emitted as both a JSON text\n * part (every MCP host can read it) and `structuredContent` (typed hosts get\n * the object).\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\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\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\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\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\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * JSON Schema to Zod conversion for inbound MCP tools.\n *\n * An MCP tool advertises its input as JSON Schema, but a fascicle `Tool` carries\n * a Zod `input_schema` that the tool loop `safeParse`s before `execute` and the\n * engine serializes back to JSON Schema for the provider. So the converted Zod\n * must do two things at once: stay permissive enough never to reject an arg the\n * remote server would accept, and round-trip through `z.toJSONSchema` to a shape\n * the provider can fill.\n *\n * Two deliberate choices serve those goals. Objects are `looseObject` so extra\n * keys survive to the server (which re-validates and is the real authority), and\n * a freeform object maps to `z.looseObject({})` (emits `{type:\"object\"}`) rather\n * than `z.unknown()` (emits `{}`), preserving the \"takes an object\" signal. Value\n * constraints (min/max, length, pattern, format) are intentionally not modeled:\n * they add rejection risk for marginal provider benefit, and the server enforces\n * them anyway. Structure, types, enums, const, unions, and descriptions are\n * preserved; anything unrecognized degrades to `z.unknown()`.\n */\n\nimport { z } from 'zod'\nimport { as_record, is_record } from './internal.js'\n\nexport function json_schema_to_zod(schema: unknown): z.ZodType {\n try {\n return convert(schema)\n } catch {\n // An arbitrary remote schema must never crash tool discovery.\n return z.unknown()\n }\n}\n\nfunction convert(node: unknown): z.ZodType {\n const schema = as_record(node)\n if (schema === undefined) return z.unknown()\n\n const described = (inner: z.ZodType): z.ZodType => {\n const description = schema['description']\n return typeof description === 'string' ? inner.describe(description) : inner\n }\n\n if ('const' in schema) return described(literal_of(schema['const']))\n if (Array.isArray(schema['enum'])) return described(enum_of(schema['enum']))\n if (Array.isArray(schema['anyOf'])) return described(union_of(schema['anyOf']))\n if (Array.isArray(schema['oneOf'])) return described(union_of(schema['oneOf']))\n if (Array.isArray(schema['allOf'])) return described(intersection_of(schema['allOf']))\n\n const type = schema['type']\n if (Array.isArray(type)) {\n return described(union_of_types(type, schema))\n }\n if (typeof type === 'string') {\n return described(for_type(type, schema))\n }\n // No explicit type: an object with declared properties is still an object;\n // otherwise nothing structural is known, so stay permissive.\n if (is_record(schema['properties'])) return described(build_object(schema))\n return described(z.unknown())\n}\n\nfunction for_type(type: string, schema: Record<string, unknown>): z.ZodType {\n switch (type) {\n case 'object':\n return build_object(schema)\n case 'array':\n return build_array(schema)\n case 'string':\n return z.string()\n case 'number':\n return z.number()\n case 'integer':\n return z.number().int()\n case 'boolean':\n return z.boolean()\n case 'null':\n return z.null()\n default:\n return z.unknown()\n }\n}\n\nfunction build_object(schema: Record<string, unknown>): z.ZodType {\n const properties = as_record(schema['properties']) ?? {}\n const required = new Set(string_array(schema['required']))\n const shape: Record<string, z.ZodType> = {}\n for (const [key, prop] of Object.entries(properties)) {\n const child = convert(prop)\n shape[key] = required.has(key) ? child : child.optional()\n }\n return z.looseObject(shape)\n}\n\nfunction build_array(schema: Record<string, unknown>): z.ZodType {\n // A positional-tuple `items` array and a missing `items` both convert to\n // `z.unknown()`, so one permissive element type covers every case. Tuple\n // schemas are rare in MCP tools and the server re-validates them anyway.\n return z.array(convert(schema['items']))\n}\n\nfunction enum_of(values: unknown[]): z.ZodType {\n if (values.length === 0) return z.unknown()\n if (values.every((v): v is string => typeof v === 'string')) {\n return z.enum(values)\n }\n return combine_union(values.map(literal_of))\n}\n\nfunction union_of(nodes: unknown[]): z.ZodType {\n return combine_union(nodes.map(convert))\n}\n\nfunction union_of_types(types: unknown[], schema: Record<string, unknown>): z.ZodType {\n return combine_union(types.map((t) => for_type(String(t), schema)))\n}\n\nfunction intersection_of(nodes: unknown[]): z.ZodType {\n const parts = nodes.map(convert)\n if (parts.length === 0) return z.unknown()\n return parts.reduce((acc, part) => z.intersection(acc, part))\n}\n\nfunction combine_union(variants: z.ZodType[]): z.ZodType {\n const [first, second, ...rest] = variants\n if (first === undefined) return z.unknown()\n if (second === undefined) return first\n return z.union([first, second, ...rest])\n}\n\nfunction literal_of(value: unknown): z.ZodType {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return z.literal(value)\n }\n if (value === null) return z.null()\n // Object and array literals are not expressible as z.literal; accept anything.\n return z.unknown()\n}\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\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 * `mcp_client` owns the connection lifecycle (config in, `{ tools, close }`\n * out) so callers do not have to import SDK transport classes themselves. Each\n * advertised MCP tool becomes an ordinary `Tool`: its JSON Schema is bridged to\n * Zod for the loop's `safeParse` and the provider, and `execute` forwards to\n * `callTool`, propagating the run's abort signal.\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_zod } 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\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\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\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\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_zod(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 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\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;;;;;;;ACrBA,SAAgB,UAAU,OAAkD;CAC1E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,UAAU,OAAqD;CAC7E,OAAO,UAAU,KAAK,IAAI,QAAQ,KAAA;AACpC;;;;;;;;;;;;;;;;ACWA,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,KA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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/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 * JSON Schema to Zod conversion for inbound MCP tools.\n *\n * An MCP tool advertises its input as JSON Schema, but a fascicle `Tool` carries\n * a Zod `input_schema` that the tool loop `safeParse`s before `execute` and the\n * engine serializes back to JSON Schema for the provider. So the converted Zod\n * must do two things at once: stay permissive enough never to reject an arg the\n * remote server would accept, and round-trip through `z.toJSONSchema` to a shape\n * the provider can fill.\n *\n * Two deliberate choices serve those goals. Objects are `looseObject` so extra\n * keys survive to the server (which re-validates and is the real authority), and\n * a freeform object maps to `z.looseObject({})` (emits `{type:\"object\"}`) rather\n * than `z.unknown()` (emits `{}`), preserving the \"takes an object\" signal. Value\n * constraints (min/max, length, pattern, format) are intentionally not modeled:\n * they add rejection risk for marginal provider benefit, and the server enforces\n * them anyway. Structure, types, enums, const, unions, and descriptions are\n * preserved; anything unrecognized degrades to `z.unknown()`.\n */\n\nimport { z } from 'zod'\nimport { as_record, is_record } from './internal.js'\n\n/**\n * Converts a JSON Schema node into a Zod type, never throwing.\n *\n * A malformed or unrecognized schema falls back to `z.unknown()` instead of\n * propagating an error, since an arbitrary remote MCP server's schema must\n * never crash tool discovery.\n */\nexport function json_schema_to_zod(schema: unknown): z.ZodType {\n try {\n return convert(schema)\n } catch {\n // An arbitrary remote schema must never crash tool discovery.\n return z.unknown()\n }\n}\n\n/**\n * Converts one JSON Schema node to a Zod type, recursing into nested schemas.\n *\n * Checks `const`, `enum`, `anyOf`, `oneOf`, and `allOf` before `type`, since\n * those keywords can appear without a `type` and take precedence when they\n * do. A `description` on the node carries through to the returned Zod type.\n */\nfunction convert(node: unknown): z.ZodType {\n const schema = as_record(node)\n if (schema === undefined) return z.unknown()\n\n const described = (inner: z.ZodType): z.ZodType => {\n const description = schema['description']\n return typeof description === 'string' ? inner.describe(description) : inner\n }\n\n if ('const' in schema) return described(literal_of(schema['const']))\n if (Array.isArray(schema['enum'])) return described(enum_of(schema['enum']))\n if (Array.isArray(schema['anyOf'])) return described(union_of(schema['anyOf']))\n if (Array.isArray(schema['oneOf'])) return described(union_of(schema['oneOf']))\n if (Array.isArray(schema['allOf'])) return described(intersection_of(schema['allOf']))\n\n const type = schema['type']\n if (Array.isArray(type)) {\n return described(union_of_types(type, schema))\n }\n if (typeof type === 'string') {\n return described(for_type(type, schema))\n }\n // No explicit type: an object with declared properties is still an object;\n // otherwise nothing structural is known, so stay permissive.\n if (is_record(schema['properties'])) return described(build_object(schema))\n return described(z.unknown())\n}\n\n/**\n * Maps a single JSON Schema `type` keyword to the matching Zod primitive or\n * container, falling back to `z.unknown()` for an unrecognized type.\n */\nfunction for_type(type: string, schema: Record<string, unknown>): z.ZodType {\n switch (type) {\n case 'object':\n return build_object(schema)\n case 'array':\n return build_array(schema)\n case 'string':\n return z.string()\n case 'number':\n return z.number()\n case 'integer':\n return z.number().int()\n case 'boolean':\n return z.boolean()\n case 'null':\n return z.null()\n default:\n return z.unknown()\n }\n}\n\n/**\n * Builds a Zod object type from a JSON Schema object's `properties` and\n * `required`, marking any key absent from `required` as optional.\n *\n * Uses `z.looseObject` rather than `z.object` so keys the remote server\n * accepts but this conversion did not anticipate still pass through instead\n * of being stripped or rejected.\n */\nfunction build_object(schema: Record<string, unknown>): z.ZodType {\n const properties = as_record(schema['properties']) ?? {}\n const required = new Set(string_array(schema['required']))\n const shape: Record<string, z.ZodType> = {}\n for (const [key, prop] of Object.entries(properties)) {\n const child = convert(prop)\n shape[key] = required.has(key) ? child : child.optional()\n }\n return z.looseObject(shape)\n}\n\n/**\n * Builds a Zod array type from a JSON Schema array's `items`.\n */\nfunction build_array(schema: Record<string, unknown>): z.ZodType {\n // A positional-tuple `items` array and a missing `items` both convert to\n // `z.unknown()`, so one permissive element type covers every case. Tuple\n // schemas are rare in MCP tools and the server re-validates them anyway.\n return z.array(convert(schema['items']))\n}\n\n/**\n * Converts a JSON Schema `enum` array to a Zod type.\n *\n * An all-string enum maps to `z.enum`; a mixed-type enum maps to a union of\n * literals instead, since `z.enum` only accepts strings.\n */\nfunction enum_of(values: unknown[]): z.ZodType {\n if (values.length === 0) return z.unknown()\n if (values.every((v): v is string => typeof v === 'string')) {\n return z.enum(values)\n }\n return combine_union(values.map(literal_of))\n}\n\n/**\n * Converts a JSON Schema `anyOf` or `oneOf` array to a Zod union, converting\n * each branch independently.\n */\nfunction union_of(nodes: unknown[]): z.ZodType {\n return combine_union(nodes.map(convert))\n}\n\n/**\n * Converts a JSON Schema `type` array (e.g. `[\"string\", \"null\"]`) to a Zod\n * union of the matching primitive types.\n */\nfunction union_of_types(types: unknown[], schema: Record<string, unknown>): z.ZodType {\n return combine_union(types.map((t) => for_type(String(t), schema)))\n}\n\n/**\n * Converts a JSON Schema `allOf` array to a Zod intersection of every branch.\n */\nfunction intersection_of(nodes: unknown[]): z.ZodType {\n const parts = nodes.map(convert)\n if (parts.length === 0) return z.unknown()\n return parts.reduce((acc, part) => z.intersection(acc, part))\n}\n\n/**\n * Builds a Zod union from a list of variants, collapsing the degenerate\n * cases: zero variants becomes `z.unknown()`, one variant is returned as is,\n * since `z.union` requires at least two.\n */\nfunction combine_union(variants: z.ZodType[]): z.ZodType {\n const [first, second, ...rest] = variants\n if (first === undefined) return z.unknown()\n if (second === undefined) return first\n return z.union([first, second, ...rest])\n}\n\n/**\n * Converts a single JSON value, as used in a `const` or an `enum` entry, to\n * a Zod literal.\n */\nfunction literal_of(value: unknown): z.ZodType {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return z.literal(value)\n }\n if (value === null) return z.null()\n // Object and array literals are not expressible as z.literal; accept anything.\n return z.unknown()\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_zod } 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 bridged to Zod for the\n * loop's `safeParse` and the provider, and `execute` forwards to `callTool`,\n * propagating the run's abort signal. For the `client` transport variant the\n * caller keeps ownership of the connection, so `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_zod(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 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;;;;;;;;;;AClBA,SAAgB,UAAU,OAAkD;CAC1E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;AAKA,SAAgB,UAAU,OAAqD;CAC7E,OAAO,UAAU,KAAK,IAAI,QAAQ,KAAA;AACpC;;;;;;;;;;;;;;;;;ACMA,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,U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E;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"}
|
package/dist/otel.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { J as TrajectoryLogger } from "./index-
|
|
1
|
+
import { J as TrajectoryLogger } from "./index-SkPG_Rew.js";
|
|
2
2
|
import { Tracer } from "@opentelemetry/api";
|
|
3
3
|
|
|
4
4
|
//#region src/otel/trajectory_logger.d.ts
|
|
@@ -14,6 +14,13 @@ type OtelTrajectoryLoggerOptions = {
|
|
|
14
14
|
*/
|
|
15
15
|
readonly attribute_prefix?: string;
|
|
16
16
|
};
|
|
17
|
+
/**
|
|
18
|
+
* Create a `TrajectoryLogger` that mirrors spans and events onto
|
|
19
|
+
* OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).
|
|
20
|
+
*
|
|
21
|
+
* Parent resolution favors an explicit `parent_span_id` on the start meta;
|
|
22
|
+
* otherwise it falls back to the currently open span on an internal stack.
|
|
23
|
+
*/
|
|
17
24
|
declare function create_otel_trajectory_logger(options?: OtelTrajectoryLoggerOptions): TrajectoryLogger;
|
|
18
25
|
//#endregion
|
|
19
26
|
export { type OtelTrajectoryLoggerOptions, create_otel_trajectory_logger };
|
package/dist/otel.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SpanStatusCode, context, trace } from "@opentelemetry/api";
|
|
2
2
|
//#region src/otel/trajectory_logger.ts
|
|
3
3
|
/**
|
|
4
|
-
* OpenTelemetry bridge for fascicle trajectory events
|
|
4
|
+
* OpenTelemetry bridge for fascicle trajectory events.
|
|
5
5
|
*
|
|
6
6
|
* `create_otel_trajectory_logger` returns a plain TrajectoryLogger that turns
|
|
7
7
|
* the engine's own span + event stream into OpenTelemetry spans: the
|
|
@@ -12,9 +12,9 @@ import { SpanStatusCode, context, trace } from "@opentelemetry/api";
|
|
|
12
12
|
* transports get traces without any AI-SDK involvement.
|
|
13
13
|
*
|
|
14
14
|
* This module is the ONLY place `@opentelemetry/api` is imported, and it lives
|
|
15
|
-
* outside `src/engine/` on purpose
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* outside `src/engine/` on purpose: the engine's `ai + zod` npm-dep invariant
|
|
16
|
+
* holds unmodified, and an app that never imports `fascicle/otel` pulls in
|
|
17
|
+
* zero OTel packages at runtime.
|
|
18
18
|
*
|
|
19
19
|
* Nesting is resolved two ways, in order: an explicit `parent_span_id` on the
|
|
20
20
|
* start meta (how the composition runner threads composer-span parenthood) wins;
|
|
@@ -29,6 +29,10 @@ const INTERNAL_KEYS = /* @__PURE__ */ new Set([
|
|
|
29
29
|
"span_id",
|
|
30
30
|
"parent_span_id"
|
|
31
31
|
]);
|
|
32
|
+
/**
|
|
33
|
+
* JSON-stringify `value`, falling back to `String(value)` when `stringify`
|
|
34
|
+
* throws or returns `undefined` (e.g. for functions or symbols).
|
|
35
|
+
*/
|
|
32
36
|
function safe_json(value) {
|
|
33
37
|
try {
|
|
34
38
|
return JSON.stringify(value) ?? String(value);
|
|
@@ -36,6 +40,13 @@ function safe_json(value) {
|
|
|
36
40
|
return String(value);
|
|
37
41
|
}
|
|
38
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Convert a JS value into an OTel-compatible attribute value.
|
|
45
|
+
*
|
|
46
|
+
* Primitives and homogeneous primitive arrays pass through unchanged;
|
|
47
|
+
* anything else falls back to `safe_json`; `null`/`undefined` drop out
|
|
48
|
+
* entirely (returning `undefined`) so the caller can omit the attribute.
|
|
49
|
+
*/
|
|
39
50
|
function to_attribute_value(value) {
|
|
40
51
|
if (value === null || value === void 0) return void 0;
|
|
41
52
|
const kind = typeof value;
|
|
@@ -48,6 +59,13 @@ function to_attribute_value(value) {
|
|
|
48
59
|
}
|
|
49
60
|
return safe_json(value);
|
|
50
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Build an OTel `Attributes` object from event/meta fields.
|
|
64
|
+
*
|
|
65
|
+
* Skips the bridge's internal plumbing keys (`kind`, `span_id`,
|
|
66
|
+
* `parent_span_id`) and prefixes the rest with `prefix` so they stay out of
|
|
67
|
+
* OTel's semantic-convention namespace.
|
|
68
|
+
*/
|
|
51
69
|
function to_attributes(meta, prefix) {
|
|
52
70
|
const attrs = {};
|
|
53
71
|
if (meta === void 0) return attrs;
|
|
@@ -58,6 +76,13 @@ function to_attributes(meta, prefix) {
|
|
|
58
76
|
}
|
|
59
77
|
return attrs;
|
|
60
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* Create a `TrajectoryLogger` that mirrors spans and events onto
|
|
81
|
+
* OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).
|
|
82
|
+
*
|
|
83
|
+
* Parent resolution favors an explicit `parent_span_id` on the start meta;
|
|
84
|
+
* otherwise it falls back to the currently open span on an internal stack.
|
|
85
|
+
*/
|
|
61
86
|
function create_otel_trajectory_logger(options = {}) {
|
|
62
87
|
const tracer = options.tracer ?? trace.getTracer("fascicle");
|
|
63
88
|
const prefix = options.attribute_prefix ?? "fascicle.";
|
package/dist/otel.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otel.js","names":["otel_context"],"sources":["../src/otel/trajectory_logger.ts"],"sourcesContent":["/**\n * OpenTelemetry bridge for fascicle trajectory events
|
|
1
|
+
{"version":3,"file":"otel.js","names":["otel_context"],"sources":["../src/otel/trajectory_logger.ts"],"sourcesContent":["/**\n * OpenTelemetry bridge for fascicle trajectory events.\n *\n * `create_otel_trajectory_logger` returns a plain TrajectoryLogger that turns\n * the engine's own span + event stream into OpenTelemetry spans: the\n * `engine.generate` span becomes an OTel root span, each `engine.generate.step`\n * a child span, and every `record`ed event (tool_call, tool_result, cost, ...)\n * an OTel span event on the currently-open span. It is transport-neutral: the\n * spans come from events the engine already emits, so native and external\n * transports get traces without any AI-SDK involvement.\n *\n * This module is the ONLY place `@opentelemetry/api` is imported, and it lives\n * outside `src/engine/` on purpose: the engine's `ai + zod` npm-dep invariant\n * holds unmodified, and an app that never imports `fascicle/otel` pulls in\n * zero OTel packages at runtime.\n *\n * Nesting is resolved two ways, in order: an explicit `parent_span_id` on the\n * start meta (how the composition runner threads composer-span parenthood) wins;\n * otherwise the currently-open span (top of the open stack) is the parent. This\n * is exact for the sequential engine flow (generate → step → step) and for\n * runner-nested spans; genuinely interleaved sibling spans that carry no\n * `parent_span_id` (concurrent branches sharing one logger) fall back to stack\n * order, which is this bridge's one documented approximation.\n */\n\nimport {\n context as otel_context,\n trace,\n SpanStatusCode,\n type AttributeValue,\n type Attributes,\n type Context,\n type Span,\n type Tracer,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\n\nexport type OtelTrajectoryLoggerOptions = {\n /**\n * Tracer to open spans on. Defaults to `trace.getTracer('fascicle')`, which\n * resolves against whatever global TracerProvider the host has registered.\n */\n readonly tracer?: Tracer\n /**\n * Prefix for span + event attributes derived from event metadata, keeping\n * them out of the OTel semantic-convention namespace. Defaults to `fascicle.`.\n */\n readonly attribute_prefix?: string\n}\n\n// Event/meta keys that are bridge plumbing, not span attributes.\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set(['kind', 'span_id', 'parent_span_id'])\n\n/**\n * JSON-stringify `value`, falling back to `String(value)` when `stringify`\n * throws or returns `undefined` (e.g. for functions or symbols).\n */\nfunction safe_json(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * Convert a JS value into an OTel-compatible attribute value.\n *\n * Primitives and homogeneous primitive arrays pass through unchanged;\n * anything else falls back to `safe_json`; `null`/`undefined` drop out\n * entirely (returning `undefined`) so the caller can omit the attribute.\n */\nfunction to_attribute_value(value: unknown): AttributeValue | undefined {\n if (value === null || value === undefined) return undefined\n const kind = typeof value\n if (kind === 'string' || kind === 'number' || kind === 'boolean') {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return value as AttributeValue\n }\n if (Array.isArray(value)) {\n if (value.every((v) => typeof v === 'string')) return value\n if (value.every((v) => typeof v === 'number')) return value\n if (value.every((v) => typeof v === 'boolean')) return value\n return safe_json(value)\n }\n return safe_json(value)\n}\n\n/**\n * Build an OTel `Attributes` object from event/meta fields.\n *\n * Skips the bridge's internal plumbing keys (`kind`, `span_id`,\n * `parent_span_id`) and prefixes the rest with `prefix` so they stay out of\n * OTel's semantic-convention namespace.\n */\nfunction to_attributes(\n meta: Readonly<Record<string, unknown>> | undefined,\n prefix: string,\n): Attributes {\n const attrs: Attributes = {}\n if (meta === undefined) return attrs\n for (const [key, value] of Object.entries(meta)) {\n if (INTERNAL_KEYS.has(key)) continue\n const attr = to_attribute_value(value)\n if (attr !== undefined) attrs[`${prefix}${key}`] = attr\n }\n return attrs\n}\n\ntype OpenSpan = { readonly span: Span; readonly context: Context }\n\n/**\n * Create a `TrajectoryLogger` that mirrors spans and events onto\n * OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).\n *\n * Parent resolution favors an explicit `parent_span_id` on the start meta;\n * otherwise it falls back to the currently open span on an internal stack.\n */\nexport function create_otel_trajectory_logger(\n options: OtelTrajectoryLoggerOptions = {},\n): TrajectoryLogger {\n const tracer = options.tracer ?? trace.getTracer('fascicle')\n const prefix = options.attribute_prefix ?? 'fascicle.'\n const open = new Map<string, OpenSpan>()\n const stack: string[] = []\n let counter = 0\n\n const top_context = (): Context | undefined => {\n const top = stack[stack.length - 1]\n if (top === undefined) return undefined\n return open.get(top)?.context\n }\n\n const parent_context = (meta: Record<string, unknown> | undefined): Context => {\n const explicit = meta?.['parent_span_id']\n if (typeof explicit === 'string') {\n const parent = open.get(explicit)\n if (parent !== undefined) return parent.context\n }\n return top_context() ?? otel_context.active()\n }\n\n const target_for_event = (event: TrajectoryEvent): Span | undefined => {\n if (typeof event.span_id === 'string') {\n const target = open.get(event.span_id)\n if (target !== undefined) return target.span\n }\n const top = stack[stack.length - 1]\n return top !== undefined ? open.get(top)?.span : undefined\n }\n\n return {\n start_span(name, meta) {\n const parent = parent_context(meta)\n const span = tracer.startSpan(name, { attributes: to_attributes(meta, prefix) }, parent)\n counter += 1\n const id = `fascicle-otel-${counter}`\n open.set(id, { span, context: trace.setSpan(parent, span) })\n stack.push(id)\n return id\n },\n end_span(id, meta) {\n const entry = open.get(id)\n if (entry === undefined) return\n const { span } = entry\n span.setAttributes(to_attributes(meta, prefix))\n const error = meta?.['error']\n if (typeof error === 'string' && error.length > 0) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: error })\n }\n span.end()\n open.delete(id)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n record(event) {\n const span = target_for_event(event)\n if (span === undefined) return\n const name = typeof event.kind === 'string' ? event.kind : 'event'\n span.addEvent(name, to_attributes(event, prefix))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,gCAAqC,IAAI,IAAI;CAAC;CAAQ;CAAW;AAAgB,CAAC;;;;;AAMxF,SAAS,UAAU,OAAwB;CACzC,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;;;;;;;AASA,SAAS,mBAAmB,OAA4C;CACtE,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO,KAAA;CAClD,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WAErD,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,IA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2
|
import { z } from "zod";
|
|
3
3
|
|
|
4
4
|
//#region src/stdio/execute_stdio.d.ts
|
|
@@ -29,9 +29,26 @@ type StdioIo = {
|
|
|
29
29
|
write(chunk: string): unknown;
|
|
30
30
|
};
|
|
31
31
|
};
|
|
32
|
+
/**
|
|
33
|
+
* Runs the stdio agent contract over injected `io`: read input, run the
|
|
34
|
+
* flow, dispose the engine, write output, and return the outcome as a
|
|
35
|
+
* value.
|
|
36
|
+
*
|
|
37
|
+
* Disposes the engine before writing output so a teardown failure on the
|
|
38
|
+
* success path yields code 1 and no stdout, keeping "code 0 means stdout
|
|
39
|
+
* carries an authoritative result" true even when disposal fails.
|
|
40
|
+
*/
|
|
32
41
|
declare function execute_stdio<i, o>(flow: Step<i, o>, options: RunStdioOptions<i, o>, io: StdioIo): Promise<StdioOutcome>;
|
|
33
42
|
//#endregion
|
|
34
43
|
//#region src/stdio/run_stdio.d.ts
|
|
44
|
+
/**
|
|
45
|
+
* Runs a flow as the stdio agent contract against the real process streams,
|
|
46
|
+
* then exits with the outcome's code.
|
|
47
|
+
*
|
|
48
|
+
* On a non-zero outcome, writes the `StdioFailure` as the last line on
|
|
49
|
+
* stderr so a parent process can take the tail line as machine-readable
|
|
50
|
+
* detail.
|
|
51
|
+
*/
|
|
35
52
|
declare function run_stdio<i, o>(flow: Step<i, o>, options?: RunStdioOptions<i, o>): Promise<void>;
|
|
36
53
|
//#endregion
|
|
37
54
|
export { type RunStdioOptions, type StdioFailure, type StdioIo, type StdioOutcome, execute_stdio, run_stdio };
|