@meridian-flow/runtime 0.2.0 → 0.3.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/README.md CHANGED
@@ -11,12 +11,13 @@ Node 20 or newer, ESM only.
11
11
 
12
12
  ## Entries
13
13
 
14
- | Entry | What it is |
15
- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
16
- | `@meridian-flow/runtime/gateway` | One streaming `Gateway` over Anthropic, OpenAI, Gemini and OpenAI-compatible providers: retries, deadlines, usage normalization and a credential per call. |
17
- | `@meridian-flow/runtime/gateway/shapes` | The gateway's usage, provider-error and JSON types. No Node built-ins and no SDKs, so a browser bundle can import them. |
18
- | `@meridian-flow/runtime/gateway/mock` | A mock provider server for tests and local development (needs `node:http`). |
19
- | `@meridian-flow/runtime/gateway/mock-script` | The zod schemas of the mock's scripts. |
14
+ | Entry | What it is |
15
+ | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
16
+ | `@meridian-flow/runtime/gateway` | One streaming `Gateway` over Anthropic, OpenAI, Gemini and OpenAI-compatible providers: retries, deadlines, usage normalization and a credential per call. |
17
+ | `@meridian-flow/runtime/gateway/shapes` | The gateway's usage, provider-error and JSON types. No Node built-ins and no SDKs, so a browser bundle can import them. |
18
+ | `@meridian-flow/runtime/gateway/mock` | A mock provider server for tests and local development (needs `node:http`). |
19
+ | `@meridian-flow/runtime/gateway/mock-script` | The zod schemas of the mock's scripts. |
20
+ | `@meridian-flow/runtime/mcp` | A client for MCP servers over stdio and Streamable HTTP: list, call and check, with replies read off the wire, plus pure functions that pin tools for a model. Needs Node. |
20
21
 
21
22
  The package reads no environment variable: keys, URLs and policy come in through config or the call.
22
23
 
