@koneeric/onetool 0.0.0-stage → 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.
@@ -0,0 +1,301 @@
1
+ // Runs a JavaScript program in a process of its own. See the meeting point of sandbox.
2
+ //
3
+ // Lines on the program process's standard input (from here):
4
+ // { t: "init", code, tools, state, shell, progress, library } once, first; state is JSON text, or null when none
5
+ // was given; shell is true when the program finds `$`, `read`, `write`
6
+ // and `edit`; progress is true when it finds `progress`; library is
7
+ // the list of { name, params, code }, or null when none was given
8
+ // { t: "result", id, status, text } the answer of a tool call: status "ok" (text is JSON),
9
+ // "undefined" or "error" (text is the message)
10
+ // Lines on its standard output (to here):
11
+ // { t: "log", s } { t: "progress", s } { t: "use", name, ok } { t: "call", id, server, tool, args }
12
+ // { t: "done", kind, text, state }
13
+ // state is JSON text, or null when the state cannot be held; it is absent when none was given.
14
+ // checkWalls runs probe.mjs in a process started by the same code (launch), and reads one line of it.
15
+ import { spawn } from "node:child_process";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const CHILD = fileURLToPath(new URL("./child.mjs", import.meta.url));
19
+ const PROBE = fileURLToPath(new URL("./probe.mjs", import.meta.url));
20
+ const FILES = [CHILD, fileURLToPath(new URL("./last-expression.mjs", import.meta.url))];
21
+ const DEFAULT_MEMORY_MB = 256;
22
+ const NOT_KEPT = "state was not kept: it cannot be sent as JSON";
23
+ const LONGEST_TIMER = 2 ** 31 - 1;
24
+
25
+ const running = new Set();
26
+ let listening = false;
27
+
28
+ function kill(child) {
29
+ if (child.exitCode === null && child.signalCode === null) {
30
+ try {
31
+ child.kill("SIGKILL");
32
+ } catch {
33
+ // already gone
34
+ }
35
+ }
36
+ }
37
+
38
+ function listen() {
39
+ if (listening) return;
40
+ listening = true;
41
+ process.on("exit", () => {
42
+ for (const child of running) kill(child);
43
+ });
44
+ }
45
+
46
+ // The one place a process of the sandbox is started: a program and the probe of checkWalls differ only in the
47
+ // file they run (and the files they may read).
48
+ function launch(script, { files, memoryMb, args = [] }) {
49
+ const child = spawn(
50
+ process.execPath,
51
+ ["--permission", ...files.map((file) => `--allow-fs-read=${file}`), `--max-old-space-size=${memoryMb}`, script, ...args],
52
+ { env: {}, stdio: ["pipe", "pipe", "ignore"], windowsHide: true },
53
+ );
54
+ running.add(child);
55
+ child.stdout.setEncoding("utf8");
56
+ child.stdout.on("error", () => {});
57
+ child.stdin.on("error", () => {});
58
+ return child;
59
+ }
60
+
61
+ function onLines(child, onLine) {
62
+ let buffer = "";
63
+ child.stdout.on("data", (chunk) => {
64
+ buffer += chunk;
65
+ let end;
66
+ while ((end = buffer.indexOf("\n")) >= 0) {
67
+ const line = buffer.slice(0, end);
68
+ buffer = buffer.slice(end + 1);
69
+ onLine(line);
70
+ }
71
+ });
72
+ }
73
+
74
+ // The JSON text of a state the caller gave, or a TypeError.
75
+ function stateText(state) {
76
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
77
+ throw new TypeError("state must be a plain object that JSON.stringify can turn to text");
78
+ }
79
+ let text;
80
+ try {
81
+ text = JSON.stringify(state);
82
+ } catch {
83
+ throw new TypeError("state must be a plain object that JSON.stringify can turn to text");
84
+ }
85
+ const back = typeof text === "string" ? JSON.parse(text) : null;
86
+ if (typeof back !== "object" || back === null || Array.isArray(back)) {
87
+ throw new TypeError("state must be a plain object that JSON.stringify can turn to text");
88
+ }
89
+ return text;
90
+ }
91
+
92
+ function isPlainObject(value) {
93
+ if (typeof value !== "object" || value === null) return false;
94
+ const prototype = Object.getPrototypeOf(value);
95
+ return prototype === Object.prototype || prototype === null;
96
+ }
97
+
98
+ function checkLibrary(library) {
99
+ const bad = new TypeError("library must be a list of { name, params, code }: a string, a list of strings, a string");
100
+ if (!Array.isArray(library)) throw bad;
101
+ for (const item of library) {
102
+ if (!isPlainObject(item) || typeof item.name !== "string" || typeof item.code !== "string") throw bad;
103
+ if (!Array.isArray(item.params) || !item.params.every((param) => typeof param === "string")) throw bad;
104
+ }
105
+ }
106
+
107
+ function check(code, { tools, callTool, timeoutMs, memoryMb, shell, onProgress, signal, library, onLibrary }) {
108
+ if (typeof code !== "string") throw new TypeError("code must be a string");
109
+ if (typeof tools !== "object" || tools === null || Array.isArray(tools)) {
110
+ throw new TypeError("tools must be an object of arrays of strings or the value true");
111
+ }
112
+ let named = false;
113
+ for (const list of Object.values(tools)) {
114
+ if (list === true) named = true;
115
+ else if (!Array.isArray(list) || !list.every((name) => typeof name === "string")) {
116
+ throw new TypeError("tools must be an object of arrays of strings or the value true");
117
+ }
118
+ else if (list.length > 0) named = true;
119
+ }
120
+ if (typeof shell !== "boolean") throw new TypeError("shell must be true or false");
121
+ if ((named || shell) && typeof callTool !== "function") {
122
+ throw new TypeError("callTool must be a function when tools names a tool or a server given as true, or shell is true");
123
+ }
124
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
125
+ throw new TypeError("timeoutMs must be a finite number above 0");
126
+ }
127
+ if (typeof memoryMb !== "number" || !Number.isInteger(memoryMb) || memoryMb < 16) {
128
+ throw new TypeError("memoryMb must be a whole number of 16 or more");
129
+ }
130
+ if (onProgress !== undefined && typeof onProgress !== "function") throw new TypeError("onProgress must be a function");
131
+ if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal");
132
+ if (library !== undefined) {
133
+ checkLibrary(library);
134
+ if (typeof callTool !== "function") throw new TypeError("callTool must be a function when library is given");
135
+ }
136
+ if (onLibrary !== undefined && typeof onLibrary !== "function") throw new TypeError("onLibrary must be a function");
137
+ }
138
+
139
+ // A line goes to the caller's function; what it does or returns is no concern of the program.
140
+ function post(onProgress, line) {
141
+ try {
142
+ const returned = onProgress(line);
143
+ if (returned instanceof Promise) returned.catch(() => {});
144
+ } catch {
145
+ // the program is not told
146
+ }
147
+ }
148
+
149
+ function messageOf(thrown) {
150
+ try {
151
+ const message = thrown?.message;
152
+ if (message !== undefined && message !== null) return String(message);
153
+ } catch {
154
+ // fall through
155
+ }
156
+ try {
157
+ return String(thrown);
158
+ } catch {
159
+ return "";
160
+ }
161
+ }
162
+
163
+ export async function runProgram(
164
+ code,
165
+ { tools = {}, callTool, timeoutMs = 60000, memoryMb = DEFAULT_MEMORY_MB, state, shell = false, onProgress, signal, library, onLibrary } = {},
166
+ ) {
167
+ check(code, { tools, callTool, timeoutMs, memoryMb, shell, onProgress, signal, library, onLibrary });
168
+ const given = state === undefined ? undefined : stateText(state);
169
+ const stopped = () => {
170
+ const result = { ok: false, error: { kind: "stopped", message: "stopped by the caller" }, logs: [] };
171
+ if (given !== undefined) result.state = JSON.parse(given);
172
+ return result;
173
+ };
174
+ if (signal?.aborted) return stopped();
175
+ listen();
176
+
177
+ return new Promise((resolve) => {
178
+ const logs = [];
179
+ let finished = false;
180
+
181
+ const child = launch(CHILD, { files: FILES, memoryMb });
182
+
183
+ const timer = setTimeout(
184
+ () => finish({ ok: false, error: { kind: "timeout", message: `stopped after ${timeoutMs} ms` }, logs }),
185
+ Math.min(timeoutMs, LONGEST_TIMER),
186
+ );
187
+
188
+ // childState: the state text the program's process sent; anything else gives the argument back.
189
+ function finish(result, childState) {
190
+ if (finished) return;
191
+ finished = true;
192
+ if (given !== undefined) result.state = JSON.parse(typeof childState === "string" ? childState : given);
193
+ clearTimeout(timer);
194
+ signal?.removeEventListener("abort", onAbort);
195
+ running.delete(child);
196
+ kill(child);
197
+ resolve(result);
198
+ }
199
+ const onAbort = () => fail("stopped", "stopped by the caller");
200
+ const fail = (kind, message, childState) => finish({ ok: false, error: { kind, message }, logs }, childState);
201
+
202
+ const send = (message) => {
203
+ if (child.stdin.writable) child.stdin.write(JSON.stringify(message) + "\n");
204
+ };
205
+
206
+ async function answer({ id, server, tool, args }) {
207
+ let reply;
208
+ try {
209
+ if (finished) return;
210
+ const value = await callTool(server, tool, JSON.parse(args));
211
+ const json = value === undefined ? undefined : JSON.stringify(value);
212
+ reply = json === undefined ? { status: "undefined" } : { status: "ok", text: json };
213
+ } catch (thrown) {
214
+ reply = { status: "error", text: messageOf(thrown) };
215
+ }
216
+ if (!finished) send({ t: "result", id, ...reply });
217
+ }
218
+
219
+ function onLine(line) {
220
+ if (finished) return;
221
+ let message;
222
+ try {
223
+ message = JSON.parse(line);
224
+ } catch {
225
+ return;
226
+ }
227
+ if (message.t === "log") logs.push(message.s);
228
+ else if (message.t === "progress") {
229
+ if (onProgress !== undefined) post(onProgress, message.s);
230
+ }
231
+ else if (message.t === "use") {
232
+ if (onLibrary !== undefined) post(onLibrary, { name: String(message.name), ok: message.ok === true });
233
+ }
234
+ else if (message.t === "call") answer(message);
235
+ else if (message.t === "done") {
236
+ if (message.kind === "error") fail("error", message.text, message.state);
237
+ else if (given !== undefined && typeof message.state !== "string") fail("error", NOT_KEPT);
238
+ else finish({ ok: true, value: message.kind === "value" ? JSON.parse(message.text) : undefined, logs }, message.state);
239
+ }
240
+ }
241
+
242
+ onLines(child, onLine);
243
+ child.on("error", () => fail("crash", "code null, signal null"));
244
+ child.on("close", (exitCode, signal) => fail("crash", `code ${exitCode}, signal ${signal}`));
245
+
246
+ signal?.addEventListener("abort", onAbort, { once: true });
247
+ send({
248
+ t: "init",
249
+ code,
250
+ tools,
251
+ state: given ?? null,
252
+ shell,
253
+ progress: onProgress !== undefined,
254
+ library: library === undefined ? null : library.map(({ name, params, code }) => ({ name, params, code })),
255
+ });
256
+ });
257
+ }
258
+
259
+ const WALL = new Set(["refused", "done", "failed"]);
260
+
261
+ export async function checkWalls(probePath, { timeoutMs = 10000 } = {}) {
262
+ if (typeof probePath !== "string" || probePath === "") throw new TypeError("probePath must be the path of a file");
263
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
264
+ throw new TypeError("timeoutMs must be a finite number above 0");
265
+ }
266
+ listen();
267
+
268
+ return new Promise((resolve, reject) => {
269
+ let settled = false;
270
+ const child = launch(PROBE, { files: [...FILES, PROBE], memoryMb: DEFAULT_MEMORY_MB, args: [probePath] });
271
+
272
+ const timer = setTimeout(
273
+ () => settle(() => reject(new Error(`the probe did not answer in ${timeoutMs} ms`))),
274
+ Math.min(timeoutMs, LONGEST_TIMER),
275
+ );
276
+
277
+ function settle(outcome) {
278
+ if (settled) return;
279
+ settled = true;
280
+ clearTimeout(timer);
281
+ running.delete(child);
282
+ kill(child);
283
+ outcome();
284
+ }
285
+
286
+ onLines(child, (line) => {
287
+ let walls;
288
+ try {
289
+ walls = JSON.parse(line);
290
+ } catch {
291
+ return;
292
+ }
293
+ const keys = ["read", "write", "spawn", "worker"];
294
+ if (walls === null || typeof walls !== "object" || !keys.every((key) => WALL.has(walls[key]))) return;
295
+ settle(() => resolve(Object.fromEntries(keys.map((key) => [key, walls[key]]))));
296
+ });
297
+ const ended = () => settle(() => reject(new Error("the probe ended before it answered")));
298
+ child.on("error", ended);
299
+ child.on("close", ended);
300
+ });
301
+ }
@@ -0,0 +1,134 @@
1
+ // Finds the value of a program without a parser. The text is cut at the ends of lines and after semicolons that
2
+ // stand outside every bracket, string, template and comment; each cut gives a text whose tail is wrapped in
3
+ // `return (...)`. The caller compiles the texts in turn and keeps the first that is valid JavaScript.
4
+
5
+ const KEYWORDS_BEFORE_REGEX = new Set([
6
+ "return", "typeof", "case", "do", "else", "in", "of", "instanceof", "new", "void", "delete", "throw", "yield", "await",
7
+ ]);
8
+ const WORD = /[\w$]/;
9
+ // A tail that starts like this is a declaration: as an expression it would lose its hoisting.
10
+ const DECLARATION = /^\s*(async\s+function|function|class)\b/;
11
+ const MOST_CUTS = 64;
12
+
13
+ function regexAllowed(src, p) {
14
+ if (p < 0) return true;
15
+ const c = src[p];
16
+ if (WORD.test(c)) {
17
+ let s = p;
18
+ while (s >= 0 && WORD.test(src[s])) s--;
19
+ return KEYWORDS_BEFORE_REGEX.has(src.slice(s + 1, p + 1));
20
+ }
21
+ return c !== ")" && c !== "]" && c !== '"' && c !== "'" && c !== "`";
22
+ }
23
+
24
+ function scan(src) {
25
+ const n = src.length;
26
+ const cuts = [];
27
+ const semicolons = new Map(); // position of a `;` -> position of the significant character before it
28
+ const stack = [];
29
+ let lastSig = -1;
30
+ let i = 0;
31
+
32
+ const cut = (p) => {
33
+ if (cuts[cuts.length - 1] !== p) cuts.push(p);
34
+ };
35
+ const skipString = (j) => {
36
+ const quote = src[j++];
37
+ while (j < n) {
38
+ const c = src[j];
39
+ if (c === "\\") j += 2;
40
+ else if (c === quote) return j + 1;
41
+ else if (c === "\n") return j;
42
+ else j++;
43
+ }
44
+ return n;
45
+ };
46
+ // From inside a template: to after its closing backquote, or to after a `${`, which opens code again.
47
+ const skipTemplate = (j) => {
48
+ while (j < n) {
49
+ const c = src[j];
50
+ if (c === "\\") j += 2;
51
+ else if (c === "`") return j + 1;
52
+ else if (c === "$" && src[j + 1] === "{") {
53
+ stack.push("${");
54
+ return j + 2;
55
+ } else j++;
56
+ }
57
+ return n;
58
+ };
59
+ const skipRegex = (j) => {
60
+ let inClass = false;
61
+ j++;
62
+ while (j < n) {
63
+ const c = src[j];
64
+ if (c === "\\") j += 2;
65
+ else if (c === "\n") return j;
66
+ else {
67
+ j++;
68
+ if (c === "[") inClass = true;
69
+ else if (c === "]") inClass = false;
70
+ else if (c === "/" && !inClass) break;
71
+ }
72
+ }
73
+ while (j < n && WORD.test(src[j])) j++;
74
+ return j;
75
+ };
76
+
77
+ while (i < n) {
78
+ const c = src[i];
79
+ if (c === "\n") {
80
+ if (!stack.length) cut(i + 1);
81
+ i++;
82
+ } else if (/\s/.test(c)) {
83
+ i++;
84
+ } else if (c === "/" && src[i + 1] === "/") {
85
+ while (i < n && src[i] !== "\n") i++;
86
+ } else if (c === "/" && src[i + 1] === "*") {
87
+ const close = src.indexOf("*/", i + 2);
88
+ i = close < 0 ? n : close + 2;
89
+ } else if (c === '"' || c === "'") {
90
+ i = skipString(i);
91
+ lastSig = i - 1;
92
+ } else if (c === "`") {
93
+ i = skipTemplate(i + 1);
94
+ lastSig = i - 1;
95
+ } else if (c === "/" && regexAllowed(src, lastSig)) {
96
+ i = skipRegex(i);
97
+ lastSig = i - 1;
98
+ } else if (c === "}" && stack[stack.length - 1] === "${") {
99
+ stack.pop();
100
+ i = skipTemplate(i + 1);
101
+ lastSig = i - 1;
102
+ } else {
103
+ if (c === "(" || c === "[" || c === "{") stack.push(c);
104
+ else if (c === ")" || c === "]" || c === "}") stack.pop();
105
+ else if (c === ";") {
106
+ semicolons.set(i, lastSig);
107
+ if (!stack.length) cut(i + 1);
108
+ }
109
+ lastSig = i;
110
+ i++;
111
+ }
112
+ }
113
+
114
+ // The end of the program's code: without comments, white space and final semicolons.
115
+ let end = lastSig + 1;
116
+ while (end > 0 && src[end - 1] === ";" && semicolons.has(end - 1)) end = semicolons.get(end - 1) + 1;
117
+ return { cuts, end };
118
+ }
119
+
120
+ // The texts to try, the one that gives the most to the last expression first. None when the program has no code.
121
+ export function* withLastExpression(src) {
122
+ const { cuts, end } = scan(src);
123
+ if (end === 0) return;
124
+ let tried = 0;
125
+ for (let k = cuts.length - 1; k >= 0 && tried < MOST_CUTS; k--) {
126
+ if (cuts[k] >= end) continue;
127
+ const tail = src.slice(cuts[k], end);
128
+ if (DECLARATION.test(tail)) continue;
129
+ tried++;
130
+ yield src.slice(0, cuts[k]) + "\nreturn (\n" + tail + "\n)";
131
+ }
132
+ const whole = src.slice(0, end);
133
+ if (!DECLARATION.test(whole)) yield "return (\n" + whole + "\n)";
134
+ }
@@ -0,0 +1,42 @@
1
+ // The probe of checkWalls, run in a process started as the process of a program is. argv[2] is the path of a file
2
+ // that exists outside sandbox/src. It tries four things the program may not do and writes one line to standard
3
+ // output: { read, write, spawn, worker }, each "refused" (ERR_ACCESS_DENIED), "done" or "failed" (anything else).
4
+ import fs from "node:fs";
5
+ import { spawn } from "node:child_process";
6
+ import { Worker } from "node:worker_threads";
7
+
8
+ const target = process.argv[2];
9
+ const cleanup = [];
10
+
11
+ function attempt(fn) {
12
+ try {
13
+ fn();
14
+ return "done";
15
+ } catch (thrown) {
16
+ return thrown?.code === "ERR_ACCESS_DENIED" ? "refused" : "failed";
17
+ }
18
+ }
19
+
20
+ const walls = {
21
+ read: attempt(() => fs.readFileSync(target)),
22
+ write: attempt(() => fs.writeFileSync(target + ".written", "written by the probe\n")),
23
+ spawn: attempt(() => {
24
+ const child = spawn(process.execPath, ["--version"], { stdio: "ignore" });
25
+ child.on("error", () => {});
26
+ cleanup.push(() => child.kill("SIGKILL"));
27
+ }),
28
+ worker: attempt(() => {
29
+ const worker = new Worker("0", { eval: true });
30
+ worker.on("error", () => {});
31
+ cleanup.push(() => worker.terminate());
32
+ }),
33
+ };
34
+
35
+ for (const stop of cleanup) {
36
+ try {
37
+ stop();
38
+ } catch {
39
+ // nothing to stop
40
+ }
41
+ }
42
+ process.stdout.write(JSON.stringify(walls) + "\n", () => process.exit(0));
@@ -0,0 +1,190 @@
1
+ // The connection to one listed server: start its process, speak MCP to it, read its list of tools.
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
4
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
5
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
7
+ import { quietProvider, signInStamp } from "../../auth/src/index.js";
8
+ import { keptTools, signsIn } from "../../core/src/index.js";
9
+
10
+ /** The transport of the package, which also knows when the process of the server has ended. */
11
+ class Transport extends StdioClientTransport {
12
+ ended = false;
13
+
14
+ async start() {
15
+ await super.start();
16
+ this._process?.once("close", () => {
17
+ this.ended = true;
18
+ });
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Whether `err` is a JSON-RPC error that the server itself answered, and not one the package makes when its own
24
+ * request is given up or its connection is gone.
25
+ */
26
+ export function isServerError(err) {
27
+ if (!(err instanceof McpError)) return false;
28
+ if (err.code === ErrorCode.RequestTimeout) return false;
29
+ return !(err.code === ErrorCode.ConnectionClosed && err.message === `MCP error ${err.code}: Connection closed`);
30
+ }
31
+
32
+ /**
33
+ * Whether `err` is the server asking for a sign-in that is not there or not good: the package's `UnauthorizedError`, or
34
+ * the error of its transport for an HTTP status 401. Written against the package at 1.32.2.
35
+ */
36
+ export function isSignInFailure(err) {
37
+ return err instanceof UnauthorizedError || err?.code === 401;
38
+ }
39
+
40
+ /** The stamp of the sign-in of a sign-in server in the home folder: `null` when there is none usable. */
41
+ function stampOf(entry) {
42
+ try {
43
+ return signInStamp(entry.name, entry.url);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * One listed server. `tools` is its list once connected; `error` the reason when it is not; `needed` that it is a
51
+ * sign-in server that needs a sign-in (neither `tools` nor `error` then). `connect()` never rejects: it settles one of
52
+ * the three, and may be called again for a server that is sign in needed.
53
+ */
54
+ export class Connection {
55
+ constructor(name, entry, connectSeconds, version) {
56
+ this.name = name;
57
+ this.entry = entry;
58
+ this.connectSeconds = connectSeconds;
59
+ this.version = version;
60
+ this.tools = null;
61
+ this.error = null;
62
+ this.client = null;
63
+ this.transport = null;
64
+ this.closing = null;
65
+ this.needed = false;
66
+ this.signIn = !Object.hasOwn(entry, "url") ? false : signsIn(entry);
67
+ // the stamp of the sign-in the last connection used, and whether it was given a provider
68
+ this.stampTried = null;
69
+ this.withSignIn = false;
70
+ }
71
+
72
+ /** Whether it is reached at an address: it then has no process of its own. */
73
+ get remote() {
74
+ return Object.hasOwn(this.entry, "url");
75
+ }
76
+
77
+ get connected() {
78
+ return this.tools !== null && (this.remote || !this.transport.ended);
79
+ }
80
+
81
+ /** The stamp of the sign-in file now; `null` for a server that is not a sign-in server or has none. */
82
+ stamp() {
83
+ return this.signIn ? stampOf(this.entry) : null;
84
+ }
85
+
86
+ makeTransport() {
87
+ if (this.remote) {
88
+ const { url, headers } = this.entry;
89
+ const options = { requestInit: { headers } };
90
+ if (this.signIn) {
91
+ const stamp = stampOf(this.entry);
92
+ this.stampTried = stamp;
93
+ this.withSignIn = stamp !== null;
94
+ if (stamp !== null) options.authProvider = quietProvider(this.entry.name, url, { oauth: this.entry.oauth });
95
+ }
96
+ return new StreamableHTTPClientTransport(new URL(url), options);
97
+ }
98
+ const { command, args, env } = this.entry;
99
+ return new Transport({ command, args, env, stderr: "inherit" });
100
+ }
101
+
102
+ async connect() {
103
+ const ms = this.connectSeconds * 1000;
104
+ this.closing = null;
105
+ let tools = null;
106
+ let error = null;
107
+ let needed = false;
108
+ try {
109
+ this.transport = this.makeTransport();
110
+ } catch {
111
+ this.tools = null;
112
+ this.needed = false;
113
+ this.error = "could not connect";
114
+ return this;
115
+ }
116
+ this.client = new Client({ name: "onetool", version: this.version });
117
+ let timer;
118
+ const timeout = new Promise((resolve) => {
119
+ timer = setTimeout(() => resolve("timeout"), ms);
120
+ });
121
+ // the package's own request limit is kept above ours, so that ours speaks first
122
+ const options = { timeout: ms + 5000 };
123
+ const work = (async () => {
124
+ await this.client.connect(this.transport, options);
125
+ const tools = [];
126
+ let cursor;
127
+ do {
128
+ const page = await this.client.listTools(cursor === undefined ? undefined : { cursor }, options);
129
+ tools.push(...page.tools);
130
+ cursor = page.nextCursor;
131
+ } while (cursor);
132
+ return tools;
133
+ })();
134
+ work.catch(() => {});
135
+ try {
136
+ const got = await Promise.race([work, timeout]);
137
+ if (got === "timeout") {
138
+ error = `no answer in ${String(this.connectSeconds)} seconds`;
139
+ } else {
140
+ // an entry with `tools` offers only those tools
141
+ tools = Object.hasOwn(this.entry, "tools") ? keptTools(got, this.entry.tools) : got;
142
+ }
143
+ } catch (err) {
144
+ if (this.signIn && isSignInFailure(err)) {
145
+ needed = true;
146
+ } else if (this.remote) {
147
+ error = isServerError(err) ? "refused the connection" : "could not connect";
148
+ } else {
149
+ const refused = err instanceof McpError && !this.transport.ended;
150
+ error = refused ? "refused the connection" : "could not start";
151
+ }
152
+ } finally {
153
+ clearTimeout(timer);
154
+ }
155
+ this.tools = tools;
156
+ this.error = error;
157
+ this.needed = needed;
158
+ if (error !== null || needed) this.close();
159
+ return this;
160
+ }
161
+
162
+ /**
163
+ * The connection of a sign-in server is closed and its tools are forgotten: it is sign in needed, and `stamp` is the
164
+ * stamp of the file that did not work.
165
+ */
166
+ goNeeded(stamp) {
167
+ this.tools = null;
168
+ this.error = null;
169
+ this.needed = true;
170
+ this.stampTried = stamp;
171
+ return this.close();
172
+ }
173
+
174
+ /** Ends the connection and its process. Gives a promise that is settled once they are gone. */
175
+ close() {
176
+ if (!this.transport) return Promise.resolve();
177
+ this.closing ??= this.transport.close().catch(() => {});
178
+ return this.closing;
179
+ }
180
+
181
+ /** Ends the process at once, whatever it does. */
182
+ kill() {
183
+ const pid = this.transport?.pid;
184
+ if (pid) {
185
+ try {
186
+ process.kill(pid, "SIGKILL");
187
+ } catch {}
188
+ }
189
+ }
190
+ }