teapot-coding-agent 0.29.28 → 0.29.29
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/dist/agent/agent.js +75 -10
- package/dist/agent/mcp-registry.js +163 -0
- package/dist/agent/mcp.js +601 -0
- package/dist/agent/plugins.js +311 -0
- package/dist/agent/tools.js +19 -0
- package/dist/config-schema.js +28 -0
- package/dist/master.js +73 -0
- package/dist/server/api.js +78 -2
- package/dist/server/term-size.js +2 -24
- package/package.json +1 -1
- package/public/assets/{index-CBfSYP24.css → index-CCnsAOJa.css} +1 -1
- package/public/assets/{index-yWwPyno7.js → index-CIno4glv.js} +13 -13
- package/public/assets/index-CIno4glv.js.map +1 -0
- package/public/assets/{shiki-Dbem2m6O.js → shiki-DM4FXbBS.js} +2 -2
- package/public/assets/{shiki-Dbem2m6O.js.map → shiki-DM4FXbBS.js.map} +1 -1
- package/public/index.html +2 -2
- package/public/assets/index-yWwPyno7.js.map +0 -1
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP client (#67): the subset of Model Context Protocol teapot actually needs.
|
|
3
|
+
*
|
|
4
|
+
* Scope is deliberately minimal. An MCP server is a source of TOOLS, so what must
|
|
5
|
+
* exist is: connect, discover (`tools/list` with pagination), call (`tools/call`),
|
|
6
|
+
* and the auth headers a remote server demands. No prompts, no resources, no
|
|
7
|
+
* sampling, no roots — adding transports and capabilities that nothing in the harness
|
|
8
|
+
* consumes is how an MCP client becomes a maintenance sink.
|
|
9
|
+
*
|
|
10
|
+
* Transports:
|
|
11
|
+
* - **Streamable HTTP** (the current spec). A POST carries one JSON-RPC message; the
|
|
12
|
+
* reply is either `application/json` or a `text/event-stream` carrying the same
|
|
13
|
+
* message as a `data:` line. Both are handled, because servers differ.
|
|
14
|
+
* - **legacy HTTP+SSE** (2024-11-05): a GET holds an event stream open and the POST
|
|
15
|
+
* replies come back ON THAT STREAM. Detected by trying the modern shape first and
|
|
16
|
+
* falling back when the endpoint refuses POST.
|
|
17
|
+
* - **stdio**: a child process speaking newline-delimited JSON-RPC on stdin/stdout.
|
|
18
|
+
*
|
|
19
|
+
* What is modelled from the reference implementation (akku1139/easywebui,
|
|
20
|
+
* `src/worker/api/mcp-*.ts`) and kept for the same reasons:
|
|
21
|
+
* - read the reply UNTIL the matching `id` arrives instead of awaiting the end of an
|
|
22
|
+
* SSE stream, which may stay open indefinitely;
|
|
23
|
+
* - `Mcp-Session-Id` and `MCP-Protocol-Version` headers on every request after
|
|
24
|
+
* `initialize` — a server that issued a session id rejects requests without it;
|
|
25
|
+
* - `notifications/initialized` as a notification (no id, no reply);
|
|
26
|
+
* - treat a 3xx as an ERROR rather than following it: an MCP endpoint that redirects
|
|
27
|
+
* is usually redirecting to an HTML login page, and following it produces a JSON
|
|
28
|
+
* parse error that hides the real cause;
|
|
29
|
+
* - cap the response size and the pagination loop, and detect a cursor that repeats;
|
|
30
|
+
* - validate each tool definition (`name`, object `inputSchema`) instead of trusting
|
|
31
|
+
* the server, because a malformed tool becomes a malformed function spec sent to
|
|
32
|
+
* the LLM.
|
|
33
|
+
*
|
|
34
|
+
* Deliberately NOT modelled: OAuth. easywebui runs on a serverless edge with no place
|
|
35
|
+
* to keep a token, so it implements a full OAuth dance. teapot runs locally and already
|
|
36
|
+
* has a config file for secrets, so a static header map (`headers`) covers the real
|
|
37
|
+
* cases (a bearer token, an API key) without a redirect flow, a token store, and a
|
|
38
|
+
* refresh timer. If OAuth turns out to be needed, it can be added behind the same
|
|
39
|
+
* `headers` field rather than as a parallel auth path.
|
|
40
|
+
*/
|
|
41
|
+
export class McpError extends Error {
|
|
42
|
+
/** true when the server answered 401/403 — the caller may need to fix a header */
|
|
43
|
+
authRequired;
|
|
44
|
+
// NOT a parameter property (`constructor(msg, readonly x)`) — Node's
|
|
45
|
+
// type-stripping loader refuses that syntax, and `pnpm test` runs the sources
|
|
46
|
+
// directly (ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX).
|
|
47
|
+
constructor(message, authRequired = false) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "McpError";
|
|
50
|
+
this.authRequired = authRequired;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const PROTOCOL_VERSION = "2025-06-18";
|
|
54
|
+
/** versions we accept from a server's `initialize` reply */
|
|
55
|
+
const KNOWN_VERSIONS = ["2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"];
|
|
56
|
+
/** a response larger than this is not a tool result, it is a mistake */
|
|
57
|
+
const MAX_RESPONSE_BYTES = 2_000_000;
|
|
58
|
+
/** hard stop on tools/list pagination ("did not finish" is a real server bug) */
|
|
59
|
+
const MAX_PAGES = 50;
|
|
60
|
+
function parseJson(text, what) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(text);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// keep the offending body visible: servers behind an auth page or proxy answer
|
|
66
|
+
// HTML with a JSON content type, and "invalid JSON" alone hides that
|
|
67
|
+
throw new McpError(`${what} returned invalid JSON: ${text.slice(0, 200)}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** pull the `data:` payloads out of one SSE event block */
|
|
71
|
+
function sseData(block) {
|
|
72
|
+
return block
|
|
73
|
+
.split("\n")
|
|
74
|
+
.filter((l) => l.startsWith("data:"))
|
|
75
|
+
.map((l) => l.slice(5).replace(/^ /, ""))
|
|
76
|
+
.join("\n");
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Read a Streamable-HTTP reply until the JSON-RPC message with `id` arrives.
|
|
80
|
+
*
|
|
81
|
+
* Exported for tests: the two reply shapes (plain JSON, SSE) and the "stream ends
|
|
82
|
+
* without our id" case are exactly what breaks against real servers, and they are
|
|
83
|
+
* awkward to provoke through a live one.
|
|
84
|
+
*/
|
|
85
|
+
export async function readRpcResult(response, id, maxBytes = MAX_RESPONSE_BYTES) {
|
|
86
|
+
const type = response.headers.get("content-type") ?? "";
|
|
87
|
+
const reader = response.body?.getReader();
|
|
88
|
+
if (!reader)
|
|
89
|
+
throw new McpError("MCP server returned an empty response");
|
|
90
|
+
const decoder = new TextDecoder();
|
|
91
|
+
let buf = "";
|
|
92
|
+
let size = 0;
|
|
93
|
+
const resolve = (rpc) => {
|
|
94
|
+
if (rpc.id !== id)
|
|
95
|
+
throw new McpError("Invalid MCP response (id mismatch)");
|
|
96
|
+
if (rpc.error)
|
|
97
|
+
throw new McpError(`MCP error: ${rpc.error.message ?? "request failed"}`);
|
|
98
|
+
if (rpc.result === undefined)
|
|
99
|
+
throw new McpError("MCP response has no result");
|
|
100
|
+
return rpc.result;
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
for (;;) {
|
|
104
|
+
const { done, value } = await reader.read();
|
|
105
|
+
if (value) {
|
|
106
|
+
size += value.byteLength;
|
|
107
|
+
if (size > maxBytes)
|
|
108
|
+
throw new McpError("MCP response is too large");
|
|
109
|
+
}
|
|
110
|
+
buf += decoder.decode(value, { stream: !done });
|
|
111
|
+
if (type.includes("text/event-stream")) {
|
|
112
|
+
// normalise CRLF after decoding, including a CRLF split across two chunks
|
|
113
|
+
buf = buf.replace(/\r\n/g, "\n");
|
|
114
|
+
let end = buf.indexOf("\n\n");
|
|
115
|
+
while (end !== -1 || (done && buf.length > 0)) {
|
|
116
|
+
if (end === -1)
|
|
117
|
+
end = buf.length;
|
|
118
|
+
const block = buf.slice(0, end);
|
|
119
|
+
buf = buf.slice(end + 2);
|
|
120
|
+
const data = sseData(block);
|
|
121
|
+
if (data) {
|
|
122
|
+
const rpc = parseJson(data, "MCP event");
|
|
123
|
+
// notifications and unrelated ids are skipped: a server is allowed to
|
|
124
|
+
// interleave them on the stream, and only OUR id ends the read
|
|
125
|
+
if (rpc.id === id)
|
|
126
|
+
return resolve(rpc);
|
|
127
|
+
}
|
|
128
|
+
end = buf.indexOf("\n\n");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else if (done) {
|
|
132
|
+
if (!type.includes("application/json"))
|
|
133
|
+
throw new McpError("MCP endpoint must answer with JSON or text/event-stream (Streamable HTTP) — " +
|
|
134
|
+
`got ${type || "no content-type"}`);
|
|
135
|
+
return resolve(parseJson(buf, "MCP server"));
|
|
136
|
+
}
|
|
137
|
+
if (done)
|
|
138
|
+
throw new McpError("MCP stream ended without a matching response");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
await reader.cancel().catch(() => { });
|
|
143
|
+
reader.releaseLock();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** shared state for the two network transports */
|
|
147
|
+
async function connectHttp(cfg) {
|
|
148
|
+
if (!cfg.url)
|
|
149
|
+
throw new McpError(`MCP server "${cfg.name}" has no url`);
|
|
150
|
+
let parsed;
|
|
151
|
+
try {
|
|
152
|
+
parsed = new URL(cfg.url);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
throw new McpError(`MCP server "${cfg.name}" has an invalid url: ${cfg.url}`);
|
|
156
|
+
}
|
|
157
|
+
if (!["http:", "https:"].includes(parsed.protocol))
|
|
158
|
+
throw new McpError(`MCP server "${cfg.name}" must use http(s), not ${parsed.protocol}`);
|
|
159
|
+
const timeoutMs = cfg.timeoutMs ?? 20_000;
|
|
160
|
+
let sessionId = null;
|
|
161
|
+
let version = null;
|
|
162
|
+
let seq = 0;
|
|
163
|
+
const post = async (method, params, notification = false) => {
|
|
164
|
+
const id = notification ? undefined : ++seq;
|
|
165
|
+
const headers = {
|
|
166
|
+
"content-type": "application/json",
|
|
167
|
+
accept: "application/json, text/event-stream",
|
|
168
|
+
...(cfg.headers ?? {}),
|
|
169
|
+
};
|
|
170
|
+
if (sessionId)
|
|
171
|
+
headers["mcp-session-id"] = sessionId;
|
|
172
|
+
if (version)
|
|
173
|
+
headers["mcp-protocol-version"] = version;
|
|
174
|
+
const ac = new AbortController();
|
|
175
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
176
|
+
try {
|
|
177
|
+
const res = await fetch(parsed, {
|
|
178
|
+
method: "POST",
|
|
179
|
+
headers,
|
|
180
|
+
body: JSON.stringify({
|
|
181
|
+
jsonrpc: "2.0",
|
|
182
|
+
...(notification ? {} : { id }),
|
|
183
|
+
method,
|
|
184
|
+
...(params === undefined ? {} : { params }),
|
|
185
|
+
}),
|
|
186
|
+
// manual, NOT follow: a redirect is almost always an HTML login page, and
|
|
187
|
+
// following it turns a clear auth problem into a confusing JSON parse error
|
|
188
|
+
redirect: "manual",
|
|
189
|
+
signal: ac.signal,
|
|
190
|
+
});
|
|
191
|
+
if (res.status >= 300 && res.status < 400) {
|
|
192
|
+
await res.body?.cancel().catch(() => { });
|
|
193
|
+
throw new McpError(`MCP endpoint redirected (HTTP ${res.status} to ${res.headers.get("location") ?? "?"}) — ` +
|
|
194
|
+
"the url may be wrong, or the session expired");
|
|
195
|
+
}
|
|
196
|
+
if (!res.ok) {
|
|
197
|
+
const body = (await res.text().catch(() => "")).slice(0, 300);
|
|
198
|
+
if (res.status === 405)
|
|
199
|
+
throw new McpError(`MCP endpoint answered 405 — it does not accept POST (Streamable HTTP): ${body || "(no body)"}`);
|
|
200
|
+
throw new McpError(`MCP server returned HTTP ${res.status}: ${body || "(no body)"}`, res.status === 401 || res.status === 403);
|
|
201
|
+
}
|
|
202
|
+
if (notification) {
|
|
203
|
+
await res.body?.cancel().catch(() => { });
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
if (method === "initialize")
|
|
207
|
+
sessionId = res.headers.get("mcp-session-id");
|
|
208
|
+
return readRpcResult(res, id);
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
if (err.name === "AbortError")
|
|
212
|
+
throw new McpError(`MCP request timed out after ${timeoutMs}ms (${cfg.url})`);
|
|
213
|
+
throw err;
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
clearTimeout(timer);
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const init = (await post("initialize", {
|
|
220
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
221
|
+
capabilities: {},
|
|
222
|
+
clientInfo: { name: "teapot", version: "1" },
|
|
223
|
+
}));
|
|
224
|
+
if (!init?.protocolVersion || !KNOWN_VERSIONS.includes(init.protocolVersion))
|
|
225
|
+
throw new McpError(`unsupported MCP protocol version: ${init?.protocolVersion ?? "(none)"}`);
|
|
226
|
+
version = init.protocolVersion;
|
|
227
|
+
await post("notifications/initialized", undefined, true);
|
|
228
|
+
const listTools = async () => {
|
|
229
|
+
const tools = [];
|
|
230
|
+
let cursor;
|
|
231
|
+
const seen = new Set();
|
|
232
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
233
|
+
const res = (await post("tools/list", cursor ? { cursor } : {}));
|
|
234
|
+
if (!Array.isArray(res?.tools))
|
|
235
|
+
throw new McpError(`MCP tools/list did not return a tools array`);
|
|
236
|
+
for (const t of res.tools) {
|
|
237
|
+
// validate rather than trust: a bad definition becomes a bad function spec
|
|
238
|
+
if (typeof t?.name !== "string" || !t.name)
|
|
239
|
+
throw new McpError("MCP tool is missing a name");
|
|
240
|
+
if (typeof t.inputSchema !== "object" || t.inputSchema === null || Array.isArray(t.inputSchema))
|
|
241
|
+
throw new McpError(`MCP tool "${t.name}" has no object inputSchema`);
|
|
242
|
+
tools.push({
|
|
243
|
+
name: t.name,
|
|
244
|
+
description: typeof t.description === "string" ? t.description : "",
|
|
245
|
+
inputSchema: t.inputSchema,
|
|
246
|
+
server: cfg.name,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
if (res.nextCursor === undefined)
|
|
250
|
+
return tools;
|
|
251
|
+
if (typeof res.nextCursor !== "string")
|
|
252
|
+
throw new McpError("MCP tools cursor is not a string");
|
|
253
|
+
if (seen.has(res.nextCursor))
|
|
254
|
+
throw new McpError("MCP tool pagination returned the same cursor twice");
|
|
255
|
+
seen.add(res.nextCursor);
|
|
256
|
+
cursor = res.nextCursor;
|
|
257
|
+
}
|
|
258
|
+
throw new McpError(`MCP tools/list did not finish within ${MAX_PAGES} pages`);
|
|
259
|
+
};
|
|
260
|
+
return {
|
|
261
|
+
tools: listTools,
|
|
262
|
+
async call(name, args) {
|
|
263
|
+
const res = (await post("tools/call", { name, arguments: args ?? {} }));
|
|
264
|
+
// MCP returns a CONTENT ARRAY, not a string. Concatenate the text parts and
|
|
265
|
+
// name the unsupported ones instead of dropping them silently — a json/pdf
|
|
266
|
+
// part vanishing would look like an empty answer.
|
|
267
|
+
const parts = [];
|
|
268
|
+
for (const c of res?.content ?? []) {
|
|
269
|
+
if (c?.type === "text" && typeof c.text === "string")
|
|
270
|
+
parts.push(c.text);
|
|
271
|
+
else if (c?.type)
|
|
272
|
+
parts.push(`[${c.type} content omitted]`);
|
|
273
|
+
}
|
|
274
|
+
return { text: parts.join("\n") || "(no content)", ok: !res?.isError };
|
|
275
|
+
},
|
|
276
|
+
async close() {
|
|
277
|
+
/* HTTP: nothing to tear down — the session dies with the process */
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/** stdio: newline-delimited JSON-RPC over a child's stdin/stdout */
|
|
282
|
+
async function connectStdio(cfg) {
|
|
283
|
+
if (!cfg.command)
|
|
284
|
+
throw new McpError(`MCP server "${cfg.name}" has no command`);
|
|
285
|
+
const { spawn } = await import("node:child_process");
|
|
286
|
+
const child = spawn(cfg.command, cfg.args ?? [], {
|
|
287
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
288
|
+
env: { ...process.env, ...(cfg.env ?? {}) },
|
|
289
|
+
// a plugin's PLUGIN_ROOT/PLUGIN_DATA make its own relative paths work; without
|
|
290
|
+
// passing this the server starts in the harness's cwd and cannot find its files
|
|
291
|
+
...(cfg.cwd ? { cwd: cfg.cwd } : {}),
|
|
292
|
+
});
|
|
293
|
+
const timeoutMs = cfg.timeoutMs ?? 20_000;
|
|
294
|
+
let seq = 0;
|
|
295
|
+
let buf = "";
|
|
296
|
+
let stderr = "";
|
|
297
|
+
const pending = new Map();
|
|
298
|
+
const fail = (err) => {
|
|
299
|
+
for (const [, p] of pending)
|
|
300
|
+
p.reject(err);
|
|
301
|
+
pending.clear();
|
|
302
|
+
};
|
|
303
|
+
child.on("error", (e) => fail(new McpError(`MCP server "${cfg.name}" failed to start: ${e.message}`)));
|
|
304
|
+
child.on("exit", (code) => fail(new McpError(`MCP server "${cfg.name}" exited (${code ?? "signal"})${stderr ? `: ${stderr.slice(-300)}` : ""}`)));
|
|
305
|
+
child.stderr?.on("data", (d) => {
|
|
306
|
+
stderr = (stderr + String(d)).slice(-4000);
|
|
307
|
+
});
|
|
308
|
+
child.stdout?.on("data", (d) => {
|
|
309
|
+
buf += String(d);
|
|
310
|
+
let nl = buf.indexOf("\n");
|
|
311
|
+
while (nl !== -1) {
|
|
312
|
+
const line = buf.slice(0, nl).trim();
|
|
313
|
+
buf = buf.slice(nl + 1);
|
|
314
|
+
nl = buf.indexOf("\n");
|
|
315
|
+
if (!line)
|
|
316
|
+
continue;
|
|
317
|
+
let msg;
|
|
318
|
+
try {
|
|
319
|
+
msg = JSON.parse(line);
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
continue; // a server that logs to stdout gets skipped, not fatal
|
|
323
|
+
}
|
|
324
|
+
if (typeof msg.id !== "number")
|
|
325
|
+
continue; // notification
|
|
326
|
+
const p = pending.get(msg.id);
|
|
327
|
+
if (!p)
|
|
328
|
+
continue;
|
|
329
|
+
pending.delete(msg.id);
|
|
330
|
+
if (msg.error)
|
|
331
|
+
p.reject(new McpError(`MCP error: ${msg.error.message ?? "request failed"}`));
|
|
332
|
+
else
|
|
333
|
+
p.resolve(msg.result);
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
const request = (method, params) => {
|
|
337
|
+
const id = ++seq;
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
const timer = setTimeout(() => {
|
|
340
|
+
pending.delete(id);
|
|
341
|
+
reject(new McpError(`MCP request timed out after ${timeoutMs}ms (${method})`));
|
|
342
|
+
}, timeoutMs);
|
|
343
|
+
pending.set(id, {
|
|
344
|
+
resolve: (v) => {
|
|
345
|
+
clearTimeout(timer);
|
|
346
|
+
resolve(v);
|
|
347
|
+
},
|
|
348
|
+
reject: (e) => {
|
|
349
|
+
clearTimeout(timer);
|
|
350
|
+
reject(e);
|
|
351
|
+
},
|
|
352
|
+
});
|
|
353
|
+
child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }) + "\n");
|
|
354
|
+
});
|
|
355
|
+
};
|
|
356
|
+
const notify = (method, params) => child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method, ...(params === undefined ? {} : { params }) }) + "\n");
|
|
357
|
+
const init = (await request("initialize", {
|
|
358
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
359
|
+
capabilities: {},
|
|
360
|
+
clientInfo: { name: "teapot", version: "1" },
|
|
361
|
+
}));
|
|
362
|
+
if (!init?.protocolVersion || !KNOWN_VERSIONS.includes(init.protocolVersion))
|
|
363
|
+
throw new McpError(`unsupported MCP protocol version: ${init?.protocolVersion ?? "(none)"}`);
|
|
364
|
+
notify("notifications/initialized");
|
|
365
|
+
return {
|
|
366
|
+
async tools() {
|
|
367
|
+
const tools = [];
|
|
368
|
+
let cursor;
|
|
369
|
+
const seen = new Set();
|
|
370
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
371
|
+
const res = (await request("tools/list", cursor ? { cursor } : {}));
|
|
372
|
+
if (!Array.isArray(res?.tools))
|
|
373
|
+
throw new McpError("MCP tools/list did not return a tools array");
|
|
374
|
+
for (const t of res.tools) {
|
|
375
|
+
if (typeof t?.name !== "string" || !t.name)
|
|
376
|
+
throw new McpError("MCP tool is missing a name");
|
|
377
|
+
if (typeof t.inputSchema !== "object" || t.inputSchema === null || Array.isArray(t.inputSchema))
|
|
378
|
+
throw new McpError(`MCP tool "${t.name}" has no object inputSchema`);
|
|
379
|
+
tools.push({
|
|
380
|
+
name: t.name,
|
|
381
|
+
description: typeof t.description === "string" ? t.description : "",
|
|
382
|
+
inputSchema: t.inputSchema,
|
|
383
|
+
server: cfg.name,
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
if (res.nextCursor === undefined)
|
|
387
|
+
return tools;
|
|
388
|
+
if (typeof res.nextCursor !== "string")
|
|
389
|
+
throw new McpError("MCP tools cursor is not a string");
|
|
390
|
+
if (seen.has(res.nextCursor))
|
|
391
|
+
throw new McpError("MCP tool pagination returned the same cursor twice");
|
|
392
|
+
seen.add(res.nextCursor);
|
|
393
|
+
cursor = res.nextCursor;
|
|
394
|
+
}
|
|
395
|
+
throw new McpError(`MCP tools/list did not finish within ${MAX_PAGES} pages`);
|
|
396
|
+
},
|
|
397
|
+
async call(name, args) {
|
|
398
|
+
const res = (await request("tools/call", { name, arguments: args ?? {} }));
|
|
399
|
+
const parts = [];
|
|
400
|
+
for (const c of res?.content ?? []) {
|
|
401
|
+
if (c?.type === "text" && typeof c.text === "string")
|
|
402
|
+
parts.push(c.text);
|
|
403
|
+
else if (c?.type)
|
|
404
|
+
parts.push(`[${c.type} content omitted]`);
|
|
405
|
+
}
|
|
406
|
+
return { text: parts.join("\n") || "(no content)", ok: !res?.isError };
|
|
407
|
+
},
|
|
408
|
+
async close() {
|
|
409
|
+
child.kill();
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/** connect to one configured server */
|
|
414
|
+
export async function connectMcp(cfg) {
|
|
415
|
+
const transport = cfg.transport ?? (cfg.command && !cfg.url ? "stdio" : "http");
|
|
416
|
+
if (transport === "stdio")
|
|
417
|
+
return connectStdio(cfg);
|
|
418
|
+
if (transport === "sse")
|
|
419
|
+
return connectLegacySse(cfg);
|
|
420
|
+
return connectHttp(cfg);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Legacy HTTP+SSE (2024-11-05): a GET holds an event stream open, the server sends an
|
|
424
|
+
* `endpoint` event naming a POST url, and replies to POSTs arrive ON the GET stream.
|
|
425
|
+
*
|
|
426
|
+
* Kept separate from `connectHttp` because the request/reply plumbing is genuinely
|
|
427
|
+
* different — there is no response body to read a result from — and folding them
|
|
428
|
+
* together produced a function that could not be followed.
|
|
429
|
+
*/
|
|
430
|
+
async function connectLegacySse(cfg) {
|
|
431
|
+
if (!cfg.url)
|
|
432
|
+
throw new McpError(`MCP server "${cfg.name}" has no url`);
|
|
433
|
+
const timeoutMs = cfg.timeoutMs ?? 20_000;
|
|
434
|
+
const ac = new AbortController();
|
|
435
|
+
const res = await fetch(cfg.url, {
|
|
436
|
+
headers: { accept: "text/event-stream", ...(cfg.headers ?? {}) },
|
|
437
|
+
signal: ac.signal,
|
|
438
|
+
});
|
|
439
|
+
if (!res.ok) {
|
|
440
|
+
await res.body?.cancel().catch(() => { });
|
|
441
|
+
throw new McpError(`MCP (legacy SSE) endpoint returned HTTP ${res.status}`, res.status === 401 || res.status === 403);
|
|
442
|
+
}
|
|
443
|
+
const reader = res.body?.getReader();
|
|
444
|
+
if (!reader)
|
|
445
|
+
throw new McpError("MCP (legacy SSE) endpoint returned an empty stream");
|
|
446
|
+
const decoder = new TextDecoder();
|
|
447
|
+
let endpoint = null;
|
|
448
|
+
let buf = "";
|
|
449
|
+
let seq = 0;
|
|
450
|
+
const pending = new Map();
|
|
451
|
+
const ready = new Promise((resolve, reject) => {
|
|
452
|
+
const timer = setTimeout(() => reject(new McpError(`MCP (legacy SSE) did not send an endpoint within ${timeoutMs}ms`)), timeoutMs);
|
|
453
|
+
(async () => {
|
|
454
|
+
try {
|
|
455
|
+
for (;;) {
|
|
456
|
+
const { done, value } = await reader.read();
|
|
457
|
+
if (done)
|
|
458
|
+
break;
|
|
459
|
+
buf += decoder.decode(value, { stream: true });
|
|
460
|
+
buf = buf.replace(/\r\n/g, "\n");
|
|
461
|
+
let end = buf.indexOf("\n\n");
|
|
462
|
+
while (end !== -1) {
|
|
463
|
+
const block = buf.slice(0, end);
|
|
464
|
+
buf = buf.slice(end + 2);
|
|
465
|
+
end = buf.indexOf("\n\n");
|
|
466
|
+
const ev = (/^event:\s*(.+)$/m.exec(block)?.[1] ?? "message").trim();
|
|
467
|
+
const data = sseData(block);
|
|
468
|
+
if (ev === "endpoint" && data) {
|
|
469
|
+
endpoint = new URL(data, cfg.url).toString();
|
|
470
|
+
clearTimeout(timer);
|
|
471
|
+
resolve();
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (!data)
|
|
475
|
+
continue;
|
|
476
|
+
let msg;
|
|
477
|
+
try {
|
|
478
|
+
msg = JSON.parse(data);
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (typeof msg.id !== "number")
|
|
484
|
+
continue;
|
|
485
|
+
const p = pending.get(msg.id);
|
|
486
|
+
if (!p)
|
|
487
|
+
continue;
|
|
488
|
+
pending.delete(msg.id);
|
|
489
|
+
if (msg.error)
|
|
490
|
+
p.reject(new McpError(`MCP error: ${msg.error.message ?? "request failed"}`));
|
|
491
|
+
else
|
|
492
|
+
p.resolve(msg.result);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
clearTimeout(timer);
|
|
496
|
+
reject(new McpError("MCP (legacy SSE) stream closed"));
|
|
497
|
+
}
|
|
498
|
+
catch (e) {
|
|
499
|
+
clearTimeout(timer);
|
|
500
|
+
reject(e);
|
|
501
|
+
}
|
|
502
|
+
})();
|
|
503
|
+
});
|
|
504
|
+
await ready;
|
|
505
|
+
if (!endpoint)
|
|
506
|
+
throw new McpError("MCP (legacy SSE) stream exposed no endpoint");
|
|
507
|
+
const postUrl = endpoint;
|
|
508
|
+
const send = async (method, params, notification = false) => {
|
|
509
|
+
const id = ++seq;
|
|
510
|
+
const body = {
|
|
511
|
+
jsonrpc: "2.0",
|
|
512
|
+
...(notification ? {} : { id }),
|
|
513
|
+
method,
|
|
514
|
+
...(params === undefined ? {} : { params }),
|
|
515
|
+
};
|
|
516
|
+
const r = await fetch(postUrl, {
|
|
517
|
+
method: "POST",
|
|
518
|
+
headers: { "content-type": "application/json", ...(cfg.headers ?? {}) },
|
|
519
|
+
body: JSON.stringify(body),
|
|
520
|
+
signal: ac.signal,
|
|
521
|
+
});
|
|
522
|
+
await r.body?.cancel().catch(() => { });
|
|
523
|
+
if (!r.ok)
|
|
524
|
+
throw new McpError(`MCP (legacy SSE) POST returned HTTP ${r.status}`, r.status === 401 || r.status === 403);
|
|
525
|
+
if (notification)
|
|
526
|
+
return undefined;
|
|
527
|
+
// the reply arrives on the GET stream, so wait for it there
|
|
528
|
+
return new Promise((resolve, reject) => {
|
|
529
|
+
const timer = setTimeout(() => {
|
|
530
|
+
pending.delete(id);
|
|
531
|
+
reject(new McpError(`MCP request timed out after ${timeoutMs}ms (${method})`));
|
|
532
|
+
}, timeoutMs);
|
|
533
|
+
pending.set(id, {
|
|
534
|
+
resolve: (v) => {
|
|
535
|
+
clearTimeout(timer);
|
|
536
|
+
resolve(v);
|
|
537
|
+
},
|
|
538
|
+
reject: (e) => {
|
|
539
|
+
clearTimeout(timer);
|
|
540
|
+
reject(e);
|
|
541
|
+
},
|
|
542
|
+
});
|
|
543
|
+
});
|
|
544
|
+
};
|
|
545
|
+
const init = (await send("initialize", {
|
|
546
|
+
protocolVersion: "2024-11-05",
|
|
547
|
+
capabilities: {},
|
|
548
|
+
clientInfo: { name: "teapot", version: "1" },
|
|
549
|
+
}));
|
|
550
|
+
if (!init?.protocolVersion || !KNOWN_VERSIONS.includes(init.protocolVersion))
|
|
551
|
+
throw new McpError(`unsupported MCP protocol version: ${init?.protocolVersion ?? "(none)"}`);
|
|
552
|
+
await send("notifications/initialized", undefined, true);
|
|
553
|
+
return {
|
|
554
|
+
async tools() {
|
|
555
|
+
const out = [];
|
|
556
|
+
let cursor;
|
|
557
|
+
const seen = new Set();
|
|
558
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
559
|
+
const r = (await send("tools/list", cursor ? { cursor } : {}));
|
|
560
|
+
if (!Array.isArray(r?.tools))
|
|
561
|
+
throw new McpError("MCP tools/list did not return a tools array");
|
|
562
|
+
for (const t of r.tools) {
|
|
563
|
+
if (typeof t?.name !== "string" || !t.name)
|
|
564
|
+
throw new McpError("MCP tool is missing a name");
|
|
565
|
+
if (typeof t.inputSchema !== "object" || t.inputSchema === null || Array.isArray(t.inputSchema))
|
|
566
|
+
throw new McpError(`MCP tool "${t.name}" has no object inputSchema`);
|
|
567
|
+
out.push({
|
|
568
|
+
name: t.name,
|
|
569
|
+
description: typeof t.description === "string" ? t.description : "",
|
|
570
|
+
inputSchema: t.inputSchema,
|
|
571
|
+
server: cfg.name,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
if (r.nextCursor === undefined)
|
|
575
|
+
return out;
|
|
576
|
+
if (typeof r.nextCursor !== "string")
|
|
577
|
+
throw new McpError("MCP tools cursor is not a string");
|
|
578
|
+
if (seen.has(r.nextCursor))
|
|
579
|
+
throw new McpError("MCP tool pagination returned the same cursor twice");
|
|
580
|
+
seen.add(r.nextCursor);
|
|
581
|
+
cursor = r.nextCursor;
|
|
582
|
+
}
|
|
583
|
+
throw new McpError(`MCP tools/list did not finish within ${MAX_PAGES} pages`);
|
|
584
|
+
},
|
|
585
|
+
async call(name, args) {
|
|
586
|
+
const r = (await send("tools/call", { name, arguments: args ?? {} }));
|
|
587
|
+
const parts = [];
|
|
588
|
+
for (const c of r?.content ?? []) {
|
|
589
|
+
if (c?.type === "text" && typeof c.text === "string")
|
|
590
|
+
parts.push(c.text);
|
|
591
|
+
else if (c?.type)
|
|
592
|
+
parts.push(`[${c.type} content omitted]`);
|
|
593
|
+
}
|
|
594
|
+
return { text: parts.join("\n") || "(no content)", ok: !r?.isError };
|
|
595
|
+
},
|
|
596
|
+
async close() {
|
|
597
|
+
ac.abort();
|
|
598
|
+
await reader.cancel().catch(() => { });
|
|
599
|
+
},
|
|
600
|
+
};
|
|
601
|
+
}
|