teapot-coding-agent 0.29.32 → 0.29.34
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 +47 -0
- package/dist/agent/mcp-oauth-manager.js +197 -255
- package/dist/agent/mcp-registry.js +169 -65
- package/dist/agent/mcp.js +131 -591
- package/dist/master.js +34 -3
- package/dist/server/api.js +41 -61
- package/package.json +5 -3
- package/public/assets/index-DWK26mKp.css +1 -0
- package/public/assets/{index-CUHACAGL.js → index-rx1ZjP50.js} +8 -8
- package/public/assets/index-rx1ZjP50.js.map +1 -0
- package/public/assets/{shiki-B8vfRZ8s.js → shiki-8MhNGmet.js} +2 -2
- package/public/assets/{shiki-B8vfRZ8s.js.map → shiki-8MhNGmet.js.map} +1 -1
- package/public/index.html +2 -2
- package/dist/agent/mcp-oauth.js +0 -429
- package/public/assets/index-CCnsAOJa.css +0 -1
- package/public/assets/index-CUHACAGL.js.map +0 -1
package/dist/agent/mcp.js
CHANGED
|
@@ -1,621 +1,161 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* MCP client (#67)
|
|
2
|
+
* MCP client (#67), on `@modelcontextprotocol/client` v2.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* consumes is how an MCP client becomes a maintenance sink.
|
|
4
|
+
* The hand-written protocol layer is GONE. It had been carrying Streamable HTTP, legacy
|
|
5
|
+
* HTTP+SSE and stdio, each with its own JSON-RPC framing, session-id handling and SSE
|
|
6
|
+
* parsing — which is exactly the surface the official client now owns, and protocol
|
|
7
|
+
* details (new protocol versions, new transports, task-based calls) move under it.
|
|
9
8
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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.
|
|
9
|
+
* What teapot keeps is the part that is NOT protocol: which servers are configured, how
|
|
10
|
+
* one connection is shared across agents, tool-name namespacing, and the OAuth STORE
|
|
11
|
+
* (where the grant lives). The SDK supplies the discovery and the flow.
|
|
18
12
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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.
|
|
13
|
+
* Discovery deliberately uses the SDK's own `buildDiscoveryUrls` order rather than a
|
|
14
|
+
* hand-rolled one. MEASURED against the live servers before the rewrite:
|
|
33
15
|
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
16
|
+
* GitHub (issuer https://github.com/login/oauth) serves ONLY
|
|
17
|
+
* https://github.com/.well-known/oauth-authorization-server/login/oauth 200
|
|
18
|
+
* https://github.com/login/oauth/.well-known/oauth-authorization-server 404
|
|
19
|
+
* Notion (issuer https://mcp.notion.com, no path) serves the root form.
|
|
20
|
+
*
|
|
21
|
+
* and the SDK tries exactly: RFC 8414 pre-path oauth → pre-path OIDC → post-path OIDC.
|
|
22
|
+
* It does NOT try the post-path `oauth-authorization-server` shape, which is correct —
|
|
23
|
+
* no MCP server is known to publish it, and guessing more shapes risks accepting a
|
|
24
|
+
* document from a different issuer.
|
|
40
25
|
*/
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
26
|
+
import { Client } from "@modelcontextprotocol/client";
|
|
27
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
28
|
+
import { SSEClientTransport } from "@modelcontextprotocol/client";
|
|
29
|
+
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
30
|
+
/** pull the text out of an MCP tool result's content array */
|
|
31
|
+
function resultText(result) {
|
|
32
|
+
const parts = [];
|
|
33
|
+
for (const c of result?.content ?? []) {
|
|
34
|
+
if (c?.type === "text" && typeof c.text === "string")
|
|
35
|
+
parts.push(c.text);
|
|
36
|
+
// name the parts we cannot render rather than dropping them silently: a json or
|
|
37
|
+
// image part vanishing would look like an empty answer
|
|
38
|
+
else if (c?.type)
|
|
39
|
+
parts.push(`[${c.type} content omitted]`);
|
|
51
40
|
}
|
|
41
|
+
return { text: parts.join("\n") || "(no content)", ok: result?.isError !== true };
|
|
52
42
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
43
|
+
/** normalise what a server reports into teapot's tool shape */
|
|
44
|
+
function toTools(list, server) {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const t of list?.tools ?? []) {
|
|
47
|
+
const name = typeof t.name === "string" ? t.name : "";
|
|
48
|
+
if (!name)
|
|
49
|
+
continue; // a nameless tool is unusable either way
|
|
50
|
+
const schema = t.inputSchema;
|
|
51
|
+
out.push({
|
|
52
|
+
name,
|
|
53
|
+
description: typeof t.description === "string" ? t.description : "",
|
|
54
|
+
// The SDK VALIDATES that every tool carries an object `inputSchema`, so this
|
|
55
|
+
// fallback is only a type guard — a server that omits it fails at `tools()` before
|
|
56
|
+
// reaching here. Kept so a future protocol version that makes it optional does not
|
|
57
|
+
// hand the model an undefined schema.
|
|
58
|
+
inputSchema: schema && typeof schema === "object" && !Array.isArray(schema)
|
|
59
|
+
? schema
|
|
60
|
+
: { type: "object", properties: {} },
|
|
61
|
+
server,
|
|
62
|
+
});
|
|
68
63
|
}
|
|
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");
|
|
64
|
+
return out;
|
|
77
65
|
}
|
|
78
66
|
/**
|
|
79
|
-
*
|
|
67
|
+
* Connect to one configured server.
|
|
80
68
|
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
* awkward to provoke through a live one.
|
|
69
|
+
* `auth` is optional: without it the transports send only the static headers, which is
|
|
70
|
+
* the common case (a local server, or a static API key).
|
|
84
71
|
*/
|
|
85
|
-
export async function
|
|
86
|
-
const
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
}
|
|
72
|
+
export async function connectMcp(cfg, auth) {
|
|
73
|
+
const transport = cfg.transport ?? (cfg.command && !cfg.url ? "stdio" : "http");
|
|
74
|
+
const client = new Client({ name: "teapot", version: "1" });
|
|
75
|
+
let session;
|
|
76
|
+
if (transport === "stdio") {
|
|
77
|
+
if (!cfg.command)
|
|
78
|
+
throw new Error(`MCP server "${cfg.name}" has no command`);
|
|
79
|
+
session = new StdioClientTransport({
|
|
80
|
+
command: cfg.command,
|
|
81
|
+
args: cfg.args ?? [],
|
|
82
|
+
env: { ...process.env, ...(cfg.env ?? {}) },
|
|
83
|
+
...(cfg.cwd ? { cwd: cfg.cwd } : {}),
|
|
84
|
+
// a server that logs to stdout can corrupt the frame stream; the SDK's stderr
|
|
85
|
+
// option ("inherit" by default) is the place to say otherwise
|
|
86
|
+
stderr: "inherit",
|
|
87
|
+
});
|
|
140
88
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
89
|
+
else if (transport === "sse") {
|
|
90
|
+
if (!cfg.url)
|
|
91
|
+
throw new Error(`MCP server "${cfg.name}" has no url`);
|
|
92
|
+
const url = new URL(cfg.url);
|
|
93
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
94
|
+
throw new Error(`MCP server "${cfg.name}" must use http(s), not ${url.protocol}`);
|
|
95
|
+
session = new SSEClientTransport(url, {
|
|
96
|
+
// `manual`, NOT follow: an MCP endpoint that redirects is nearly always an HTML
|
|
97
|
+
// login page, and following it replaces a clear auth problem with a parse error
|
|
98
|
+
redirectPolicy: "same-origin",
|
|
99
|
+
...(cfg.headers ? { requestInit: { headers: cfg.headers } } : {}),
|
|
100
|
+
...(auth ? { authProvider: auth.provider } : {}),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
if (!cfg.url)
|
|
105
|
+
throw new Error(`MCP server "${cfg.name}" has no url`);
|
|
106
|
+
const url = new URL(cfg.url);
|
|
107
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
108
|
+
throw new Error(`MCP server "${cfg.name}" must use http(s), not ${url.protocol}`);
|
|
109
|
+
session = new StreamableHTTPClientTransport(url, {
|
|
110
|
+
redirectPolicy: "same-origin",
|
|
111
|
+
...(cfg.headers ? { requestInit: { headers: cfg.headers } } : {}),
|
|
112
|
+
...(auth ? { authProvider: auth.provider } : {}),
|
|
113
|
+
});
|
|
144
114
|
}
|
|
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
115
|
try {
|
|
152
|
-
|
|
116
|
+
await client.connect(session);
|
|
153
117
|
}
|
|
154
|
-
catch {
|
|
155
|
-
|
|
118
|
+
catch (err) {
|
|
119
|
+
// let the caller distinguish "needs a grant" from "broken", which is what the
|
|
120
|
+
// settings panel shows differently
|
|
121
|
+
await client.close().catch(() => { });
|
|
122
|
+
throw err;
|
|
156
123
|
}
|
|
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
|
-
// OAuth wins over a static authorization header: it is the more specific grant, and
|
|
171
|
-
// resolving it per request is what lets a refresh take effect mid-session.
|
|
172
|
-
if (cfg.oauthAuthorization) {
|
|
173
|
-
const auth = await cfg.oauthAuthorization().catch(() => null);
|
|
174
|
-
if (auth) {
|
|
175
|
-
// Remove any spelling of the header the CONFIG supplied first. Keys are
|
|
176
|
-
// case-insensitive on the wire but not in a JS object, so leaving
|
|
177
|
-
// `Authorization` beside `authorization` would send BOTH and let the server
|
|
178
|
-
// pick — the exact ambiguity this precedence rule exists to remove.
|
|
179
|
-
for (const k of Object.keys(headers)) {
|
|
180
|
-
if (k.toLowerCase() === "authorization")
|
|
181
|
-
delete headers[k];
|
|
182
|
-
}
|
|
183
|
-
headers.authorization = auth;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
if (sessionId)
|
|
187
|
-
headers["mcp-session-id"] = sessionId;
|
|
188
|
-
if (version)
|
|
189
|
-
headers["mcp-protocol-version"] = version;
|
|
190
|
-
const ac = new AbortController();
|
|
191
|
-
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
192
|
-
try {
|
|
193
|
-
const res = await fetch(parsed, {
|
|
194
|
-
method: "POST",
|
|
195
|
-
headers,
|
|
196
|
-
body: JSON.stringify({
|
|
197
|
-
jsonrpc: "2.0",
|
|
198
|
-
...(notification ? {} : { id }),
|
|
199
|
-
method,
|
|
200
|
-
...(params === undefined ? {} : { params }),
|
|
201
|
-
}),
|
|
202
|
-
// manual, NOT follow: a redirect is almost always an HTML login page, and
|
|
203
|
-
// following it turns a clear auth problem into a confusing JSON parse error
|
|
204
|
-
redirect: "manual",
|
|
205
|
-
signal: ac.signal,
|
|
206
|
-
});
|
|
207
|
-
if (res.status >= 300 && res.status < 400) {
|
|
208
|
-
await res.body?.cancel().catch(() => { });
|
|
209
|
-
throw new McpError(`MCP endpoint redirected (HTTP ${res.status} to ${res.headers.get("location") ?? "?"}) — ` +
|
|
210
|
-
"the url may be wrong, or the session expired");
|
|
211
|
-
}
|
|
212
|
-
if (!res.ok) {
|
|
213
|
-
const body = (await res.text().catch(() => "")).slice(0, 300);
|
|
214
|
-
if (res.status === 405)
|
|
215
|
-
throw new McpError(`MCP endpoint answered 405 — it does not accept POST (Streamable HTTP): ${body || "(no body)"}`);
|
|
216
|
-
// Tell the caller so it can drop a cached token: a 401 here means the access
|
|
217
|
-
// token was rejected, and retrying with the same one would loop.
|
|
218
|
-
if (res.status === 401 || res.status === 403)
|
|
219
|
-
cfg.onUnauthorized?.();
|
|
220
|
-
throw new McpError(`MCP server returned HTTP ${res.status}: ${body || "(no body)"}`, res.status === 401 || res.status === 403);
|
|
221
|
-
}
|
|
222
|
-
if (notification) {
|
|
223
|
-
await res.body?.cancel().catch(() => { });
|
|
224
|
-
return undefined;
|
|
225
|
-
}
|
|
226
|
-
if (method === "initialize")
|
|
227
|
-
sessionId = res.headers.get("mcp-session-id");
|
|
228
|
-
return readRpcResult(res, id);
|
|
229
|
-
}
|
|
230
|
-
catch (err) {
|
|
231
|
-
if (err.name === "AbortError")
|
|
232
|
-
throw new McpError(`MCP request timed out after ${timeoutMs}ms (${cfg.url})`);
|
|
233
|
-
throw err;
|
|
234
|
-
}
|
|
235
|
-
finally {
|
|
236
|
-
clearTimeout(timer);
|
|
237
|
-
}
|
|
238
|
-
};
|
|
239
|
-
const init = (await post("initialize", {
|
|
240
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
241
|
-
capabilities: {},
|
|
242
|
-
clientInfo: { name: "teapot", version: "1" },
|
|
243
|
-
}));
|
|
244
|
-
if (!init?.protocolVersion || !KNOWN_VERSIONS.includes(init.protocolVersion))
|
|
245
|
-
throw new McpError(`unsupported MCP protocol version: ${init?.protocolVersion ?? "(none)"}`);
|
|
246
|
-
version = init.protocolVersion;
|
|
247
|
-
await post("notifications/initialized", undefined, true);
|
|
248
|
-
const listTools = async () => {
|
|
249
|
-
const tools = [];
|
|
250
|
-
let cursor;
|
|
251
|
-
const seen = new Set();
|
|
252
|
-
for (let page = 0; page < MAX_PAGES; page++) {
|
|
253
|
-
const res = (await post("tools/list", cursor ? { cursor } : {}));
|
|
254
|
-
if (!Array.isArray(res?.tools))
|
|
255
|
-
throw new McpError(`MCP tools/list did not return a tools array`);
|
|
256
|
-
for (const t of res.tools) {
|
|
257
|
-
// validate rather than trust: a bad definition becomes a bad function spec
|
|
258
|
-
if (typeof t?.name !== "string" || !t.name)
|
|
259
|
-
throw new McpError("MCP tool is missing a name");
|
|
260
|
-
if (typeof t.inputSchema !== "object" || t.inputSchema === null || Array.isArray(t.inputSchema))
|
|
261
|
-
throw new McpError(`MCP tool "${t.name}" has no object inputSchema`);
|
|
262
|
-
tools.push({
|
|
263
|
-
name: t.name,
|
|
264
|
-
description: typeof t.description === "string" ? t.description : "",
|
|
265
|
-
inputSchema: t.inputSchema,
|
|
266
|
-
server: cfg.name,
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
if (res.nextCursor === undefined)
|
|
270
|
-
return tools;
|
|
271
|
-
if (typeof res.nextCursor !== "string")
|
|
272
|
-
throw new McpError("MCP tools cursor is not a string");
|
|
273
|
-
if (seen.has(res.nextCursor))
|
|
274
|
-
throw new McpError("MCP tool pagination returned the same cursor twice");
|
|
275
|
-
seen.add(res.nextCursor);
|
|
276
|
-
cursor = res.nextCursor;
|
|
277
|
-
}
|
|
278
|
-
throw new McpError(`MCP tools/list did not finish within ${MAX_PAGES} pages`);
|
|
279
|
-
};
|
|
280
|
-
return {
|
|
281
|
-
tools: listTools,
|
|
282
|
-
async call(name, args) {
|
|
283
|
-
const res = (await post("tools/call", { name, arguments: args ?? {} }));
|
|
284
|
-
// MCP returns a CONTENT ARRAY, not a string. Concatenate the text parts and
|
|
285
|
-
// name the unsupported ones instead of dropping them silently — a json/pdf
|
|
286
|
-
// part vanishing would look like an empty answer.
|
|
287
|
-
const parts = [];
|
|
288
|
-
for (const c of res?.content ?? []) {
|
|
289
|
-
if (c?.type === "text" && typeof c.text === "string")
|
|
290
|
-
parts.push(c.text);
|
|
291
|
-
else if (c?.type)
|
|
292
|
-
parts.push(`[${c.type} content omitted]`);
|
|
293
|
-
}
|
|
294
|
-
return { text: parts.join("\n") || "(no content)", ok: !res?.isError };
|
|
295
|
-
},
|
|
296
|
-
async close() {
|
|
297
|
-
/* HTTP: nothing to tear down — the session dies with the process */
|
|
298
|
-
},
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
/** stdio: newline-delimited JSON-RPC over a child's stdin/stdout */
|
|
302
|
-
async function connectStdio(cfg) {
|
|
303
|
-
if (!cfg.command)
|
|
304
|
-
throw new McpError(`MCP server "${cfg.name}" has no command`);
|
|
305
|
-
const { spawn } = await import("node:child_process");
|
|
306
|
-
const child = spawn(cfg.command, cfg.args ?? [], {
|
|
307
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
308
|
-
env: { ...process.env, ...(cfg.env ?? {}) },
|
|
309
|
-
// a plugin's PLUGIN_ROOT/PLUGIN_DATA make its own relative paths work; without
|
|
310
|
-
// passing this the server starts in the harness's cwd and cannot find its files
|
|
311
|
-
...(cfg.cwd ? { cwd: cfg.cwd } : {}),
|
|
312
|
-
});
|
|
313
|
-
const timeoutMs = cfg.timeoutMs ?? 20_000;
|
|
314
|
-
let seq = 0;
|
|
315
|
-
let buf = "";
|
|
316
|
-
let stderr = "";
|
|
317
|
-
const pending = new Map();
|
|
318
|
-
const fail = (err) => {
|
|
319
|
-
for (const [, p] of pending)
|
|
320
|
-
p.reject(err);
|
|
321
|
-
pending.clear();
|
|
322
|
-
};
|
|
323
|
-
child.on("error", (e) => fail(new McpError(`MCP server "${cfg.name}" failed to start: ${e.message}`)));
|
|
324
|
-
child.on("exit", (code) => fail(new McpError(`MCP server "${cfg.name}" exited (${code ?? "signal"})${stderr ? `: ${stderr.slice(-300)}` : ""}`)));
|
|
325
|
-
child.stderr?.on("data", (d) => {
|
|
326
|
-
stderr = (stderr + String(d)).slice(-4000);
|
|
327
|
-
});
|
|
328
|
-
child.stdout?.on("data", (d) => {
|
|
329
|
-
buf += String(d);
|
|
330
|
-
let nl = buf.indexOf("\n");
|
|
331
|
-
while (nl !== -1) {
|
|
332
|
-
const line = buf.slice(0, nl).trim();
|
|
333
|
-
buf = buf.slice(nl + 1);
|
|
334
|
-
nl = buf.indexOf("\n");
|
|
335
|
-
if (!line)
|
|
336
|
-
continue;
|
|
337
|
-
let msg;
|
|
338
|
-
try {
|
|
339
|
-
msg = JSON.parse(line);
|
|
340
|
-
}
|
|
341
|
-
catch {
|
|
342
|
-
continue; // a server that logs to stdout gets skipped, not fatal
|
|
343
|
-
}
|
|
344
|
-
if (typeof msg.id !== "number")
|
|
345
|
-
continue; // notification
|
|
346
|
-
const p = pending.get(msg.id);
|
|
347
|
-
if (!p)
|
|
348
|
-
continue;
|
|
349
|
-
pending.delete(msg.id);
|
|
350
|
-
if (msg.error)
|
|
351
|
-
p.reject(new McpError(`MCP error: ${msg.error.message ?? "request failed"}`));
|
|
352
|
-
else
|
|
353
|
-
p.resolve(msg.result);
|
|
354
|
-
}
|
|
355
|
-
});
|
|
356
|
-
const request = (method, params) => {
|
|
357
|
-
const id = ++seq;
|
|
358
|
-
return new Promise((resolve, reject) => {
|
|
359
|
-
const timer = setTimeout(() => {
|
|
360
|
-
pending.delete(id);
|
|
361
|
-
reject(new McpError(`MCP request timed out after ${timeoutMs}ms (${method})`));
|
|
362
|
-
}, timeoutMs);
|
|
363
|
-
pending.set(id, {
|
|
364
|
-
resolve: (v) => {
|
|
365
|
-
clearTimeout(timer);
|
|
366
|
-
resolve(v);
|
|
367
|
-
},
|
|
368
|
-
reject: (e) => {
|
|
369
|
-
clearTimeout(timer);
|
|
370
|
-
reject(e);
|
|
371
|
-
},
|
|
372
|
-
});
|
|
373
|
-
child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }) + "\n");
|
|
374
|
-
});
|
|
375
|
-
};
|
|
376
|
-
const notify = (method, params) => child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method, ...(params === undefined ? {} : { params }) }) + "\n");
|
|
377
|
-
const init = (await request("initialize", {
|
|
378
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
379
|
-
capabilities: {},
|
|
380
|
-
clientInfo: { name: "teapot", version: "1" },
|
|
381
|
-
}));
|
|
382
|
-
if (!init?.protocolVersion || !KNOWN_VERSIONS.includes(init.protocolVersion))
|
|
383
|
-
throw new McpError(`unsupported MCP protocol version: ${init?.protocolVersion ?? "(none)"}`);
|
|
384
|
-
notify("notifications/initialized");
|
|
385
124
|
return {
|
|
386
125
|
async tools() {
|
|
387
|
-
|
|
126
|
+
// one page is the norm; follow the cursor so a server that paginates is not
|
|
127
|
+
// silently truncated
|
|
128
|
+
const all = [];
|
|
388
129
|
let cursor;
|
|
389
130
|
const seen = new Set();
|
|
390
|
-
for (let page = 0; page <
|
|
391
|
-
const res =
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
inputSchema: t.inputSchema,
|
|
403
|
-
server: cfg.name,
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
if (res.nextCursor === undefined)
|
|
407
|
-
return tools;
|
|
408
|
-
if (typeof res.nextCursor !== "string")
|
|
409
|
-
throw new McpError("MCP tools cursor is not a string");
|
|
410
|
-
if (seen.has(res.nextCursor))
|
|
411
|
-
throw new McpError("MCP tool pagination returned the same cursor twice");
|
|
412
|
-
seen.add(res.nextCursor);
|
|
413
|
-
cursor = res.nextCursor;
|
|
414
|
-
}
|
|
415
|
-
throw new McpError(`MCP tools/list did not finish within ${MAX_PAGES} pages`);
|
|
131
|
+
for (let page = 0; page < 50; page++) {
|
|
132
|
+
const res = await client.listTools(cursor ? { cursor } : undefined);
|
|
133
|
+
all.push(...toTools(res, cfg.name));
|
|
134
|
+
const next = res.nextCursor;
|
|
135
|
+
if (typeof next !== "string")
|
|
136
|
+
return all;
|
|
137
|
+
if (seen.has(next))
|
|
138
|
+
throw new Error("MCP tool pagination returned the same cursor twice");
|
|
139
|
+
seen.add(next);
|
|
140
|
+
cursor = next;
|
|
141
|
+
}
|
|
142
|
+
throw new Error("MCP tools/list did not finish within 50 pages");
|
|
416
143
|
},
|
|
417
144
|
async call(name, args) {
|
|
418
|
-
const res =
|
|
419
|
-
|
|
420
|
-
for (const c of res?.content ?? []) {
|
|
421
|
-
if (c?.type === "text" && typeof c.text === "string")
|
|
422
|
-
parts.push(c.text);
|
|
423
|
-
else if (c?.type)
|
|
424
|
-
parts.push(`[${c.type} content omitted]`);
|
|
425
|
-
}
|
|
426
|
-
return { text: parts.join("\n") || "(no content)", ok: !res?.isError };
|
|
427
|
-
},
|
|
428
|
-
async close() {
|
|
429
|
-
child.kill();
|
|
430
|
-
},
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
/** connect to one configured server */
|
|
434
|
-
export async function connectMcp(cfg) {
|
|
435
|
-
const transport = cfg.transport ?? (cfg.command && !cfg.url ? "stdio" : "http");
|
|
436
|
-
if (transport === "stdio")
|
|
437
|
-
return connectStdio(cfg);
|
|
438
|
-
if (transport === "sse")
|
|
439
|
-
return connectLegacySse(cfg);
|
|
440
|
-
return connectHttp(cfg);
|
|
441
|
-
}
|
|
442
|
-
/**
|
|
443
|
-
* Legacy HTTP+SSE (2024-11-05): a GET holds an event stream open, the server sends an
|
|
444
|
-
* `endpoint` event naming a POST url, and replies to POSTs arrive ON the GET stream.
|
|
445
|
-
*
|
|
446
|
-
* Kept separate from `connectHttp` because the request/reply plumbing is genuinely
|
|
447
|
-
* different — there is no response body to read a result from — and folding them
|
|
448
|
-
* together produced a function that could not be followed.
|
|
449
|
-
*/
|
|
450
|
-
async function connectLegacySse(cfg) {
|
|
451
|
-
if (!cfg.url)
|
|
452
|
-
throw new McpError(`MCP server "${cfg.name}" has no url`);
|
|
453
|
-
const timeoutMs = cfg.timeoutMs ?? 20_000;
|
|
454
|
-
const ac = new AbortController();
|
|
455
|
-
const res = await fetch(cfg.url, {
|
|
456
|
-
headers: { accept: "text/event-stream", ...(cfg.headers ?? {}) },
|
|
457
|
-
signal: ac.signal,
|
|
458
|
-
});
|
|
459
|
-
if (!res.ok) {
|
|
460
|
-
await res.body?.cancel().catch(() => { });
|
|
461
|
-
throw new McpError(`MCP (legacy SSE) endpoint returned HTTP ${res.status}`, res.status === 401 || res.status === 403);
|
|
462
|
-
}
|
|
463
|
-
const reader = res.body?.getReader();
|
|
464
|
-
if (!reader)
|
|
465
|
-
throw new McpError("MCP (legacy SSE) endpoint returned an empty stream");
|
|
466
|
-
const decoder = new TextDecoder();
|
|
467
|
-
let endpoint = null;
|
|
468
|
-
let buf = "";
|
|
469
|
-
let seq = 0;
|
|
470
|
-
const pending = new Map();
|
|
471
|
-
const ready = new Promise((resolve, reject) => {
|
|
472
|
-
const timer = setTimeout(() => reject(new McpError(`MCP (legacy SSE) did not send an endpoint within ${timeoutMs}ms`)), timeoutMs);
|
|
473
|
-
(async () => {
|
|
474
|
-
try {
|
|
475
|
-
for (;;) {
|
|
476
|
-
const { done, value } = await reader.read();
|
|
477
|
-
if (done)
|
|
478
|
-
break;
|
|
479
|
-
buf += decoder.decode(value, { stream: true });
|
|
480
|
-
buf = buf.replace(/\r\n/g, "\n");
|
|
481
|
-
let end = buf.indexOf("\n\n");
|
|
482
|
-
while (end !== -1) {
|
|
483
|
-
const block = buf.slice(0, end);
|
|
484
|
-
buf = buf.slice(end + 2);
|
|
485
|
-
end = buf.indexOf("\n\n");
|
|
486
|
-
const ev = (/^event:\s*(.+)$/m.exec(block)?.[1] ?? "message").trim();
|
|
487
|
-
const data = sseData(block);
|
|
488
|
-
if (ev === "endpoint" && data) {
|
|
489
|
-
endpoint = new URL(data, cfg.url).toString();
|
|
490
|
-
clearTimeout(timer);
|
|
491
|
-
resolve();
|
|
492
|
-
continue;
|
|
493
|
-
}
|
|
494
|
-
if (!data)
|
|
495
|
-
continue;
|
|
496
|
-
let msg;
|
|
497
|
-
try {
|
|
498
|
-
msg = JSON.parse(data);
|
|
499
|
-
}
|
|
500
|
-
catch {
|
|
501
|
-
continue;
|
|
502
|
-
}
|
|
503
|
-
if (typeof msg.id !== "number")
|
|
504
|
-
continue;
|
|
505
|
-
const p = pending.get(msg.id);
|
|
506
|
-
if (!p)
|
|
507
|
-
continue;
|
|
508
|
-
pending.delete(msg.id);
|
|
509
|
-
if (msg.error)
|
|
510
|
-
p.reject(new McpError(`MCP error: ${msg.error.message ?? "request failed"}`));
|
|
511
|
-
else
|
|
512
|
-
p.resolve(msg.result);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
clearTimeout(timer);
|
|
516
|
-
reject(new McpError("MCP (legacy SSE) stream closed"));
|
|
517
|
-
}
|
|
518
|
-
catch (e) {
|
|
519
|
-
clearTimeout(timer);
|
|
520
|
-
reject(e);
|
|
521
|
-
}
|
|
522
|
-
})();
|
|
523
|
-
});
|
|
524
|
-
await ready;
|
|
525
|
-
if (!endpoint)
|
|
526
|
-
throw new McpError("MCP (legacy SSE) stream exposed no endpoint");
|
|
527
|
-
const postUrl = endpoint;
|
|
528
|
-
const send = async (method, params, notification = false) => {
|
|
529
|
-
const id = ++seq;
|
|
530
|
-
const body = {
|
|
531
|
-
jsonrpc: "2.0",
|
|
532
|
-
...(notification ? {} : { id }),
|
|
533
|
-
method,
|
|
534
|
-
...(params === undefined ? {} : { params }),
|
|
535
|
-
};
|
|
536
|
-
const r = await fetch(postUrl, {
|
|
537
|
-
method: "POST",
|
|
538
|
-
headers: { "content-type": "application/json", ...(cfg.headers ?? {}) },
|
|
539
|
-
body: JSON.stringify(body),
|
|
540
|
-
signal: ac.signal,
|
|
541
|
-
});
|
|
542
|
-
await r.body?.cancel().catch(() => { });
|
|
543
|
-
if (!r.ok)
|
|
544
|
-
throw new McpError(`MCP (legacy SSE) POST returned HTTP ${r.status}`, r.status === 401 || r.status === 403);
|
|
545
|
-
if (notification)
|
|
546
|
-
return undefined;
|
|
547
|
-
// the reply arrives on the GET stream, so wait for it there
|
|
548
|
-
return new Promise((resolve, reject) => {
|
|
549
|
-
const timer = setTimeout(() => {
|
|
550
|
-
pending.delete(id);
|
|
551
|
-
reject(new McpError(`MCP request timed out after ${timeoutMs}ms (${method})`));
|
|
552
|
-
}, timeoutMs);
|
|
553
|
-
pending.set(id, {
|
|
554
|
-
resolve: (v) => {
|
|
555
|
-
clearTimeout(timer);
|
|
556
|
-
resolve(v);
|
|
557
|
-
},
|
|
558
|
-
reject: (e) => {
|
|
559
|
-
clearTimeout(timer);
|
|
560
|
-
reject(e);
|
|
561
|
-
},
|
|
562
|
-
});
|
|
563
|
-
});
|
|
564
|
-
};
|
|
565
|
-
const init = (await send("initialize", {
|
|
566
|
-
protocolVersion: "2024-11-05",
|
|
567
|
-
capabilities: {},
|
|
568
|
-
clientInfo: { name: "teapot", version: "1" },
|
|
569
|
-
}));
|
|
570
|
-
if (!init?.protocolVersion || !KNOWN_VERSIONS.includes(init.protocolVersion))
|
|
571
|
-
throw new McpError(`unsupported MCP protocol version: ${init?.protocolVersion ?? "(none)"}`);
|
|
572
|
-
await send("notifications/initialized", undefined, true);
|
|
573
|
-
return {
|
|
574
|
-
async tools() {
|
|
575
|
-
const out = [];
|
|
576
|
-
let cursor;
|
|
577
|
-
const seen = new Set();
|
|
578
|
-
for (let page = 0; page < MAX_PAGES; page++) {
|
|
579
|
-
const r = (await send("tools/list", cursor ? { cursor } : {}));
|
|
580
|
-
if (!Array.isArray(r?.tools))
|
|
581
|
-
throw new McpError("MCP tools/list did not return a tools array");
|
|
582
|
-
for (const t of r.tools) {
|
|
583
|
-
if (typeof t?.name !== "string" || !t.name)
|
|
584
|
-
throw new McpError("MCP tool is missing a name");
|
|
585
|
-
if (typeof t.inputSchema !== "object" || t.inputSchema === null || Array.isArray(t.inputSchema))
|
|
586
|
-
throw new McpError(`MCP tool "${t.name}" has no object inputSchema`);
|
|
587
|
-
out.push({
|
|
588
|
-
name: t.name,
|
|
589
|
-
description: typeof t.description === "string" ? t.description : "",
|
|
590
|
-
inputSchema: t.inputSchema,
|
|
591
|
-
server: cfg.name,
|
|
592
|
-
});
|
|
593
|
-
}
|
|
594
|
-
if (r.nextCursor === undefined)
|
|
595
|
-
return out;
|
|
596
|
-
if (typeof r.nextCursor !== "string")
|
|
597
|
-
throw new McpError("MCP tools cursor is not a string");
|
|
598
|
-
if (seen.has(r.nextCursor))
|
|
599
|
-
throw new McpError("MCP tool pagination returned the same cursor twice");
|
|
600
|
-
seen.add(r.nextCursor);
|
|
601
|
-
cursor = r.nextCursor;
|
|
602
|
-
}
|
|
603
|
-
throw new McpError(`MCP tools/list did not finish within ${MAX_PAGES} pages`);
|
|
145
|
+
const res = await client.callTool({ name, arguments: (args ?? {}) });
|
|
146
|
+
return resultText(res);
|
|
604
147
|
},
|
|
605
|
-
async
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
}
|
|
614
|
-
return { text: parts.join("\n") || "(no content)", ok: !r?.isError };
|
|
148
|
+
async finishAuth(code, iss) {
|
|
149
|
+
// the VERIFIER and discovery state live on the transport, so completing the
|
|
150
|
+
// exchange must go through the same instance that started the flow
|
|
151
|
+
if (!(session instanceof StreamableHTTPClientTransport) && !(session instanceof SSEClientTransport))
|
|
152
|
+
throw new Error("this transport has no OAuth flow");
|
|
153
|
+
await session.finishAuth(iss === undefined ? code : new URLSearchParams({ code, iss }));
|
|
154
|
+
// the connection failed at connect() time (401); finish the handshake now
|
|
155
|
+
await client.connect(session);
|
|
615
156
|
},
|
|
616
157
|
async close() {
|
|
617
|
-
|
|
618
|
-
await reader.cancel().catch(() => { });
|
|
158
|
+
await client.close().catch(() => { });
|
|
619
159
|
},
|
|
620
160
|
};
|
|
621
161
|
}
|