@ant0/mcp 0.0.0-stage → 0.3.22-beta.8

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.
Files changed (54) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +95 -2
  3. package/THIRD_PARTY_NOTICES +311 -0
  4. package/dist/api/generated/schema.d.ts +7340 -0
  5. package/dist/api/generated/schema.js +6 -0
  6. package/dist/api/index.d.ts +171 -0
  7. package/dist/api/index.js +332 -0
  8. package/dist/bin.d.ts +3 -0
  9. package/dist/bin.js +59 -0
  10. package/dist/call-permits.d.ts +10 -0
  11. package/dist/call-permits.js +67 -0
  12. package/dist/connection.d.ts +20 -0
  13. package/dist/connection.js +157 -0
  14. package/dist/credential-file.d.ts +33 -0
  15. package/dist/credential-file.js +773 -0
  16. package/dist/daemon.d.ts +7 -0
  17. package/dist/daemon.js +306 -0
  18. package/dist/errors.d.ts +92 -0
  19. package/dist/errors.js +101 -0
  20. package/dist/export-files.d.ts +37 -0
  21. package/dist/export-files.js +167 -0
  22. package/dist/grant.d.ts +5 -0
  23. package/dist/grant.js +11 -0
  24. package/dist/http-local.d.ts +38 -0
  25. package/dist/http-local.js +324 -0
  26. package/dist/http.d.ts +66 -0
  27. package/dist/http.js +556 -0
  28. package/dist/index.d.ts +21 -0
  29. package/dist/index.js +86 -0
  30. package/dist/key-contract.d.ts +325 -0
  31. package/dist/key-contract.js +241 -0
  32. package/dist/limits.d.ts +22 -0
  33. package/dist/limits.js +22 -0
  34. package/dist/local-routes.d.ts +30 -0
  35. package/dist/local-routes.js +231 -0
  36. package/dist/output-descriptor.d.ts +3 -0
  37. package/dist/output-descriptor.js +19 -0
  38. package/dist/output-worker-body.d.ts +3 -0
  39. package/dist/output-worker-body.js +77 -0
  40. package/dist/output-worker.d.ts +2 -0
  41. package/dist/output-worker.js +4 -0
  42. package/dist/output-writer.d.ts +39 -0
  43. package/dist/output-writer.js +199 -0
  44. package/dist/peer-watchdog.d.ts +4 -0
  45. package/dist/peer-watchdog.js +55 -0
  46. package/dist/server.d.ts +28 -0
  47. package/dist/server.js +33 -0
  48. package/dist/text-budget.d.ts +13 -0
  49. package/dist/text-budget.js +42 -0
  50. package/dist/tools.d.ts +39 -0
  51. package/dist/tools.js +1893 -0
  52. package/dist/transport.d.ts +45 -0
  53. package/dist/transport.js +313 -0
  54. package/package.json +66 -4
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Daemon routes reachable ONLY with the local bearer (never with a private credential or API key).
3
+ * Each entry is an exact (method, path) pair with the single success status the route returns.
4
+ * The daemon's own key-auth allowlist already rejects API keys on these routes; this table is the
5
+ * adapter-side half, and `daemonClient` consults it only when the connection is not in key mode.
6
+ */
7
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
8
+ /** Query-string check from a fixed allowlist: known keys only, each once, each value valid. */
9
+ const queryOf = (allowed) => (params) => {
10
+ const keys = [...params.keys()];
11
+ if (new Set(keys).size !== keys.length)
12
+ return false;
13
+ return keys.every((key) => Object.hasOwn(allowed, key) && allowed[key](params.get(key)));
14
+ };
15
+ const TAB_VALUE = (value) => /^[A-Za-z0-9-]{8,64}$/.test(value);
16
+ const REF_VALUE = (value) => /^[A-Za-z0-9]{1,32}$/.test(value);
17
+ const intIn = (min, max) => (value) => /^\d{1,6}$/.test(value) && Number(value) >= min && Number(value) <= max;
18
+ /** Hand-off request ids are opaque; the daemon owns their shape, so only the charset is bound. */
19
+ export const HUMAN_ID = "[A-Za-z0-9_-]{1,64}";
20
+ const pagePath = (tail) => new RegExp(`^/v1/profiles/${UUID}/page/${tail}$`);
21
+ const exportQuery = (params) => {
22
+ const keys = [...params.keys()];
23
+ if (keys.length > 1 || keys.some((key) => key !== "format"))
24
+ return false;
25
+ const formats = params.getAll("format");
26
+ return formats.every((format) => format === "json" || format === "netscape");
27
+ };
28
+ export const LOCAL_ROUTES = Object.freeze([
29
+ { method: "POST", path: /^\/v1\/profiles$/, status: 201, body: true },
30
+ { method: "PATCH", path: new RegExp(`^/v1/profiles/${UUID}$`), status: 200, body: true },
31
+ { method: "POST", path: new RegExp(`^/v1/profiles/${UUID}/duplicate$`), status: 201, body: true },
32
+ // No query string is ever allowed here, so `permanent`, `purge` and `cloud` cannot be sent.
33
+ { method: "DELETE", path: new RegExp(`^/v1/profiles/${UUID}$`), status: 204, body: false },
34
+ { method: "POST", path: new RegExp(`^/v1/profiles/${UUID}/restore$`), status: 200, body: true },
35
+ { method: "GET", path: new RegExp(`^/v1/profiles/${UUID}/identity$`), status: 200, body: false },
36
+ // Run state with the CDP endpoint. No query string is allowed; the daemon alone decides access.
37
+ { method: "GET", path: new RegExp(`^/v1/profiles/${UUID}/status$`), status: 200, body: false },
38
+ // The profile's agent rules (read only): the tools that would bypass them check this first.
39
+ {
40
+ method: "GET",
41
+ path: new RegExp(`^/v1/profiles/${UUID}/agent-rules$`),
42
+ status: 200,
43
+ body: false,
44
+ },
45
+ { method: "POST", path: /^\/v1\/proxies$/, status: 201, body: true },
46
+ { method: "POST", path: new RegExp(`^/v1/proxies/${UUID}/check$`), status: 200, body: true },
47
+ { method: "POST", path: new RegExp(`^/v1/proxies/${UUID}/change-ip$`), status: 200, body: true },
48
+ {
49
+ method: "GET",
50
+ path: new RegExp(`^/v1/profiles/${UUID}/cookies$`),
51
+ status: 200,
52
+ body: false,
53
+ text: true,
54
+ query: exportQuery,
55
+ },
56
+ { method: "POST", path: new RegExp(`^/v1/profiles/${UUID}/cookies$`), status: 200, body: true },
57
+ // Page actions. Exact paths; the GET query strings are fixed allowlists.
58
+ {
59
+ method: "GET",
60
+ path: pagePath("snapshot"),
61
+ status: 200,
62
+ body: false,
63
+ page: true,
64
+ query: queryOf({ tab: TAB_VALUE, max_chars: intIn(200, 100_000), max_refs: intIn(1, 20_000) }),
65
+ },
66
+ { method: "POST", path: pagePath("navigate"), status: 200, body: true, page: true },
67
+ { method: "POST", path: pagePath("click"), status: 200, body: true, page: true },
68
+ { method: "POST", path: pagePath("type"), status: 200, body: true, page: true },
69
+ { method: "POST", path: pagePath("fill"), status: 200, body: true, page: true },
70
+ { method: "POST", path: pagePath("select"), status: 200, body: true, page: true },
71
+ { method: "POST", path: pagePath("key"), status: 200, body: true, page: true },
72
+ { method: "POST", path: pagePath("wait"), status: 200, body: true, page: true, readOnly: true },
73
+ {
74
+ method: "GET",
75
+ path: pagePath("screenshot"),
76
+ status: 200,
77
+ body: false,
78
+ page: true,
79
+ binary: true,
80
+ query: queryOf({ tab: TAB_VALUE, ref: REF_VALUE }),
81
+ },
82
+ {
83
+ method: "GET",
84
+ path: pagePath("text"),
85
+ status: 200,
86
+ body: false,
87
+ page: true,
88
+ query: queryOf({ tab: TAB_VALUE, max_chars: intIn(1, 100_000) }),
89
+ },
90
+ { method: "POST", path: pagePath("hover"), status: 200, body: true, page: true },
91
+ { method: "POST", path: pagePath("drag"), status: 200, body: true, page: true },
92
+ { method: "POST", path: pagePath("scroll"), status: 200, body: true, page: true },
93
+ { method: "POST", path: pagePath("upload"), status: 200, body: true, page: true },
94
+ {
95
+ method: "GET",
96
+ path: pagePath("downloads"),
97
+ status: 200,
98
+ body: false,
99
+ page: true,
100
+ query: queryOf({ tab: TAB_VALUE }),
101
+ },
102
+ { method: "POST", path: pagePath("downloads/save"), status: 200, body: true, page: true },
103
+ { method: "POST", path: pagePath("evaluate"), status: 200, body: true, page: true },
104
+ {
105
+ method: "POST",
106
+ path: pagePath("extract"),
107
+ status: 200,
108
+ body: true,
109
+ page: true,
110
+ readOnly: true,
111
+ },
112
+ {
113
+ method: "GET",
114
+ path: pagePath("dialogs"),
115
+ status: 200,
116
+ body: false,
117
+ page: true,
118
+ query: queryOf({ tab: TAB_VALUE }),
119
+ },
120
+ { method: "POST", path: pagePath("dialog"), status: 200, body: true, page: true },
121
+ { method: "POST", path: pagePath("console"), status: 200, body: true, page: true },
122
+ { method: "POST", path: pagePath("network"), status: 200, body: true, page: true },
123
+ // Hand-off to a person. The create route holds up to `wait_s`; the wait route resumes it.
124
+ {
125
+ method: "POST",
126
+ path: /^\/v1\/profiles\/[^/]+\/human$/,
127
+ status: 200,
128
+ body: true,
129
+ human: true,
130
+ },
131
+ {
132
+ method: "POST",
133
+ path: new RegExp(`^/v1/human/${HUMAN_ID}/wait$`),
134
+ status: 200,
135
+ body: true,
136
+ human: true,
137
+ readOnly: true,
138
+ },
139
+ { method: "GET", path: pagePath("tabs"), status: 200, body: false, page: true },
140
+ { method: "POST", path: pagePath("tabs"), status: 200, body: true, page: true },
141
+ ]);
142
+ export function matchLocalRoute(method, pathname) {
143
+ return LOCAL_ROUTES.find((route) => route.method === method && route.path.test(pathname));
144
+ }
145
+ /** Request-shape check shared by the transport: query string and body presence. */
146
+ export function localRequestAllowed(route, url, body, isObjectBody) {
147
+ if (route.query) {
148
+ if (url.search !== "" && !route.query(url.searchParams))
149
+ return false;
150
+ }
151
+ else if (url.search !== "")
152
+ return false;
153
+ return route.body ? isObjectBody(body.toString("utf8")) : body.length === 0;
154
+ }
155
+ /** Daemon page error codes and their fixed MCP failures. Only page routes consult this. */
156
+ const PAGE_CODES = Object.freeze({
157
+ "page.ref_stale": "ref_stale",
158
+ "profile.not_running": "not_running",
159
+ "page.unsupported_input": "unsupported_input",
160
+ "page.not_editable": "not_editable",
161
+ "page.select_failed": "select_failed",
162
+ "page.out_of_view": "out_of_view",
163
+ "page.focus_mismatch": "focus_mismatch",
164
+ "page.obscured": "obscured",
165
+ "page.tab_required": "tab_required",
166
+ "page.tab_hidden": "tab_hidden",
167
+ "page.destination_blocked": "destination_blocked",
168
+ "page.timeout": "page_timeout",
169
+ "page.no_history": "no_history",
170
+ "page.dialog_pending": "dialog_pending",
171
+ "page.no_dialog": "no_dialog",
172
+ "page.value_rejected": "value_rejected",
173
+ "page.download_not_found": "download_not_found",
174
+ "page.download_not_ready": "download_not_ready",
175
+ "page.save_exists": "save_exists",
176
+ "page.url_not_allowed": "url_not_allowed",
177
+ "page.human_pending": "page_human_pending",
178
+ "page.approval_stale": "approval_stale",
179
+ "page.approval_denied": "approval_denied",
180
+ "page.approval_unavailable": "approval_unavailable",
181
+ "page.approval_target_mismatch": "approval_target_mismatch",
182
+ "page.blocked_domain": "blocked_domain",
183
+ "page.blocked_frame": "blocked_frame",
184
+ "page.ref_required": "ref_required",
185
+ "page.frame_target": "frame_target",
186
+ "page.rules_unreadable": "rules_unreadable",
187
+ });
188
+ /** Hand-off error codes. Their codes are distinct from every page code, so any local route maps them. */
189
+ const HUMAN_CODES = Object.freeze({
190
+ "human.pending": "human_pending",
191
+ "human.headless": "human_headless",
192
+ "human.no_approver": "human_no_approver",
193
+ });
194
+ /** Closed mapping of daemon error codes; the daemon's message/details never cross. */
195
+ export function mapDaemonError(status, body, page = false) {
196
+ let code;
197
+ let reason;
198
+ try {
199
+ const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
200
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
201
+ code = parsed.error;
202
+ const details = parsed.details;
203
+ if (details !== null && typeof details === "object" && !Array.isArray(details))
204
+ reason = details.reason;
205
+ }
206
+ }
207
+ catch {
208
+ code = undefined;
209
+ }
210
+ // A navigation or an input action that timed out may have partly happened: the outcome is
211
+ // unknown. Only a wait that ran out changed nothing.
212
+ if (page && code === "page.timeout" && (reason === "navigation" || reason === "action"))
213
+ return "indeterminate";
214
+ if (code === "validation_failed")
215
+ return "invalid_request";
216
+ if (page && typeof code === "string" && Object.hasOwn(PAGE_CODES, code))
217
+ return PAGE_CODES[code];
218
+ if (typeof code === "string" && Object.hasOwn(HUMAN_CODES, code))
219
+ return HUMAN_CODES[code];
220
+ if (status === 403)
221
+ return "forbidden"; // any 403 without a page code of its own
222
+ if (code === "profile.ambiguous_name")
223
+ return "ambiguous_name";
224
+ if (code === "profile.running")
225
+ return "profile_running";
226
+ if (code === "profile.synced")
227
+ return "profile_synced";
228
+ // A 409 with an unparseable body stays `upstream`; only a coded conflict is reported as one.
229
+ return status === 409 && typeof code === "string" ? "conflict" : "upstream";
230
+ }
231
+ //# sourceMappingURL=local-routes.js.map
@@ -0,0 +1,3 @@
1
+ /** Classify libuv's raw st_mode, including Windows pipes whose Stats helpers return false. */
2
+ export declare function outputDescriptorKind(mode: unknown, terminal: boolean): "pipe" | "socket" | undefined;
3
+ //# sourceMappingURL=output-descriptor.d.ts.map
@@ -0,0 +1,19 @@
1
+ /** Classify libuv's raw st_mode, including Windows pipes whose Stats helpers return false. */
2
+ export function outputDescriptorKind(mode, terminal) {
3
+ if (terminal ||
4
+ typeof mode !== "number" ||
5
+ !Number.isInteger(mode) ||
6
+ mode < 0 ||
7
+ mode > 0xffff) {
8
+ return undefined;
9
+ }
10
+ // Use the portable st_mode bits, not fs.constants/Stats helpers that may omit these types
11
+ // on Windows. Native QA on Node 24.19/libuv 1.52.1 reports mode 4096 for FILE_TYPE_PIPE.
12
+ const type = mode & 0o170000; // S_IFMT; permission/special bits do not change the file type.
13
+ if (type === 0o010000)
14
+ return "pipe"; // S_IFIFO, also libuv's Windows pipe mapping.
15
+ if (type === 0o140000)
16
+ return "socket"; // S_IFSOCK.
17
+ return undefined;
18
+ }
19
+ //# sourceMappingURL=output-descriptor.js.map
@@ -0,0 +1,3 @@
1
+ /** Private, side-effect-free on import. The bootstrap or ESM child entry calls this once. */
2
+ export declare function runOutputWorker(): void;
3
+ //# sourceMappingURL=output-worker-body.d.ts.map
@@ -0,0 +1,77 @@
1
+ import { fstatSync, write } from "node:fs";
2
+ import { isatty } from "node:tty";
3
+ import { LIMITS } from "./limits.js";
4
+ import { outputDescriptorKind } from "./output-descriptor.js";
5
+ /** Private, side-effect-free on import. The bootstrap or ESM child entry calls this once. */
6
+ export function runOutputWorker() {
7
+ if (!process.connected || typeof process.send !== "function")
8
+ process.exit(1);
9
+ // An IPC disconnect must stop this process even if its OS stdout write is blocked. fs.write
10
+ // runs that potentially blocking work off this child's event loop; the parent can independently
11
+ // kill the entire child at its deadline. No worker-thread termination is relied upon.
12
+ process.on("disconnect", () => process.exit(0));
13
+ process.on("uncaughtException", () => process.exit(1));
14
+ process.on("unhandledRejection", () => process.exit(1));
15
+ function send(message) {
16
+ if (!process.connected || !process.send)
17
+ process.exit(1);
18
+ process.send(message, (error) => {
19
+ if (error)
20
+ process.exit(1);
21
+ });
22
+ }
23
+ let busy = false;
24
+ let lastId = 0;
25
+ process.on("message", (message) => {
26
+ if (!message || typeof message !== "object" || busy)
27
+ process.exit(1);
28
+ const value = message;
29
+ if (value.type !== "write" ||
30
+ !Number.isSafeInteger(value.id) ||
31
+ value.id <= lastId ||
32
+ !Buffer.isBuffer(value.bytes) ||
33
+ value.bytes.length > LIMITS.envelopeBytes)
34
+ process.exit(1);
35
+ const bytes = value.bytes;
36
+ const id = value.id;
37
+ lastId = id;
38
+ busy = true;
39
+ let offset = 0;
40
+ const attempt = () => {
41
+ write(1, bytes, offset, bytes.length - offset, null, (error, written) => {
42
+ if (error) {
43
+ // Inherited POSIX pipes may be nonblocking. Keep one bounded envelope and retry;
44
+ // Windows synchronous pipe writes remain interruptible by killing this whole process.
45
+ if (error.code === "EAGAIN" || error.code === "EWOULDBLOCK" || error.code === "EINTR") {
46
+ setTimeout(attempt, 1);
47
+ return;
48
+ }
49
+ process.exit(1);
50
+ }
51
+ offset += written;
52
+ if (offset < bytes.length) {
53
+ setTimeout(attempt, 1);
54
+ return;
55
+ }
56
+ busy = false;
57
+ send({ type: "ack", id });
58
+ });
59
+ };
60
+ attempt();
61
+ });
62
+ try {
63
+ // Inspect the inherited descriptor using raw libuv mode bits. On Windows a real pipe can
64
+ // report mode 4096 while BOTH Stats.isFIFO() and Stats.isSocket() return false.
65
+ const stat = fstatSync(1);
66
+ const descriptor = outputDescriptorKind(stat.mode, isatty(1));
67
+ if (descriptor === undefined) {
68
+ send({ type: "unsupported" });
69
+ }
70
+ else
71
+ send({ type: "ready", descriptor });
72
+ }
73
+ catch {
74
+ process.exit(1);
75
+ }
76
+ }
77
+ //# sourceMappingURL=output-worker-body.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=output-worker.d.ts.map
@@ -0,0 +1,4 @@
1
+ /** Private ESM child entrypoint. Never imports discovery/API code or receives a bearer/home. */
2
+ import { runOutputWorker } from "./output-worker-body.js";
3
+ runOutputWorker();
4
+ //# sourceMappingURL=output-worker.js.map
@@ -0,0 +1,39 @@
1
+ import { McpFailure, type FailureCode } from "./errors.js";
2
+ /** Internal product dependency, never populated from CLI flags, environment or MCP input. */
3
+ export interface OutputWorkerCommand {
4
+ readonly executable: string;
5
+ readonly args: readonly string[];
6
+ }
7
+ /** An owned, independently killable stdout writer. The parent never writes the inherited fd. */
8
+ export declare class OutputWriter {
9
+ private readonly fd;
10
+ private readonly failed;
11
+ private child;
12
+ private started;
13
+ private stopping;
14
+ private ready;
15
+ private failure;
16
+ private startupTimer;
17
+ private resolveReady;
18
+ private rejectReady;
19
+ private resolveReaped;
20
+ private readonly reaped;
21
+ private readonly queue;
22
+ private current;
23
+ private queuedBytes;
24
+ private sequence;
25
+ private descriptor;
26
+ private readonly command;
27
+ constructor(fd: number, failed: (code: FailureCode) => void, command?: OutputWorkerCommand);
28
+ /** Lifecycle observations for tests; neither is sent over MCP or included in diagnostics. */
29
+ get pid(): number | undefined;
30
+ get descriptorKind(): "pipe" | "socket" | undefined;
31
+ start(): Promise<void>;
32
+ write(text: string, callback: (error?: McpFailure) => void): void;
33
+ private pump;
34
+ private onMessage;
35
+ private fail;
36
+ /** No detachment/unref: await the owned ChildProcess close event, including on every failure. */
37
+ close(): Promise<void>;
38
+ }
39
+ //# sourceMappingURL=output-writer.d.ts.map
@@ -0,0 +1,199 @@
1
+ import { spawn } from "node:child_process";
2
+ import { isAbsolute } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { McpFailure } from "./errors.js";
5
+ import { LIMITS } from "./limits.js";
6
+ /** An owned, independently killable stdout writer. The parent never writes the inherited fd. */
7
+ export class OutputWriter {
8
+ fd;
9
+ failed;
10
+ child;
11
+ started = false;
12
+ stopping = false;
13
+ ready = false;
14
+ failure;
15
+ startupTimer;
16
+ resolveReady = () => { };
17
+ rejectReady = () => { };
18
+ resolveReaped;
19
+ reaped = new Promise((resolve) => {
20
+ this.resolveReaped = resolve;
21
+ });
22
+ queue = [];
23
+ current;
24
+ queuedBytes = 0;
25
+ sequence = 0;
26
+ descriptor;
27
+ command;
28
+ constructor(fd, failed, command) {
29
+ this.fd = fd;
30
+ this.failed = failed;
31
+ const executable = command?.executable ?? process.execPath;
32
+ const args = command
33
+ ? [...command.args]
34
+ : [fileURLToPath(new URL("./output-worker.js", import.meta.url))];
35
+ if (!isAbsolute(executable) ||
36
+ executable.includes("\0") ||
37
+ args.some((arg) => typeof arg !== "string" || arg.includes("\0")))
38
+ throw new McpFailure("output");
39
+ this.command = Object.freeze({ executable, args: Object.freeze(args) });
40
+ }
41
+ /** Lifecycle observations for tests; neither is sent over MCP or included in diagnostics. */
42
+ get pid() {
43
+ return this.child?.pid;
44
+ }
45
+ get descriptorKind() {
46
+ return this.descriptor;
47
+ }
48
+ async start() {
49
+ if (this.started || this.stopping)
50
+ throw new McpFailure("output");
51
+ this.started = true;
52
+ const ready = new Promise((resolve, reject) => {
53
+ this.resolveReady = resolve;
54
+ this.rejectReady = reject;
55
+ });
56
+ // Also cover cancellation during startup, before the caller resumes its await.
57
+ void ready.catch(() => { });
58
+ this.startupTimer = setTimeout(() => this.fail("output"), LIMITS.writerStartupMs);
59
+ try {
60
+ // Do not inherit NODE_OPTIONS, inspector flags, application credentials or home settings.
61
+ const env = {};
62
+ for (const key of ["SystemRoot", "WINDIR", "SystemDrive", "TEMP", "TMP"]) {
63
+ if (process.env[key] !== undefined)
64
+ env[key] = process.env[key];
65
+ }
66
+ this.child = spawn(this.command.executable, this.command.args, {
67
+ env,
68
+ stdio: ["ignore", this.fd, "ignore", "ipc"],
69
+ serialization: "advanced",
70
+ detached: false,
71
+ windowsHide: true,
72
+ });
73
+ this.child.on("message", this.onMessage);
74
+ this.child.on("error", () => this.fail("output"));
75
+ this.child.on("disconnect", () => {
76
+ if (!this.stopping)
77
+ this.fail("output");
78
+ });
79
+ this.child.on("close", () => {
80
+ if (!this.stopping)
81
+ this.fail("output");
82
+ this.resolveReaped();
83
+ });
84
+ }
85
+ catch {
86
+ this.fail("output");
87
+ this.resolveReaped();
88
+ }
89
+ await ready;
90
+ }
91
+ write(text, callback) {
92
+ if (this.stopping || !this.started) {
93
+ callback(this.failure ?? new McpFailure("output"));
94
+ return;
95
+ }
96
+ const size = Buffer.byteLength(text);
97
+ if (size > LIMITS.envelopeBytes ||
98
+ this.queuedBytes + size > LIMITS.outputBytes ||
99
+ this.queue.length >= LIMITS.outputWrites ||
100
+ this.sequence === Number.MAX_SAFE_INTEGER) {
101
+ this.fail("backpressure");
102
+ callback(new McpFailure("backpressure"));
103
+ return;
104
+ }
105
+ const entry = {
106
+ id: ++this.sequence,
107
+ bytes: Buffer.from(text),
108
+ timer: setTimeout(() => this.fail("backpressure"), LIMITS.outputMs),
109
+ callback,
110
+ };
111
+ this.queuedBytes += size;
112
+ this.queue.push(entry);
113
+ this.pump();
114
+ }
115
+ pump() {
116
+ if (!this.ready || this.stopping || this.current || !this.queue.length)
117
+ return;
118
+ const entry = this.queue[0];
119
+ this.current = entry;
120
+ try {
121
+ // Exactly one envelope is in IPC/the worker at a time. A send callback only acknowledges
122
+ // IPC delivery; only the child's explicit ack acknowledges the actual stdout write.
123
+ this.child.send({ type: "write", id: entry.id, bytes: entry.bytes }, (error) => {
124
+ if (error && !this.stopping && this.current === entry)
125
+ this.fail("output");
126
+ });
127
+ }
128
+ catch {
129
+ this.fail("output");
130
+ }
131
+ }
132
+ onMessage = (message) => {
133
+ if (this.stopping)
134
+ return;
135
+ if (!message || typeof message !== "object")
136
+ return this.fail("output");
137
+ const value = message;
138
+ if (value.type === "unsupported" && !this.ready)
139
+ return this.fail("stdio");
140
+ if (value.type === "ready" &&
141
+ !this.ready &&
142
+ (value.descriptor === "pipe" || value.descriptor === "socket")) {
143
+ this.ready = true;
144
+ this.descriptor = value.descriptor;
145
+ clearTimeout(this.startupTimer);
146
+ this.resolveReady();
147
+ this.pump();
148
+ }
149
+ else if (value.type === "ack" && this.current && value.id === this.current.id) {
150
+ const entry = this.current;
151
+ this.current = undefined;
152
+ this.queue.shift();
153
+ this.queuedBytes -= entry.bytes.length;
154
+ clearTimeout(entry.timer);
155
+ entry.callback();
156
+ this.pump();
157
+ }
158
+ else
159
+ this.fail("output");
160
+ };
161
+ fail(code) {
162
+ if (this.stopping)
163
+ return;
164
+ this.failure = new McpFailure(code);
165
+ this.rejectReady(this.failure);
166
+ // Notify the transport first, so HTTP/ping cancellation is immediate, not delayed by reaping.
167
+ try {
168
+ this.failed(code);
169
+ }
170
+ finally {
171
+ void this.close();
172
+ }
173
+ }
174
+ /** No detachment/unref: await the owned ChildProcess close event, including on every failure. */
175
+ async close() {
176
+ if (!this.stopping) {
177
+ this.stopping = true;
178
+ clearTimeout(this.startupTimer);
179
+ const error = this.failure ?? new McpFailure("cancelled");
180
+ this.rejectReady(error);
181
+ this.current = undefined;
182
+ this.queuedBytes = 0;
183
+ for (const entry of this.queue.splice(0)) {
184
+ clearTimeout(entry.timer);
185
+ entry.callback(error);
186
+ }
187
+ if (this.child) {
188
+ if (this.child.exitCode === null && this.child.signalCode === null) {
189
+ // Node uses TerminateProcess for SIGKILL on Windows. Only this owned child is targeted.
190
+ this.child.kill("SIGKILL");
191
+ }
192
+ }
193
+ else
194
+ this.resolveReaped();
195
+ }
196
+ await this.reaped;
197
+ }
198
+ }
199
+ //# sourceMappingURL=output-writer.js.map
@@ -0,0 +1,4 @@
1
+ import type { Server } from "@modelcontextprotocol/server";
2
+ /** Standard MCP ping is legal during initialization. One in flight, with no progress extension. Legacy era only. */
3
+ export declare function watchPeer(server: Server, lifetime: AbortSignal, failed: () => void): () => void;
4
+ //# sourceMappingURL=peer-watchdog.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { McpFailure } from "./errors.js";
2
+ import { LIMITS } from "./limits.js";
3
+ /** Standard MCP ping is legal during initialization. One in flight, with no progress extension. Legacy era only. */
4
+ export function watchPeer(server, lifetime, failed) {
5
+ let current;
6
+ let stopped = false;
7
+ const stop = () => {
8
+ if (stopped)
9
+ return;
10
+ stopped = true;
11
+ clearInterval(timer);
12
+ lifetime.removeEventListener("abort", stop);
13
+ current?.abort(new McpFailure("cancelled"));
14
+ };
15
+ const ping = async () => {
16
+ if (stopped || current)
17
+ return;
18
+ const controller = new AbortController();
19
+ current = controller;
20
+ try {
21
+ // Server.ping() has no RequestOptions parameter. This is the same SDK ping request, with
22
+ // the contract's timeout and a fresh, disposable abort signal. Legacy (initialize)
23
+ // connections only: 2026-07-28 removed ping and server-to-client requests.
24
+ await server.request({ method: "ping" }, {
25
+ timeout: LIMITS.pingResponseMs,
26
+ maxTotalTimeout: LIMITS.pingResponseMs,
27
+ resetTimeoutOnProgress: false,
28
+ signal: controller.signal,
29
+ });
30
+ }
31
+ catch {
32
+ if (!stopped) {
33
+ current = undefined; // The request has settled; do not cancel it a second time.
34
+ stop();
35
+ failed();
36
+ }
37
+ }
38
+ finally {
39
+ if (current === controller)
40
+ current = undefined;
41
+ }
42
+ };
43
+ const tick = () => {
44
+ void ping().catch(() => {
45
+ if (!stopped)
46
+ failed();
47
+ });
48
+ };
49
+ const timer = setInterval(tick, LIMITS.pingIntervalMs);
50
+ lifetime.addEventListener("abort", stop, { once: true });
51
+ if (lifetime.aborted)
52
+ stop();
53
+ return stop;
54
+ }
55
+ //# sourceMappingURL=peer-watchdog.js.map
@@ -0,0 +1,28 @@
1
+ import { Server, type Tool } from "@modelcontextprotocol/server";
2
+ import type { Ant0Client } from "./api/index.js";
3
+ import type { CallPermits } from "./call-permits.js";
4
+ import type { KeyGrant } from "./key-contract.js";
5
+ export declare const MCP_SERVER_VERSION: string;
6
+ export interface ServerParts {
7
+ client: Ant0Client;
8
+ /** The advertised tools. Fixed for the life of the process (credential-derived). */
9
+ tools: Tool[];
10
+ grant: KeyGrant | undefined;
11
+ home: string;
12
+ permits: CallPermits;
13
+ /** Aborts every in-flight call when the whole adapter stops. */
14
+ lifetime: AbortSignal;
15
+ /**
16
+ * Narrows the tools a single request may see and call (HTTP token scopes). Absent means
17
+ * `tools` unchanged. It can only remove tools; the key grant check in `callTool` still applies.
18
+ */
19
+ allowed?: ReadonlySet<string>;
20
+ }
21
+ /**
22
+ * One low-level MCP server instance. Instances are cheap and share nothing mutable besides the
23
+ * parts above, so a serving entry may create several per connection (discover probe, then
24
+ * initialize) or one per HTTP request. Keeping the low-level API lets all validation and error
25
+ * text stay behind our boundary.
26
+ */
27
+ export declare function buildServer(parts: ServerParts): Server;
28
+ //# sourceMappingURL=server.d.ts.map