@@ -0,0 +1,2 @@
1
+ import type { McpClient, McpClientOptions } from "./types.js";
2
+ export declare function createMcpClient(options: McpClientOptions): McpClient;
@@ -0,0 +1,279 @@
1
+ import { faultOf, sessionForgotten } from "./fault.js";
2
+ import { Session } from "./session.js";
3
+ const MAX_LIST_PAGES = 100;
4
+ const CANCELLED = Symbol("cancelled");
5
+ /** A start that failed; calls within `failFastMs` get the same answer without trying again. */
6
+ class StartFailure extends Error {
7
+ fault;
8
+ constructor(fault) {
9
+ super(fault.message);
10
+ this.fault = fault;
11
+ }
12
+ }
13
+ /** The host's signal and one deadline, as one signal, with the cause of whichever fired first. */
14
+ function control(host, timeoutMs) {
15
+ const own = new AbortController();
16
+ let cause;
17
+ const fire = (why) => {
18
+ cause ??= why;
19
+ own.abort();
20
+ };
21
+ const onHost = () => fire("host");
22
+ if (host?.aborted)
23
+ fire("host");
24
+ else
25
+ host?.addEventListener("abort", onHost, { once: true });
26
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => fire("timeout"), timeoutMs);
27
+ const cancelled = new Promise((_, reject) => {
28
+ if (own.signal.aborted)
29
+ reject(CANCELLED);
30
+ else
31
+ own.signal.addEventListener("abort", () => reject(CANCELLED), { once: true });
32
+ });
33
+ cancelled.catch(() => { });
34
+ return {
35
+ signal: own.signal,
36
+ get cause() {
37
+ return cause;
38
+ },
39
+ race: (work) => Promise.race([work, cancelled]),
40
+ dispose() {
41
+ clearTimeout(timer);
42
+ host?.removeEventListener("abort", onHost);
43
+ },
44
+ };
45
+ }
46
+ export function createMcpClient(options) {
47
+ const connectTimeoutMs = options.connectTimeoutMs ?? 30_000;
48
+ const idleCloseMs = options.idleCloseMs ?? 5 * 60_000;
49
+ const failFastMs = options.failFastMs ?? 10_000;
50
+ const maxReplyBytes = options.maxReplyBytes ?? 10 * 1024 * 1024;
51
+ const cfg = {
52
+ clientInfo: options.clientInfo,
53
+ maxReplyBytes,
54
+ // Passed explicitly so the SDK never falls back to a global the host did not choose.
55
+ fetch: options.fetch ?? ((input, init) => fetch(input, init)),
56
+ ...(options.onEvent ? { onEvent: options.onEvent } : {}),
57
+ };
58
+ const entries = new Map();
59
+ function entryFor(key) {
60
+ let entry = entries.get(key);
61
+ if (!entry) {
62
+ entry = {};
63
+ entries.set(key, entry);
64
+ }
65
+ return entry;
66
+ }
67
+ /** The key's live session, started if there is none. Callers that arrive during a start share it. */
68
+ function acquire(server) {
69
+ const entry = entryFor(server.key);
70
+ if (entry.session && !entry.session.ended)
71
+ return Promise.resolve(entry.session);
72
+ if (entry.starting)
73
+ return entry.starting;
74
+ if (entry.failed) {
75
+ if (Date.now() - entry.failed.at < failFastMs)
76
+ return Promise.reject(entry.failed.failure);
77
+ entry.failed = undefined;
78
+ }
79
+ const starting = Session.open(server, cfg, { timeoutMs: connectTimeoutMs, idleCloseMs }).then((session) => {
80
+ entry.starting = undefined;
81
+ entry.session = session;
82
+ session.onEnded = () => {
83
+ if (entry.session === session)
84
+ entry.session = undefined;
85
+ };
86
+ return session;
87
+ }, (error) => {
88
+ entry.starting = undefined;
89
+ entry.failed = { at: Date.now(), failure: new StartFailure(faultOf(error, "start")) };
90
+ throw entry.failed.failure;
91
+ });
92
+ starting.catch(() => { }); // every caller may have given up; the failure is still recorded
93
+ entry.starting = starting;
94
+ return starting;
95
+ }
96
+ const unreachable = (fault, sent, ms) => ({
97
+ kind: "unreachable",
98
+ ...fault,
99
+ sent,
100
+ ms,
101
+ });
102
+ const aborted = (sent, ms) => ({ kind: "aborted", sent, ms });
103
+ /** The outcome of an acquire that did not give a session. */
104
+ function startOutcome(error, ctl, ms) {
105
+ if (error === CANCELLED) {
106
+ if (ctl.cause === "host")
107
+ return aborted(false, ms);
108
+ return unreachable({ reason: "call_timeout", message: "timed out before the session was ready" }, false, ms);
109
+ }
110
+ if (error instanceof StartFailure)
111
+ return unreachable(error.fault, false, ms);
112
+ throw error;
113
+ }
114
+ /** The outcome of one request, decided from the raw message off the wire when there is one. */
115
+ function outcomeOf(exchange, ctl, ms) {
116
+ const { raw } = exchange;
117
+ if (raw && "result" in raw)
118
+ return { kind: "answered", isError: raw.result.isError === true, reply: raw.result, ms };
119
+ if (raw) {
120
+ const { code, message } = raw.error;
121
+ return {
122
+ kind: "rejected",
123
+ code: typeof code === "number" ? code : 0,
124
+ message: typeof message === "string" ? message : "",
125
+ reply: raw.error,
126
+ ms,
127
+ };
128
+ }
129
+ if (exchange.tooLarge !== undefined)
130
+ return { kind: "too_large", bytes: exchange.tooLarge, limit: maxReplyBytes, ms };
131
+ if (ctl.cause === "host")
132
+ return aborted(exchange.sent, ms);
133
+ if (ctl.cause === "timeout")
134
+ return unreachable({ reason: "call_timeout", message: "the call timed out" }, exchange.sent, ms);
135
+ if (exchange.lost)
136
+ return unreachable({ reason: "disconnected", message: "the connection ended" }, exchange.sent, ms);
137
+ if (exchange.error === undefined)
138
+ return unreachable({
139
+ reason: "bad_reply",
140
+ message: "the SDK returned a reply the client could not read off the wire",
141
+ }, exchange.sent, ms);
142
+ return unreachable(faultOf(exchange.error, "call"), exchange.sent, ms);
143
+ }
144
+ /** Whether a request can be sent again on a new session without risking a second run. */
145
+ function resendable(exchange, session, ctl) {
146
+ if (exchange.raw || exchange.tooLarge !== undefined || ctl.cause)
147
+ return false;
148
+ if (!exchange.sent && session.ended)
149
+ return true;
150
+ return session.hasServerSession && sessionForgotten(exchange.error);
151
+ }
152
+ /** Runs `request` on the key's session, once more on a new session when the first one is gone. */
153
+ async function viaSession(server, ctl, t0, request) {
154
+ for (let attempt = 0;; attempt++) {
155
+ let session;
156
+ try {
157
+ session = await ctl.race(acquire(server));
158
+ }
159
+ catch (error) {
160
+ return { start: startOutcome(error, ctl, Math.round(performance.now() - t0)) };
161
+ }
162
+ const exchange = await request(session);
163
+ if (attempt === 0 && resendable(exchange, session, ctl)) {
164
+ void session.close("forgotten");
165
+ continue;
166
+ }
167
+ return { exchange, session };
168
+ }
169
+ }
170
+ return {
171
+ async call(server, { tool, arguments: args }, { signal, timeoutMs }) {
172
+ const t0 = performance.now();
173
+ const ctl = control(signal, timeoutMs);
174
+ try {
175
+ // A fresh copy of the arguments per attempt: its identity is how the reply is matched to this call.
176
+ const done = await viaSession(server, ctl, t0, (session) => session.call(tool.listed, tool.name, { ...args }, ctl.signal));
177
+ if ("start" in done)
178
+ return done.start;
179
+ return outcomeOf(done.exchange, ctl, Math.round(performance.now() - t0));
180
+ }
181
+ finally {
182
+ ctl.dispose();
183
+ }
184
+ },
185
+ async list(server, opts) {
186
+ const t0 = performance.now();
187
+ const ctl = control(opts?.signal, opts?.timeoutMs ?? connectTimeoutMs);
188
+ const ms = () => Math.round(performance.now() - t0);
189
+ try {
190
+ const tools = [];
191
+ let cursor;
192
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
193
+ const done = await viaSession(server, ctl, t0, (session) => session.listPage(cursor, ctl.signal));
194
+ if ("start" in done)
195
+ return done.start;
196
+ const outcome = outcomeOf(done.exchange, ctl, ms());
197
+ if (outcome.kind === "rejected" ||
198
+ outcome.kind === "unreachable" ||
199
+ outcome.kind === "aborted")
200
+ return outcome;
201
+ if (outcome.kind === "too_large")
202
+ return unreachable({
203
+ reason: "bad_reply",
204
+ message: `a tool list page is larger than ${maxReplyBytes} bytes`,
205
+ }, true, ms());
206
+ const { tools: listed, nextCursor } = outcome.reply;
207
+ if (!Array.isArray(listed))
208
+ return unreachable({ reason: "bad_reply", message: "the tool list has no tools array" }, true, ms());
209
+ tools.push(...listed);
210
+ if (typeof nextCursor !== "string" || nextCursor === "") {
211
+ const { session } = done;
212
+ return {
213
+ server: session.server,
214
+ protocolVersion: session.protocolVersion,
215
+ ...(session.instructions === undefined ? {} : { instructions: session.instructions }),
216
+ tools,
217
+ };
218
+ }
219
+ cursor = nextCursor;
220
+ }
221
+ return unreachable({ reason: "bad_reply", message: `the tool list has more than ${MAX_LIST_PAGES} pages` }, true, ms());
222
+ }
223
+ finally {
224
+ ctl.dispose();
225
+ }
226
+ },
227
+ async check(server, opts) {
228
+ const t0 = performance.now();
229
+ const ms = () => Math.round(performance.now() - t0);
230
+ const timeoutMs = opts?.timeoutMs ?? connectTimeoutMs;
231
+ const live = entries.get(server.key)?.session;
232
+ if (live && !live.ended) {
233
+ // Half the time for the ping; the handshake after it gets what is left, so the whole
234
+ // check stays within `timeoutMs`.
235
+ const ctl = control(opts?.signal, timeoutMs / 2);
236
+ try {
237
+ const { raw } = await live.ping(ctl.signal);
238
+ // A server without ping answers with an error, which still shows the session is alive.
239
+ if (raw)
240
+ return { kind: "reachable", server: live.server, ms: ms() };
241
+ if (ctl.cause === "host")
242
+ return aborted(true, ms());
243
+ }
244
+ finally {
245
+ ctl.dispose();
246
+ }
247
+ // No reply to the ping: calls on the live session are left alone, and the answer comes
248
+ // from a handshake of its own.
249
+ }
250
+ const ctl = control(opts?.signal);
251
+ try {
252
+ const session = await Session.open(server, cfg, {
253
+ signal: ctl.signal,
254
+ timeoutMs: Math.max(1, timeoutMs - ms()),
255
+ idleCloseMs: 0,
256
+ });
257
+ await session.close();
258
+ return { kind: "reachable", server: session.server, ms: ms() };
259
+ }
260
+ catch (error) {
261
+ if (ctl.cause === "host")
262
+ return aborted(false, ms());
263
+ return unreachable(faultOf(error, "start"), false, ms());
264
+ }
265
+ finally {
266
+ ctl.dispose();
267
+ }
268
+ },
269
+ async close(key) {
270
+ const targets = key === undefined ? [...entries.keys()] : [key];
271
+ await Promise.all(targets.map(async (target) => {
272
+ const entry = entries.get(target);
273
+ entries.delete(target);
274
+ const session = (await entry?.starting?.catch(() => undefined)) ?? entry?.session;
275
+ await session?.close();
276
+ }));
277
+ },
278
+ };
279
+ }
@@ -0,0 +1,7 @@
1
+ import type { ContentPart, JsonObject } from "./types.js";
2
+ /**
3
+ * What a model can read from a tool's raw reply. Blocks it cannot carry become a line saying what
4
+ * was left out. A reply with only structured content becomes that JSON as text. Cutting a long
5
+ * reply to size and storing media are the host's.
6
+ */
7
+ export declare function toContent(reply: JsonObject): ContentPart[];
@@ -0,0 +1,54 @@
1
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
+ const str = (value) => typeof value === "string" ? value : undefined;
3
+ const text = (value) => ({ type: "text", text: value });
4
+ function block(item) {
5
+ if (!isObject(item))
6
+ return text("[a content block that is not an object was left out]");
7
+ const type = str(item.type);
8
+ switch (type) {
9
+ case "text": {
10
+ const value = str(item.text);
11
+ return value === undefined ? text('[a "text" block with no text was left out]') : text(value);
12
+ }
13
+ case "image": {
14
+ const data = str(item.data);
15
+ const mediaType = str(item.mimeType);
16
+ if (data === undefined || mediaType === undefined)
17
+ return text('[an "image" block with no data or type was left out]');
18
+ return { type: "media", mediaType, source: { data } };
19
+ }
20
+ case "audio":
21
+ return text(`[audio${typeNote(item.mimeType)} was left out]`);
22
+ case "resource_link": {
23
+ const name = str(item.name) ?? "(unnamed)";
24
+ return text(`${name}: ${str(item.uri) ?? "(no uri)"}`);
25
+ }
26
+ case "resource": {
27
+ const resource = item.resource;
28
+ if (isObject(resource)) {
29
+ const embedded = str(resource.text);
30
+ if (embedded !== undefined)
31
+ return text(embedded);
32
+ return text(`[binary resource ${str(resource.uri) ?? "(no uri)"}${typeNote(resource.mimeType)} was left out]`);
33
+ }
34
+ return text('[a "resource" block with no resource was left out]');
35
+ }
36
+ default:
37
+ return text(`[a content block of type ${JSON.stringify(type ?? null)} was left out]`);
38
+ }
39
+ }
40
+ function typeNote(mimeType) {
41
+ const value = str(mimeType);
42
+ return value === undefined ? "" : ` (${value})`;
43
+ }
44
+ /**
45
+ * What a model can read from a tool's raw reply. Blocks it cannot carry become a line saying what
46
+ * was left out. A reply with only structured content becomes that JSON as text. Cutting a long
47
+ * reply to size and storing media are the host's.
48
+ */
49
+ export function toContent(reply) {
50
+ const parts = Array.isArray(reply.content) ? reply.content.map(block) : [];
51
+ if (parts.length === 0 && reply.structuredContent !== undefined)
52
+ return [text(JSON.stringify(reply.structuredContent))];
53
+ return parts;
54
+ }
@@ -0,0 +1,6 @@
1
+ import type { Unreachable } from "./types.js";
2
+ export type Fault = Pick<Unreachable, "reason" | "httpStatus" | "message">;
3
+ /** What the SDK or the network threw when no reply arrived, as an `unreachable` reason. */
4
+ export declare function faultOf(error: unknown, phase: "start" | "call"): Fault;
5
+ /** The server said it does not know this session (a 404, or a 400 "not initialized"): the call did not run. */
6
+ export declare function sessionForgotten(error: unknown): boolean;
@@ -0,0 +1,48 @@
1
+ import { ProtocolError, SdkError, SdkErrorCode, SdkHttpError, UnauthorizedError, } from "@modelcontextprotocol/client";
2
+ function describe(error) {
3
+ if (!(error instanceof Error))
4
+ return String(error).slice(0, 500);
5
+ const cause = error.cause instanceof Error ? `: ${error.cause.message}` : "";
6
+ return `${error.message}${cause}`.slice(0, 500);
7
+ }
8
+ /** What the SDK or the network threw when no reply arrived, as an `unreachable` reason. */
9
+ export function faultOf(error, phase) {
10
+ const message = describe(error);
11
+ const other = phase === "start" ? "start_failed" : "bad_reply";
12
+ if (error instanceof UnauthorizedError)
13
+ return { reason: "unauthorized", httpStatus: 401, message };
14
+ if (error instanceof SdkHttpError) {
15
+ const status = error.status;
16
+ if (status === 401)
17
+ return { reason: "unauthorized", httpStatus: status, message };
18
+ if (status === 403)
19
+ return { reason: "forbidden", httpStatus: status, message };
20
+ if (status === 429)
21
+ return { reason: "rate_limited", httpStatus: status, message };
22
+ if (status >= 500)
23
+ return { reason: "server_error", httpStatus: status, message };
24
+ return { reason: other, httpStatus: status, message };
25
+ }
26
+ if (error instanceof SdkError) {
27
+ if (error.code === SdkErrorCode.RequestTimeout)
28
+ return { reason: phase === "start" ? "connect_timeout" : "call_timeout", message };
29
+ if (error.code === SdkErrorCode.ConnectionClosed || error.code === SdkErrorCode.NotConnected)
30
+ return { reason: phase === "start" ? "start_failed" : "disconnected", message };
31
+ return { reason: "bad_reply", message };
32
+ }
33
+ // fetch rejects with a TypeError for a refused, reset or unresolvable connection.
34
+ if (error instanceof TypeError)
35
+ return { reason: phase === "start" ? "start_failed" : "disconnected", message };
36
+ if (error instanceof SyntaxError || error instanceof ProtocolError)
37
+ return { reason: "bad_reply", message };
38
+ return { reason: other, message };
39
+ }
40
+ /** The server said it does not know this session (a 404, or a 400 "not initialized"): the call did not run. */
41
+ export function sessionForgotten(error) {
42
+ if (!(error instanceof SdkHttpError))
43
+ return false;
44
+ if (error.status === 404)
45
+ return true;
46
+ const { text } = error.data;
47
+ return error.status === 400 && typeof text === "string" && /initializ|session/i.test(text);
48
+ }
@@ -0,0 +1,4 @@
1
+ export { createMcpClient } from "./client.js";
2
+ export { toContent } from "./content.js";
3
+ export { describeTool, pin, pinHash, toCatalogue, toTools } from "./pin.js";
4
+ export type * from "./types.js";
@@ -0,0 +1,3 @@
1
+ export { createMcpClient } from "./client.js";
2
+ export { toContent } from "./content.js";
3
+ export { describeTool, pin, pinHash, toCatalogue, toTools } from "./pin.js";
@@ -0,0 +1,31 @@
1
+ import type { Listing, Pin, PinnedTool, PinProblem, ToolDefinition } from "./types.js";
2
+ /** Keeps the named tools, exactly as the server listed them, or says what cannot be offered. */
3
+ export declare function pin(listing: Listing, choose: {
4
+ tools: string[];
5
+ pinnedAt: string;
6
+ }): {
7
+ pin: Pin;
8
+ } | {
9
+ problems: PinProblem[];
10
+ };
11
+ /** sha256 (hex) of the pin's canonical JSON: key order does not change it. */
12
+ export declare function pinHash(pinned: Pin): string;
13
+ /**
14
+ * The model's tool definitions for a pin. The schema is carried as listed, never parsed into
15
+ * another schema library and back. `modelName` decides the name the model sees; the default is
16
+ * the server's.
17
+ */
18
+ export declare function toTools(pinned: Pin, opts?: {
19
+ modelName?: (tool: string) => string;
20
+ }): {
21
+ tools: ToolDefinition[];
22
+ } | {
23
+ problems: PinProblem[];
24
+ };
25
+ /** One line per tool: the host's id and the first sentence of the pinned description. */
26
+ export declare function toCatalogue(entries: {
27
+ id: string;
28
+ tool: PinnedTool;
29
+ }[]): string;
30
+ /** A tool's description and input schema as text, for a model that asks to read it. */
31
+ export declare function describeTool(id: string, tool: PinnedTool): string;
@@ -0,0 +1,153 @@
1
+ import { createHash } from "node:crypto";
2
+ /** Providers (Anthropic, OpenAI) take this pattern; 64 characters is the safe length. */
3
+ const MODEL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
4
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ function toolProblem(tool) {
6
+ const invalid = (text) => ({ kind: "invalid_tool", text });
7
+ if (typeof tool.name !== "string" || tool.name === "")
8
+ return invalid("it has no name");
9
+ const schema = tool.inputSchema;
10
+ if (!isObject(schema) || schema.type !== "object")
11
+ return invalid("its inputSchema is not an object schema");
12
+ if (tool.description !== undefined && typeof tool.description !== "string")
13
+ return invalid("its description is not a string");
14
+ const execution = tool.execution;
15
+ if (isObject(execution) && execution.taskSupport === "required")
16
+ return {
17
+ kind: "task_required",
18
+ text: "it needs MCP's task protocol, which this client does not speak",
19
+ };
20
+ return undefined;
21
+ }
22
+ /** Keeps the named tools, exactly as the server listed them, or says what cannot be offered. */
23
+ export function pin(listing, choose) {
24
+ const problems = [];
25
+ const tools = [];
26
+ const chosen = new Set();
27
+ for (const name of choose.tools) {
28
+ if (chosen.has(name)) {
29
+ problems.push({
30
+ tool: name,
31
+ problem: "duplicate_choice",
32
+ message: `"${name}" is chosen twice`,
33
+ });
34
+ continue;
35
+ }
36
+ chosen.add(name);
37
+ const listed = listing.tools.find((tool) => isObject(tool) && tool.name === name);
38
+ if (!listed) {
39
+ problems.push({
40
+ tool: name,
41
+ problem: "not_listed",
42
+ message: `the server does not list "${name}"`,
43
+ });
44
+ continue;
45
+ }
46
+ const problem = toolProblem(listed);
47
+ if (problem) {
48
+ problems.push({
49
+ tool: name,
50
+ problem: problem.kind,
51
+ message: `"${name}" cannot be offered: ${problem.text}`,
52
+ });
53
+ continue;
54
+ }
55
+ tools.push({ name, listed });
56
+ }
57
+ if (problems.length > 0)
58
+ return { problems };
59
+ const { server, protocolVersion, instructions } = listing;
60
+ return {
61
+ pin: {
62
+ format: 1,
63
+ server: { name: server.name, version: server.version, protocolVersion },
64
+ pinnedAt: choose.pinnedAt,
65
+ ...(instructions === undefined ? {} : { instructions }),
66
+ tools,
67
+ },
68
+ };
69
+ }
70
+ function canonical(value) {
71
+ if (Array.isArray(value))
72
+ return `[${value.map(canonical).join(",")}]`;
73
+ if (isObject(value)) {
74
+ const keys = Object.keys(value)
75
+ .filter((key) => value[key] !== undefined)
76
+ .sort();
77
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
78
+ }
79
+ return JSON.stringify(value);
80
+ }
81
+ /** sha256 (hex) of the pin's canonical JSON: key order does not change it. */
82
+ export function pinHash(pinned) {
83
+ return createHash("sha256")
84
+ .update(canonical(pinned))
85
+ .digest("hex");
86
+ }
87
+ function description(tool) {
88
+ const { description, title } = tool.listed;
89
+ if (typeof description === "string")
90
+ return description;
91
+ return typeof title === "string" ? title : "";
92
+ }
93
+ /**
94
+ * The model's tool definitions for a pin. The schema is carried as listed, never parsed into
95
+ * another schema library and back. `modelName` decides the name the model sees; the default is
96
+ * the server's.
97
+ */
98
+ export function toTools(pinned, opts) {
99
+ const problems = [];
100
+ const names = new Set();
101
+ const tools = [];
102
+ for (const tool of pinned.tools) {
103
+ const name = opts?.modelName ? opts.modelName(tool.name) : tool.name;
104
+ if (!MODEL_NAME.test(name)) {
105
+ problems.push({
106
+ tool: tool.name,
107
+ problem: "bad_model_name",
108
+ message: `"${name}" is not a name providers accept (letters, digits, "_" and "-", up to 64)`,
109
+ });
110
+ }
111
+ else if (names.has(name)) {
112
+ problems.push({
113
+ tool: tool.name,
114
+ problem: "duplicate_model_name",
115
+ message: `two tools would be called "${name}"`,
116
+ });
117
+ }
118
+ names.add(name);
119
+ tools.push({
120
+ type: "function",
121
+ name,
122
+ description: description(tool),
123
+ inputSchema: tool.listed.inputSchema,
124
+ });
125
+ }
126
+ return problems.length > 0 ? { problems } : { tools };
127
+ }
128
+ function firstSentence(text) {
129
+ const flat = text.replace(/\s+/g, " ").trim();
130
+ const end = flat.search(/[.!?](\s|$)/);
131
+ const sentence = end === -1 ? flat : flat.slice(0, end + 1);
132
+ return sentence.length > 200 ? `${sentence.slice(0, 199)}…` : sentence;
133
+ }
134
+ /** One line per tool: the host's id and the first sentence of the pinned description. */
135
+ export function toCatalogue(entries) {
136
+ return entries
137
+ .map(({ id, tool }) => {
138
+ const sentence = firstSentence(description(tool));
139
+ return sentence === "" ? id : `${id}: ${sentence}`;
140
+ })
141
+ .join("\n");
142
+ }
143
+ /** A tool's description and input schema as text, for a model that asks to read it. */
144
+ export function describeTool(id, tool) {
145
+ const text = description(tool);
146
+ return [
147
+ id,
148
+ ...(text === "" ? [] : ["", text]),
149
+ "",
150
+ "Input schema:",
151
+ JSON.stringify(tool.listed.inputSchema, null, 2),
152
+ ].join("\n");
153
+ }
@@ -0,0 +1,14 @@
1
+ /** Thrown into the body stream of a reply that went over the limit. */
2
+ export declare class ReplyTooLarge extends Error {
3
+ readonly bytes: number;
4
+ constructor(bytes: number);
5
+ }
6
+ type Fetch = typeof fetch;
7
+ /**
8
+ * Wraps the host's `fetch` so a reply to a JSON-RPC request is stopped at `limit` bytes, before
9
+ * it is read into memory. Only POST replies are metered: the long-lived GET event stream is not
10
+ * one reply. `onOver` names the request (when its body shows an id), because the SDK swallows a
11
+ * stream error on an SSE reply and leaves the call waiting until its timeout.
12
+ */
13
+ export declare function limitReplies(inner: Fetch, limit: number, onOver: (id: number | string, bytes: number) => void): Fetch;
14
+ export {};
@@ -0,0 +1,59 @@
1
+ /** Thrown into the body stream of a reply that went over the limit. */
2
+ export class ReplyTooLarge extends Error {
3
+ bytes;
4
+ constructor(bytes) {
5
+ super(`reply is larger than the limit (at least ${bytes} bytes)`);
6
+ this.bytes = bytes;
7
+ }
8
+ }
9
+ /** The JSON-RPC id of a POSTed request, when the body shows one. */
10
+ function requestId(init) {
11
+ if (typeof init?.body !== "string")
12
+ return undefined;
13
+ try {
14
+ const id = JSON.parse(init.body).id;
15
+ return typeof id === "number" || typeof id === "string" ? id : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /**
22
+ * Wraps the host's `fetch` so a reply to a JSON-RPC request is stopped at `limit` bytes, before
23
+ * it is read into memory. Only POST replies are metered: the long-lived GET event stream is not
24
+ * one reply. `onOver` names the request (when its body shows an id), because the SDK swallows a
25
+ * stream error on an SSE reply and leaves the call waiting until its timeout.
26
+ */
27
+ export function limitReplies(inner, limit, onOver) {
28
+ return async (input, init) => {
29
+ const response = await inner(input, init);
30
+ if (init?.method !== "POST" || response.body === null)
31
+ return response;
32
+ const id = requestId(init);
33
+ const declared = Number(response.headers.get("content-length"));
34
+ if (declared > limit) {
35
+ void response.body.cancel().catch(() => { });
36
+ if (id !== undefined)
37
+ onOver(id, declared);
38
+ throw new ReplyTooLarge(declared);
39
+ }
40
+ let seen = 0;
41
+ const body = response.body.pipeThrough(new TransformStream({
42
+ transform(chunk, controller) {
43
+ seen += chunk.byteLength;
44
+ if (seen > limit) {
45
+ if (id !== undefined)
46
+ onOver(id, seen);
47
+ controller.error(new ReplyTooLarge(seen));
48
+ return;
49
+ }
50
+ controller.enqueue(chunk);
51
+ },
52
+ }));
53
+ return new Response(body, {
54
+ status: response.status,
55
+ statusText: response.statusText,
56
+ headers: response.headers,
57
+ });
58
+ };
59
+ }
@@ -0,0 +1,96 @@
1
+ import type { JsonObject, McpEvent, Server } from "./types.js";
2
+ export interface SessionConfig {
3
+ clientInfo: {
4
+ name: string;
5
+ version: string;
6
+ };
7
+ maxReplyBytes: number;
8
+ fetch: typeof fetch;
9
+ onEvent?: (event: McpEvent) => void;
10
+ }
11
+ export type SessionEnd = Extract<McpEvent, {
12
+ type: "session_ended";
13
+ }>["reason"];
14
+ /** One request's trip over the wire. The caller reads it when `exchange` returns. */
15
+ export interface Exchange {
16
+ /** True once the transport took the request: from then on it may have run. */
17
+ sent: boolean;
18
+ /** The session ended while the request was in flight and no reply had come. */
19
+ lost?: boolean;
20
+ /** The JSON-RPC response as it came off the wire, before the SDK parsed or rejected it. */
21
+ raw?: {
22
+ result: JsonObject;
23
+ } | {
24
+ error: JsonObject;
25
+ };
26
+ /** What the SDK threw, when it threw. */
27
+ error?: unknown;
28
+ /** The reply was stopped at the size limit; at least this many bytes. */
29
+ tooLarge?: number;
30
+ id?: number | string;
31
+ }
32
+ /**
33
+ * A live link to one MCP server. It reads each reply under the SDK: the transport's `send` names
34
+ * the request id of the request being made (a call is matched through the identity of its
35
+ * `arguments`, which reaches `send` unchanged; a list or ping through a reference in `_meta`,
36
+ * which survives the SDK rebuilding `params`), and the incoming-message hook keeps the raw
37
+ * response for that id. The outcome is decided from that raw message, not from what the SDK made
38
+ * of it.
39
+ *
40
+ * A session is `ended` from the moment anything starts ending it (close, idle timer, a reply over
41
+ * the limit, the transport closing), and leaves its registry then: the teardown that follows may
42
+ * take seconds and must not receive new requests.
43
+ */
44
+ export declare class Session {
45
+ readonly key: string;
46
+ private readonly cfg;
47
+ private readonly idleCloseMs;
48
+ /** Set by the registry; called once, when the session starts ending. */
49
+ onEnded?: (reason: SessionEnd) => void;
50
+ ended: boolean;
51
+ server: {
52
+ name: string;
53
+ version: string;
54
+ };
55
+ protocolVersion: string;
56
+ instructions: string | undefined;
57
+ private readonly client;
58
+ private readonly transport;
59
+ private readonly waiting;
60
+ private readonly byId;
61
+ private readonly aborts;
62
+ private closing;
63
+ private refs;
64
+ private active;
65
+ private idleTimer;
66
+ private constructor();
67
+ /** Starts the process or the HTTP session and does the handshake. Throws what the SDK threw. */
68
+ static open(server: Server, cfg: SessionConfig, opts: {
69
+ signal?: AbortSignal;
70
+ timeoutMs: number;
71
+ idleCloseMs: number;
72
+ }): Promise<Session>;
73
+ get transportKind(): "stdio" | "http";
74
+ /** An HTTP server that issued a session id can forget it; a stateless one cannot. */
75
+ get hasServerSession(): boolean;
76
+ private makeTransport;
77
+ private tap;
78
+ private replyTooLarge;
79
+ private stdioReplyTooLarge;
80
+ /** The one place a session starts ending. Synchronous, so no later request can reach it. */
81
+ private finish;
82
+ private armIdle;
83
+ /**
84
+ * Runs one request. `token` is what `send` will see to tell it from the others: the `arguments`
85
+ * object of a call, or the reference `run` put in a list or ping's `_meta`. Never throws: the
86
+ * Exchange says what happened.
87
+ */
88
+ private exchange;
89
+ call(tool: JsonObject, name: string, args: JsonObject, signal: AbortSignal): Promise<Exchange>;
90
+ /** A request without arguments of its own: `_meta` carries what tells it from the others. */
91
+ private plain;
92
+ listPage(cursor: string | undefined, signal: AbortSignal): Promise<Exchange>;
93
+ ping(signal: AbortSignal): Promise<Exchange>;
94
+ close(reason?: SessionEnd): Promise<void>;
95
+ private shutDown;
96
+ }
@@ -0,0 +1,280 @@
1
+ import { Client, SdkError, SdkErrorCode, StreamableHTTPClientTransport, } from "@modelcontextprotocol/client";
2
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
3
+ import { limitReplies } from "./reply-limit.js";
4
+ // The SDK's own timeout would otherwise default to 60 s; every call's deadline is the client's.
5
+ const NO_SDK_TIMEOUT = 2 ** 31 - 1;
6
+ const BUFFER_EXCEEDED = "ReadBuffer exceeded";
7
+ // Marks a list or ping request: the SDK may rebuild `params` but keeps what is in `_meta`.
8
+ const REF_KEY = "io.meridian-flow/ref";
9
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10
+ function lines(onLine) {
11
+ let rest = "";
12
+ return (chunk) => {
13
+ const parts = (rest + chunk.toString("utf8")).split("\n");
14
+ rest = parts.pop() ?? "";
15
+ for (const part of parts)
16
+ if (part.trim() !== "")
17
+ onLine(part.replace(/\r$/, ""));
18
+ };
19
+ }
20
+ /**
21
+ * A live link to one MCP server. It reads each reply under the SDK: the transport's `send` names
22
+ * the request id of the request being made (a call is matched through the identity of its
23
+ * `arguments`, which reaches `send` unchanged; a list or ping through a reference in `_meta`,
24
+ * which survives the SDK rebuilding `params`), and the incoming-message hook keeps the raw
25
+ * response for that id. The outcome is decided from that raw message, not from what the SDK made
26
+ * of it.
27
+ *
28
+ * A session is `ended` from the moment anything starts ending it (close, idle timer, a reply over
29
+ * the limit, the transport closing), and leaves its registry then: the teardown that follows may
30
+ * take seconds and must not receive new requests.
31
+ */
32
+ export class Session {
33
+ key;
34
+ cfg;
35
+ idleCloseMs;
36
+ /** Set by the registry; called once, when the session starts ending. */
37
+ onEnded;
38
+ ended = false;
39
+ server = { name: "", version: "" };
40
+ protocolVersion = "";
41
+ instructions;
42
+ client;
43
+ transport;
44
+ waiting = new Map();
45
+ byId = new Map();
46
+ aborts = new Map();
47
+ closing;
48
+ refs = 0;
49
+ active = 0;
50
+ idleTimer;
51
+ constructor(key, spec, cfg, idleCloseMs) {
52
+ this.key = key;
53
+ this.cfg = cfg;
54
+ this.idleCloseMs = idleCloseMs;
55
+ this.transport = this.makeTransport(spec);
56
+ this.client = new Client(cfg.clientInfo, {
57
+ // Announces no sampling, elicitation or roots: a server cannot ask the model or the user.
58
+ capabilities: {},
59
+ versionNegotiation: { mode: "legacy" },
60
+ });
61
+ this.tap();
62
+ }
63
+ /** Starts the process or the HTTP session and does the handshake. Throws what the SDK threw. */
64
+ static async open(server, cfg, opts) {
65
+ const session = new Session(server.key, server.spec, cfg, opts.idleCloseMs);
66
+ try {
67
+ await session.client.connect(session.transport, {
68
+ timeout: opts.timeoutMs,
69
+ ...(opts.signal ? { signal: opts.signal } : {}),
70
+ });
71
+ }
72
+ catch (error) {
73
+ session.ended = true;
74
+ clearTimeout(session.idleTimer);
75
+ await session.client.close().catch(() => { });
76
+ throw error;
77
+ }
78
+ const info = session.client.getServerVersion();
79
+ session.server = { name: info?.name ?? "", version: info?.version ?? "" };
80
+ session.protocolVersion = session.client.getNegotiatedProtocolVersion() ?? "";
81
+ session.instructions = session.client.getInstructions();
82
+ cfg.onEvent?.({
83
+ type: "session_started",
84
+ key: server.key,
85
+ transport: server.spec.transport,
86
+ });
87
+ session.armIdle();
88
+ return session;
89
+ }
90
+ get transportKind() {
91
+ return this.transport instanceof StreamableHTTPClientTransport ? "http" : "stdio";
92
+ }
93
+ /** An HTTP server that issued a session id can forget it; a stateless one cannot. */
94
+ get hasServerSession() {
95
+ return this.transport instanceof StreamableHTTPClientTransport && !!this.transport.sessionId;
96
+ }
97
+ makeTransport(spec) {
98
+ const { cfg, key } = this;
99
+ if (spec.transport === "stdio") {
100
+ const transport = new StdioClientTransport({
101
+ command: spec.command,
102
+ ...(spec.args ? { args: spec.args } : {}),
103
+ ...(spec.env ? { env: spec.env } : {}),
104
+ ...(spec.cwd ? { cwd: spec.cwd } : {}),
105
+ stderr: "pipe",
106
+ maxBufferSize: cfg.maxReplyBytes,
107
+ });
108
+ transport.stderr?.on("data", lines((line) => cfg.onEvent?.({ type: "stderr", key, line })));
109
+ return transport;
110
+ }
111
+ const { auth, headers } = spec;
112
+ return new StreamableHTTPClientTransport(new URL(spec.url), {
113
+ fetch: limitReplies(cfg.fetch, cfg.maxReplyBytes, (id, bytes) => this.replyTooLarge(id, bytes)),
114
+ ...(headers ? { requestInit: { headers } } : {}),
115
+ ...(auth
116
+ ? {
117
+ authProvider: {
118
+ token: () => auth.token(),
119
+ ...(auth.refresh
120
+ ? { onUnauthorized: async () => void (await auth.refresh?.()) }
121
+ : {}),
122
+ },
123
+ }
124
+ : {}),
125
+ // Never "follow": fetch would carry the token and custom headers to another origin.
126
+ redirectPolicy: "same-origin",
127
+ });
128
+ }
129
+ tap() {
130
+ const { transport } = this;
131
+ // Set before connect(): the SDK chains the hooks it finds and runs ours first.
132
+ transport.onmessage = (message) => {
133
+ if (!("id" in message) || message.id === undefined || "method" in message)
134
+ return;
135
+ const exchange = this.byId.get(message.id);
136
+ if (!exchange)
137
+ return;
138
+ if ("result" in message && isObject(message.result))
139
+ exchange.raw = { result: message.result };
140
+ else if ("error" in message)
141
+ exchange.raw = { error: message.error };
142
+ };
143
+ transport.onerror = (error) => {
144
+ // The stdio reader closes the transport when a line passes the limit, and says so only here.
145
+ if (error.message.startsWith(BUFFER_EXCEEDED))
146
+ this.stdioReplyTooLarge();
147
+ };
148
+ this.client.onclose = () => this.finish("disconnected");
149
+ const send = transport.send.bind(transport);
150
+ transport.send = async (message, options) => {
151
+ let exchange;
152
+ if ("method" in message && "id" in message && message.id !== undefined) {
153
+ const params = message.params;
154
+ const token = message.method === "tools/call" ? params?.arguments : params?._meta?.[REF_KEY];
155
+ exchange =
156
+ typeof token === "string" || isObject(token) ? this.waiting.get(token) : undefined;
157
+ if (exchange) {
158
+ exchange.sent = true;
159
+ exchange.id = message.id;
160
+ this.byId.set(message.id, exchange);
161
+ }
162
+ }
163
+ try {
164
+ await send(message, options);
165
+ }
166
+ catch (error) {
167
+ // Not connected means nothing was written, so the request can safely go to a new session.
168
+ if (exchange && error instanceof SdkError && error.code === SdkErrorCode.NotConnected)
169
+ exchange.sent = false;
170
+ throw error;
171
+ }
172
+ };
173
+ }
174
+ replyTooLarge(id, bytes) {
175
+ const exchange = this.byId.get(id);
176
+ if (!exchange)
177
+ return;
178
+ exchange.tooLarge = bytes;
179
+ this.aborts.get(exchange)?.();
180
+ }
181
+ stdioReplyTooLarge() {
182
+ // Which call's reply it was is known only when one call is in flight.
183
+ const only = this.byId.size === 1 ? [...this.byId.values()][0] : undefined;
184
+ if (only)
185
+ only.tooLarge = this.cfg.maxReplyBytes + 1;
186
+ void this.close("too_large");
187
+ }
188
+ /** The one place a session starts ending. Synchronous, so no later request can reach it. */
189
+ finish(reason) {
190
+ if (this.ended)
191
+ return;
192
+ this.ended = true;
193
+ clearTimeout(this.idleTimer);
194
+ this.cfg.onEvent?.({ type: "session_ended", key: this.key, reason });
195
+ this.onEnded?.(reason);
196
+ // No more replies are coming, so the calls in flight settle now, not when a child process
197
+ // finally exits. A forgotten session is different: each call's own reply is still on the wire.
198
+ if (reason === "forgotten")
199
+ return;
200
+ for (const [exchange, abort] of this.aborts) {
201
+ exchange.lost = true;
202
+ abort();
203
+ }
204
+ }
205
+ armIdle() {
206
+ clearTimeout(this.idleTimer);
207
+ if (this.idleCloseMs <= 0 || this.active > 0 || this.ended)
208
+ return;
209
+ this.idleTimer = setTimeout(() => void this.close("idle"), this.idleCloseMs);
210
+ this.idleTimer.unref();
211
+ }
212
+ /**
213
+ * Runs one request. `token` is what `send` will see to tell it from the others: the `arguments`
214
+ * object of a call, or the reference `run` put in a list or ping's `_meta`. Never throws: the
215
+ * Exchange says what happened.
216
+ */
217
+ async exchange(token, signal, run) {
218
+ const exchange = { sent: false };
219
+ const own = new AbortController();
220
+ this.active++;
221
+ clearTimeout(this.idleTimer);
222
+ this.waiting.set(token, exchange);
223
+ this.aborts.set(exchange, () => own.abort());
224
+ try {
225
+ await run(AbortSignal.any([signal, own.signal]), NO_SDK_TIMEOUT);
226
+ }
227
+ catch (error) {
228
+ exchange.error = error;
229
+ }
230
+ finally {
231
+ this.waiting.delete(token);
232
+ if (exchange.id !== undefined)
233
+ this.byId.delete(exchange.id);
234
+ this.aborts.delete(exchange);
235
+ this.active--;
236
+ this.armIdle();
237
+ }
238
+ return exchange;
239
+ }
240
+ async call(tool, name, args, signal) {
241
+ // The pinned tool, without outputSchema: handing it over also makes the SDK check the reply
242
+ // against that schema, which would throw away a reply from a tool that ran.
243
+ const { outputSchema: _dropped, ...definition } = tool;
244
+ const params = { name, arguments: args };
245
+ return this.exchange(args, signal, (signal, timeout) => this.client.callTool(params, {
246
+ signal,
247
+ timeout,
248
+ toolDefinition: definition,
249
+ }));
250
+ }
251
+ /** A request without arguments of its own: `_meta` carries what tells it from the others. */
252
+ plain(method, params, signal) {
253
+ const ref = `${++this.refs}`;
254
+ const withRef = { ...params, _meta: { [REF_KEY]: ref } };
255
+ return this.exchange(ref, signal, (signal, timeout) => this.client.request({ method, params: withRef }, { signal, timeout }));
256
+ }
257
+ listPage(cursor, signal) {
258
+ return this.plain("tools/list", cursor === undefined ? {} : { cursor }, signal);
259
+ }
260
+ ping(signal) {
261
+ return this.plain("ping", {}, signal);
262
+ }
263
+ close(reason = "closed") {
264
+ if (!this.closing) {
265
+ this.finish(reason);
266
+ this.closing = this.shutDown();
267
+ }
268
+ return this.closing;
269
+ }
270
+ async shutDown() {
271
+ if (this.transport instanceof StreamableHTTPClientTransport) {
272
+ // Courtesy to the server, which may keep the session in memory until told.
273
+ await Promise.race([
274
+ this.transport.terminateSession().catch(() => { }),
275
+ new Promise((resolve) => setTimeout(resolve, 1000).unref()),
276
+ ]);
277
+ }
278
+ await this.client.close().catch(() => { });
279
+ }
280
+ }
@@ -0,0 +1,182 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export type JsonObject = {
5
+ [key: string]: JsonValue;
6
+ };
7
+ export type ServerSpec = {
8
+ transport: "stdio";
9
+ /** A path the host resolved; the package runs no package manager. */
10
+ command: string;
11
+ args?: string[];
12
+ /** Added on top of the six variables the SDK copies from the host process. */
13
+ env?: Record<string, string>;
14
+ cwd?: string;
15
+ } | {
16
+ transport: "http";
17
+ url: string;
18
+ /** Sent on every request to `url`'s origin, and to no other origin. */
19
+ headers?: Record<string, string>;
20
+ auth?: TokenSource;
21
+ };
22
+ export interface TokenSource {
23
+ /** Asked before every request. */
24
+ token(): Promise<string | undefined>;
25
+ /** Called once after a 401; the request is then sent once more. */
26
+ refresh?(): Promise<void>;
27
+ }
28
+ export interface Server {
29
+ /** The host's name for one session. The client keeps one session per key. */
30
+ key: string;
31
+ spec: ServerSpec;
32
+ }
33
+ export interface McpClientOptions {
34
+ /** Sent to servers in the handshake. */
35
+ clientInfo: {
36
+ name: string;
37
+ version: string;
38
+ };
39
+ /** The handshake's limit. Default 30 s. */
40
+ connectTimeoutMs?: number;
41
+ /** Close a session unused this long. Default 5 min; 0 keeps it. */
42
+ idleCloseMs?: number;
43
+ /** After a failed start, calls fail at once for this long. Default 10 s. */
44
+ failFastMs?: number;
45
+ /** A larger reply is a `too_large` outcome. Default 10 MB. */
46
+ maxReplyBytes?: number;
47
+ /** Used for every HTTP request, so the host can limit where requests go. Default: global `fetch`. */
48
+ fetch?: typeof fetch;
49
+ /** Session started, session ended, a child's stderr line: for the host's logs. */
50
+ onEvent?: (event: McpEvent) => void;
51
+ }
52
+ export type McpEvent = {
53
+ type: "session_started";
54
+ key: string;
55
+ transport: "stdio" | "http";
56
+ } | {
57
+ type: "session_ended";
58
+ key: string;
59
+ reason: "closed" | "idle" | "disconnected" | "forgotten" | "too_large";
60
+ } | {
61
+ type: "stderr";
62
+ key: string;
63
+ line: string;
64
+ };
65
+ export interface McpClient {
66
+ list(server: Server, opts?: {
67
+ signal?: AbortSignal;
68
+ timeoutMs?: number;
69
+ }): Promise<Listing | Rejected | Unreachable | Aborted>;
70
+ call(server: Server, call: {
71
+ tool: PinnedTool;
72
+ arguments: JsonObject;
73
+ }, opts: {
74
+ signal?: AbortSignal;
75
+ timeoutMs: number;
76
+ }): Promise<CallOutcome>;
77
+ check(server: Server, opts?: {
78
+ signal?: AbortSignal;
79
+ timeoutMs?: number;
80
+ }): Promise<Reachable | Unreachable | Aborted>;
81
+ /** One session, or all of them. */
82
+ close(key?: string): Promise<void>;
83
+ }
84
+ export interface Reachable {
85
+ kind: "reachable";
86
+ server: {
87
+ name: string;
88
+ version: string;
89
+ };
90
+ ms: number;
91
+ }
92
+ export interface Listing {
93
+ /** What the server says it is. */
94
+ server: {
95
+ name: string;
96
+ version: string;
97
+ };
98
+ protocolVersion: string;
99
+ /** The server's own text for a model, if it sends one. */
100
+ instructions?: string;
101
+ /** Every tool, exactly as the server listed it. */
102
+ tools: JsonObject[];
103
+ }
104
+ export interface PinnedTool {
105
+ /** The server's name for the tool, sent when it is called. */
106
+ name: string;
107
+ /** The server's tool object, unchanged: description, inputSchema, annotations, ... */
108
+ listed: JsonObject;
109
+ }
110
+ export interface Pin {
111
+ format: 1;
112
+ server: {
113
+ name: string;
114
+ version: string;
115
+ protocolVersion: string;
116
+ };
117
+ pinnedAt: string;
118
+ instructions?: string;
119
+ tools: PinnedTool[];
120
+ }
121
+ export interface PinProblem {
122
+ /** The tool the problem is about, when it has a name. */
123
+ tool?: string;
124
+ problem: "not_listed" | "invalid_tool" | "task_required" | "duplicate_choice" | "bad_model_name" | "duplicate_model_name";
125
+ message: string;
126
+ }
127
+ /** What the model is sent for one tool. Structurally the gateway's `Tool`. */
128
+ export interface ToolDefinition {
129
+ type: "function";
130
+ name: string;
131
+ description: string;
132
+ inputSchema: JsonObject;
133
+ }
134
+ /** Structurally the gateway's `TextPart` and `MediaPart`. */
135
+ export type ContentPart = {
136
+ type: "text";
137
+ text: string;
138
+ } | {
139
+ type: "media";
140
+ mediaType: string;
141
+ source: {
142
+ data: string;
143
+ };
144
+ };
145
+ export type CallOutcome = Answered | Rejected | TooLarge | Unreachable | Aborted;
146
+ /** The tool ran. `isError` is the server's own flag. `reply` is the raw `result` off the wire. */
147
+ export interface Answered {
148
+ kind: "answered";
149
+ isError: boolean;
150
+ reply: JsonObject;
151
+ ms: number;
152
+ }
153
+ /** The server is up and refused the request. `reply` is the raw JSON-RPC error object. */
154
+ export interface Rejected {
155
+ kind: "rejected";
156
+ code: number;
157
+ message: string;
158
+ reply: JsonObject;
159
+ ms: number;
160
+ }
161
+ /** The server answered; the reply was not kept. `bytes` is a lower bound: what was known when reading stopped. */
162
+ export interface TooLarge {
163
+ kind: "too_large";
164
+ bytes: number;
165
+ limit: number;
166
+ ms: number;
167
+ }
168
+ /** The host's signal fired. */
169
+ export interface Aborted {
170
+ kind: "aborted";
171
+ sent: boolean;
172
+ ms: number;
173
+ }
174
+ export interface Unreachable {
175
+ kind: "unreachable";
176
+ reason: "start_failed" | "connect_timeout" | "disconnected" | "call_timeout" | "unauthorized" | "forbidden" | "rate_limited" | "server_error" | "bad_reply";
177
+ httpStatus?: number;
178
+ message: string;
179
+ /** False only when nothing can have left. */
180
+ sent: boolean;
181
+ ms: number;
182
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@meridian-flow/runtime",
3
- "version": "0.2.0",
4
- "description": "What an AI product needs to run models: a provider-neutral streaming model gateway (Anthropic, OpenAI, Gemini, OpenAI-compatible) with retry, deadlines and usage normalization.",
3
+ "version": "0.3.0",
4
+ "description": "What an AI product needs to run models: a provider-neutral streaming model gateway (Anthropic, OpenAI, Gemini, OpenAI-compatible) with retry, deadlines and usage normalization, and an MCP client.",
5
5
  "keywords": [
6
6
  "llm",
7
7
  "ai",
@@ -10,7 +10,9 @@
10
10
  "openai",
11
11
  "gemini",
12
12
  "streaming",
13
- "workload-identity-federation"
13
+ "workload-identity-federation",
14
+ "mcp",
15
+ "model-context-protocol"
14
16
  ],
15
17
  "license": "Apache-2.0",
16
18
  "repository": {
@@ -45,6 +47,10 @@
45
47
  "./gateway/mock-script": {
46
48
  "types": "./dist/gateway/mock-script.d.ts",
47
49
  "default": "./dist/gateway/mock-script.js"
50
+ },
51
+ "./mcp": {
52
+ "types": "./dist/mcp/index.d.ts",
53
+ "default": "./dist/mcp/index.js"
48
54
  }
49
55
  },
50
56
  "meridianRuntime": {
@@ -56,6 +62,7 @@
56
62
  "dependencies": {
57
63
  "@anthropic-ai/sdk": "^1.8.0",
58
64
  "@google/genai": "^3.3.0",
65
+ "@modelcontextprotocol/client": "^2.4.0",
59
66
  "jsonrepair": "^3.15.0",
60
67
  "openai": "^7.57.0",
61
68
  "zod": "^4.6.7"