@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,167 @@
1
+ import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, readdirSync, renameSync, unlinkSync, writeSync, } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { McpFailure } from "./errors.js";
5
+ import { LIMITS } from "./limits.js";
6
+ export const EXPORT_TTL_HOURS = 24;
7
+ const NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}-\d{8}T\d{6}Z-[0-9a-f]{4}\.(?:json|txt|png)(?:\.tmp)?$/;
8
+ /** `<ANT0_HOME>/exports/cookies`. */
9
+ export function cookieExportDir(home) {
10
+ return join(home, "exports", "cookies");
11
+ }
12
+ /** `<ANT0_HOME>/exports/screenshots`. */
13
+ export function screenshotExportDir(home) {
14
+ return join(home, "exports", "screenshots");
15
+ }
16
+ /** `<ANT0_HOME>/imports/cookies`: the only place `ant0_cookies_import` reads files from. */
17
+ export function cookieImportDir(home) {
18
+ return join(home, "imports", "cookies");
19
+ }
20
+ /** Create one of our private leaf directories (0700) and refuse a symlink or non-directory. */
21
+ function ensurePrivateDir(dir) {
22
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ const stat = lstatSync(dir);
24
+ if (!stat.isDirectory() || stat.isSymbolicLink())
25
+ throw new McpFailure("configuration");
26
+ chmodSync(dir, 0o700); // our own leaf directory only
27
+ }
28
+ function timestamp(now) {
29
+ return now
30
+ .toISOString()
31
+ .replace(/\.\d+Z$/, "Z")
32
+ .replace(/[-:]/g, "");
33
+ }
34
+ /** Delete our own files older than the TTL. Regular files with our name pattern only; best effort. */
35
+ export function sweepExports(dir, now = Date.now()) {
36
+ let names;
37
+ try {
38
+ names = readdirSync(dir);
39
+ }
40
+ catch {
41
+ return;
42
+ }
43
+ for (const name of names) {
44
+ if (!NAME.test(name))
45
+ continue;
46
+ try {
47
+ const path = join(dir, name);
48
+ const stat = lstatSync(path); // never follows a symlink
49
+ if (stat.isFile() && now - stat.mtimeMs > EXPORT_TTL_HOURS * 3_600_000)
50
+ unlinkSync(path);
51
+ }
52
+ catch {
53
+ /* ignore */
54
+ }
55
+ }
56
+ }
57
+ /**
58
+ * Write one export file and return its absolute path. The leaf directory is mode 0700 and the
59
+ * file 0600 (written under a temp name with flag "wx", then renamed in the same directory). On
60
+ * Windows the mode bits are ignored and the user-profile ACL inheritance protects the folder.
61
+ * Failures carry no cookie data.
62
+ */
63
+ export function writeCookieExport(home, profileId, extension, data, now = new Date(), test = {}) {
64
+ return writeExport(cookieExportDir(resolve(home)), profileId, extension, data, now, test);
65
+ }
66
+ /** Write one screenshot (PNG bytes) with the same guarantees as a cookie export. */
67
+ export function writeScreenshotExport(home, profileId, png, now = new Date(), test = {}) {
68
+ return writeExport(screenshotExportDir(resolve(home)), profileId, "png", png, now, test);
69
+ }
70
+ function writeExport(dir, profileId, extension, data, now, test) {
71
+ try {
72
+ ensurePrivateDir(dir);
73
+ sweepExports(dir, now.getTime());
74
+ const name = `${profileId}-${timestamp(now)}-${test.suffix ?? randomBytes(2).toString("hex")}.${extension}`;
75
+ const final = join(dir, name);
76
+ const temp = `${final}.tmp`;
77
+ const fd = openSync(temp, "wx", 0o600);
78
+ try {
79
+ const bytes = typeof data === "string" ? Buffer.from(data, "utf8") : data;
80
+ let written = 0;
81
+ while (written < bytes.length)
82
+ written += writeSync(fd, bytes, written);
83
+ }
84
+ catch (error) {
85
+ closeSync(fd);
86
+ try {
87
+ unlinkSync(temp);
88
+ }
89
+ catch {
90
+ /* ignore */
91
+ }
92
+ throw error;
93
+ }
94
+ closeSync(fd);
95
+ test.beforeRename?.(temp);
96
+ renameSync(temp, final);
97
+ return final;
98
+ }
99
+ catch (error) {
100
+ throw error instanceof McpFailure ? error : new McpFailure("internal");
101
+ }
102
+ }
103
+ /** Sweep now and then hourly (unref'd, so it never keeps the process alive). Returns the stopper. */
104
+ export const SWEEP_INTERVAL_MS = 3_600_000;
105
+ export function startExportSweeper(home) {
106
+ const dirs = [cookieExportDir(resolve(home)), screenshotExportDir(resolve(home))];
107
+ const sweep = () => {
108
+ for (const dir of dirs) {
109
+ try {
110
+ sweepExports(dir);
111
+ }
112
+ catch {
113
+ /* ignore */
114
+ }
115
+ }
116
+ };
117
+ sweep();
118
+ const timer = setInterval(sweep, SWEEP_INTERVAL_MS);
119
+ timer.unref();
120
+ return () => clearInterval(timer);
121
+ }
122
+ /**
123
+ * Read one cookie file from `<ANT0_HOME>/imports/cookies` (UTF-8, at most one request body).
124
+ * The directory is created 0700 if missing. Every failure (missing, unreadable, outside the
125
+ * directory, symlink, directory, FIFO, too large, swapped, bad UTF-8) is the same `arguments`
126
+ * failure, so the tool is not an existence or content oracle for other paths.
127
+ */
128
+ export function readImportFile(home, path, test = {}) {
129
+ const fail = () => new McpFailure("arguments");
130
+ if (!isAbsolute(path) || path.includes("\0"))
131
+ throw fail();
132
+ let fd;
133
+ try {
134
+ const dir = cookieImportDir(resolve(home));
135
+ ensurePrivateDir(dir);
136
+ const inside = relative(realpathSync(dir), realpathSync(path));
137
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside))
138
+ throw fail();
139
+ const stat = lstatSync(path);
140
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > LIMITS.bodyBytes)
141
+ throw fail();
142
+ test.afterLstat?.(path);
143
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
144
+ const opened = fstatSync(fd);
145
+ if (!opened.isFile() || opened.ino !== stat.ino || opened.dev !== stat.dev)
146
+ throw fail();
147
+ const buffer = Buffer.alloc(LIMITS.bodyBytes + 1);
148
+ let size = 0;
149
+ while (size < buffer.length) {
150
+ const count = readSync(fd, buffer, size, buffer.length - size, null);
151
+ if (count === 0)
152
+ break;
153
+ size += count;
154
+ }
155
+ if (size > LIMITS.bodyBytes)
156
+ throw fail();
157
+ return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size));
158
+ }
159
+ catch {
160
+ throw fail();
161
+ }
162
+ finally {
163
+ if (fd !== undefined)
164
+ closeSync(fd);
165
+ }
166
+ }
167
+ //# sourceMappingURL=export-files.js.map
@@ -0,0 +1,5 @@
1
+ import { type Ant0Client } from "./api/index.js";
2
+ import type { Connection } from "./connection.js";
3
+ import { type KeyGrant } from "./key-contract.js";
4
+ export declare function resolveGrant(connection: Connection, client: Ant0Client, consumer: "api" | "mcp", signal?: AbortSignal): Promise<KeyGrant | undefined>;
5
+ //# sourceMappingURL=grant.d.ts.map
package/dist/grant.js ADDED
@@ -0,0 +1,11 @@
1
+ import { unwrap } from "./api/index.js";
2
+ import { fileGrant, grantFromStatus } from "./key-contract.js";
3
+ export async function resolveGrant(connection, client, consumer, signal) {
4
+ if (connection.credential)
5
+ return fileGrant(connection.credential.value);
6
+ if (!connection.apiKey)
7
+ return undefined;
8
+ const status = unwrap(await client.GET("/v1/automation/status", signal ? { signal } : {}));
9
+ return grantFromStatus(status, connection.token, consumer).grant;
10
+ }
11
+ //# sourceMappingURL=grant.js.map
@@ -0,0 +1,38 @@
1
+ import type { Readable } from "node:stream";
2
+ import { type DiscoveryOptions } from "./connection.js";
3
+ import { McpFailure } from "./errors.js";
4
+ /** `ant0_mcp_v1_` then 32 random bytes as unpadded base64url (43 characters). */
5
+ export declare const DESKTOP_TOKEN_PATTERN: RegExp;
6
+ /** The listen port is taken. Fixed text only; the caller reports it and does not retry. */
7
+ export declare class PortInUseFailure extends McpFailure {
8
+ readonly reason: "port_in_use";
9
+ constructor();
10
+ }
11
+ export interface DesktopLocalOptions extends Pick<DiscoveryOptions, "home" | "env"> {
12
+ /** The bearer token clients must present. Must match DESKTOP_TOKEN_PATTERN. */
13
+ token: string;
14
+ /** 1024-65535, never the daemon's port. 0 (a free port) is for programmatic use and tests. */
15
+ listenPort: number;
16
+ /** Largest accepted request body in bytes. Default 1 MiB. */
17
+ maxBodyBytes?: number;
18
+ signal?: AbortSignal;
19
+ }
20
+ export interface DesktopLocalHandle {
21
+ readonly url: string;
22
+ readonly port: number;
23
+ close(): Promise<void>;
24
+ }
25
+ /** Constant-time bearer check: both sides are hashed first, so lengths never leak. */
26
+ export declare function bearerMatches(expected: string, presented: string): boolean;
27
+ /** Serve the desktop-local endpoint on 127.0.0.1. See the file comment for the contract. */
28
+ export declare function serveDesktopLocalHttp(options: DesktopLocalOptions): Promise<DesktopLocalHandle>;
29
+ /**
30
+ * Reads the token line from `stdin`, serves, and resolves once the server is closed: on stdin
31
+ * EOF/close/error (the parent is gone), or when `signal` aborts. The token line must end in a
32
+ * newline and is at most 256 bytes; anything after it is discarded.
33
+ */
34
+ export declare function serveDesktopLocalFromStdin(stdin: Readable, options: Omit<DesktopLocalOptions, "token"> & {
35
+ /** How long to wait for the token line. Default 10 s; no token means a fixed refusal. */
36
+ tokenDeadlineMs?: number;
37
+ }, onListening?: (handle: DesktopLocalHandle) => void): Promise<void>;
38
+ //# sourceMappingURL=http-local.d.ts.map
@@ -0,0 +1,324 @@
1
+ /**
2
+ * "Desktop-local" Streamable HTTP mode: a separate mode from the OAuth resource server in
3
+ * `http.ts`, started by the Ant0 desktop app as a supervised child:
4
+ *
5
+ * ant0 mcp serve --http --port <N> --token-stdin
6
+ *
7
+ * Contract with the parent (the Rust shell):
8
+ * - It writes the MCP bearer token plus a newline to this process's stdin and then KEEPS stdin
9
+ * open. The token is never passed in argv, env or a query string.
10
+ * - Stdin EOF (or close) means "the parent is gone": the server closes and the process exits.
11
+ * - Port in use gives a fixed failure (PortInUseFailure) and no other port is tried.
12
+ *
13
+ * Auth is one static bearer (`ant0_mcp_v1_` + 256 random bits, base64url), compared in constant
14
+ * time. The adapter then talks to ant0d with the LOCAL daemon token, so every local tool
15
+ * (identity and page tools included) is listed. That lift exists only here: the OAuth mode in
16
+ * `http.ts` still refuses the local token.
17
+ *
18
+ * Network rules: 127.0.0.1 only (no host setting); the Host header must be exactly
19
+ * `127.0.0.1:<port>` or `localhost:<port>`; any Origin header at all is refused with 403. Host
20
+ * and Origin are checked before auth on every route, including 404 and 405. No CORS headers,
21
+ * no OAuth metadata route (404), and a 401 challenge without `resource_metadata`.
22
+ */
23
+ import { createHash, timingSafeEqual } from "node:crypto";
24
+ import { createServer } from "node:http";
25
+ import { createMcpHandler } from "@modelcontextprotocol/server";
26
+ import { resolveHome } from "./api/index.js";
27
+ import { CallPermits } from "./call-permits.js";
28
+ import { discoverConnection, keyMode } from "./connection.js";
29
+ import { daemonClient } from "./daemon.js";
30
+ import { McpFailure, safeFailure } from "./errors.js";
31
+ import { startExportSweeper } from "./export-files.js";
32
+ import { MAX_TOKEN_CHARS, boundedBody, sanitizeResponse, webHeaders } from "./http.js";
33
+ import { buildServer } from "./server.js";
34
+ import { toolsForCredential } from "./tools.js";
35
+ /** `ant0_mcp_v1_` then 32 random bytes as unpadded base64url (43 characters). */
36
+ export const DESKTOP_TOKEN_PATTERN = /^ant0_mcp_v1_[A-Za-z0-9_-]{43}$/;
37
+ const ENDPOINT_PATH = "/mcp";
38
+ const HOST = "127.0.0.1";
39
+ const TOKEN_LINE_MAX = 256;
40
+ const TOKEN_DEADLINE_MS = 10_000;
41
+ /** The listen port is taken. Fixed text only; the caller reports it and does not retry. */
42
+ export class PortInUseFailure extends McpFailure {
43
+ reason = "port_in_use";
44
+ constructor() {
45
+ super("configuration");
46
+ }
47
+ }
48
+ function refuse(reason) {
49
+ process.stderr.write(`ant0-mcp: ${reason}\n`);
50
+ throw new McpFailure("configuration");
51
+ }
52
+ const digest = (value) => createHash("sha256").update(value, "utf8").digest();
53
+ /** Constant-time bearer check: both sides are hashed first, so lengths never leak. */
54
+ export function bearerMatches(expected, presented) {
55
+ if (presented.length > MAX_TOKEN_CHARS)
56
+ return false;
57
+ return timingSafeEqual(digest(expected), digest(presented));
58
+ }
59
+ /** The bearer from a header value, or undefined unless it is exactly `Bearer <token>`. */
60
+ function bearerFrom(header) {
61
+ if (typeof header !== "string" || header.length > MAX_TOKEN_CHARS + 7)
62
+ return undefined;
63
+ const match = /^Bearer ([!-~]+)$/i.exec(header);
64
+ return match?.[1];
65
+ }
66
+ /** Serve the desktop-local endpoint on 127.0.0.1. See the file comment for the contract. */
67
+ export async function serveDesktopLocalHttp(options) {
68
+ if (!DESKTOP_TOKEN_PATTERN.test(options.token))
69
+ refuse("the MCP token has an invalid format");
70
+ const { listenPort } = options;
71
+ if (!Number.isInteger(listenPort) ||
72
+ (listenPort !== 0 && (listenPort < 1024 || listenPort > 65535)))
73
+ refuse("the MCP port must be 1024-65535");
74
+ const maxBody = options.maxBodyBytes ?? 1024 * 1024;
75
+ const expected = options.token;
76
+ const lifetime = new AbortController();
77
+ const permits = new CallPermits();
78
+ let stopSweeper;
79
+ let server;
80
+ let handler;
81
+ let boundPort = -1;
82
+ const closeAll = async () => {
83
+ lifetime.abort();
84
+ stopSweeper?.();
85
+ await handler?.close().catch(() => { });
86
+ if (server?.listening)
87
+ await new Promise((resolve) => {
88
+ server.close(() => resolve());
89
+ server.closeAllConnections();
90
+ });
91
+ };
92
+ try {
93
+ // Never pass a port, credential file or API key: this mode always uses the local token.
94
+ const connection = discoverConnection({
95
+ ...(options.home !== undefined ? { home: options.home } : {}),
96
+ ...(options.env !== undefined ? { env: options.env } : {}),
97
+ });
98
+ if (keyMode(connection))
99
+ refuse("desktop-local mode uses the local daemon token; unset ANT0_API_KEY");
100
+ if (listenPort !== 0 && new URL(connection.origin).port === String(listenPort))
101
+ refuse("the MCP port must not be the daemon's port");
102
+ const home = resolveHome({
103
+ ...(options.home !== undefined ? { home: options.home } : {}),
104
+ env: options.env ?? process.env,
105
+ });
106
+ stopSweeper = startExportSweeper(home);
107
+ const client = daemonClient(connection, lifetime.signal);
108
+ const tools = toolsForCredential(undefined);
109
+ handler = createMcpHandler(() => buildServer({
110
+ client,
111
+ tools,
112
+ grant: undefined,
113
+ home,
114
+ permits,
115
+ lifetime: lifetime.signal,
116
+ }), { maxRequestBodySize: maxBody, legacy: "stateless" });
117
+ const mcp = handler;
118
+ server = createServer({
119
+ maxHeaderSize: 16 * 1024,
120
+ requestTimeout: 30_000,
121
+ headersTimeout: 10_000,
122
+ keepAliveTimeout: 5_000,
123
+ }, (req, res) => {
124
+ void (async () => {
125
+ const send = async (response) => {
126
+ res.statusCode = response.status;
127
+ response.headers.forEach((value, name) => res.setHeader(name, value));
128
+ res.setHeader("Cache-Control", "no-store");
129
+ res.setHeader("X-Content-Type-Options", "nosniff");
130
+ if (!response.body)
131
+ return void res.end();
132
+ const reader = response.body.getReader();
133
+ res.on("close", () => void reader.cancel().catch(() => { }));
134
+ try {
135
+ for (;;) {
136
+ const { done, value } = await reader.read();
137
+ if (done)
138
+ break;
139
+ if (!res.write(value))
140
+ await new Promise((resolve) => res.once("drain", resolve));
141
+ }
142
+ }
143
+ catch {
144
+ // The peer went away; the SDK cancels the exchange from the aborted signal.
145
+ }
146
+ res.end();
147
+ };
148
+ const status = (code, headers = {}) => send(new Response(null, { status: code, headers }));
149
+ // DNS-rebinding and cross-site defences first, on every route and method.
150
+ const authority = req.headers.host?.toLowerCase();
151
+ if (authority !== `127.0.0.1:${boundPort}` && authority !== `localhost:${boundPort}`)
152
+ return void (await status(403));
153
+ if (req.headers.origin !== undefined)
154
+ return void (await status(403));
155
+ let url;
156
+ try {
157
+ url = new URL(req.url ?? "/", `http://127.0.0.1:${boundPort}`);
158
+ }
159
+ catch {
160
+ return void (await status(400));
161
+ }
162
+ if (url.pathname !== ENDPOINT_PATH)
163
+ return void (await status(404));
164
+ // The 2026-07-28 endpoint is POST only: no GET stream, no DELETE session.
165
+ if (req.method !== "POST")
166
+ return void (await status(405, { Allow: "POST" }));
167
+ const presented = bearerFrom(req.headers.authorization);
168
+ if (presented === undefined || !bearerMatches(expected, presented))
169
+ return void (await status(401, { "WWW-Authenticate": 'Bearer error="invalid_token"' }));
170
+ const body = await boundedBody(req, maxBody);
171
+ if (body === undefined)
172
+ return void (await status(413));
173
+ let peeked;
174
+ try {
175
+ const parsed = JSON.parse(body.toString("utf8"));
176
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
177
+ peeked = parsed;
178
+ }
179
+ catch {
180
+ // Not JSON: the SDK answers it.
181
+ }
182
+ // No listChanged capability is advertised; a listen stream would only pin a slot.
183
+ if (peeked?.method === "subscriptions/listen")
184
+ return void (await send(Response.json({
185
+ jsonrpc: "2.0",
186
+ id: typeof peeked.id === "string" || typeof peeked.id === "number"
187
+ ? peeked.id
188
+ : null,
189
+ error: { code: -32601, message: "MCP request rejected" },
190
+ }, { status: 200 })));
191
+ const abort = new AbortController();
192
+ res.on("close", () => abort.abort());
193
+ const headers = webHeaders(req);
194
+ // No token passthrough: the bearer is not visible to the MCP layer's request.
195
+ headers.delete("authorization");
196
+ // Fixed base origin plus path and query only: an absolute-form request target
197
+ // (POST http://evil.test/mcp) can never change the URL the SDK sees.
198
+ const request = new Request(`http://${HOST}:${boundPort}${url.pathname}${url.search}`, {
199
+ method: "POST",
200
+ headers,
201
+ body: new Uint8Array(body),
202
+ signal: abort.signal,
203
+ });
204
+ let response;
205
+ try {
206
+ response = await mcp.fetch(request, {
207
+ authInfo: {
208
+ token: "",
209
+ clientId: "desktop-local",
210
+ scopes: ["ant0.read", "ant0.run"],
211
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
212
+ },
213
+ });
214
+ }
215
+ catch {
216
+ response = Response.json({
217
+ jsonrpc: "2.0",
218
+ id: null,
219
+ error: { code: -32603, message: "MCP request rejected" },
220
+ }, { status: 500 });
221
+ }
222
+ await send(await sanitizeResponse(response));
223
+ })().catch(() => {
224
+ if (!res.headersSent)
225
+ res.statusCode = 500;
226
+ res.end();
227
+ });
228
+ });
229
+ server.maxConnections = 64;
230
+ await new Promise((resolve, reject) => {
231
+ server.once("error", reject);
232
+ // No `exclusive: false`, no host choice and no port fallback.
233
+ server.listen(listenPort, HOST, () => resolve());
234
+ }).catch((error) => {
235
+ if (error?.code === "EADDRINUSE")
236
+ throw new PortInUseFailure();
237
+ throw error;
238
+ });
239
+ boundPort = server.address().port;
240
+ if (listenPort === 0 && String(boundPort) === new URL(connection.origin).port)
241
+ refuse("the MCP port must not be the daemon's port");
242
+ options.signal?.addEventListener("abort", () => void closeAll(), { once: true });
243
+ if (options.signal?.aborted)
244
+ void closeAll();
245
+ return {
246
+ url: `http://${HOST}:${boundPort}${ENDPOINT_PATH}`,
247
+ port: boundPort,
248
+ close: closeAll,
249
+ };
250
+ }
251
+ catch (error) {
252
+ await closeAll();
253
+ throw error instanceof McpFailure ? error : safeFailure(error);
254
+ }
255
+ }
256
+ /**
257
+ * Reads the token line from `stdin`, serves, and resolves once the server is closed: on stdin
258
+ * EOF/close/error (the parent is gone), or when `signal` aborts. The token line must end in a
259
+ * newline and is at most 256 bytes; anything after it is discarded.
260
+ */
261
+ export async function serveDesktopLocalFromStdin(stdin, options, onListening) {
262
+ let ended = false;
263
+ const endedPromise = new Promise((resolve) => {
264
+ const done = () => {
265
+ ended = true;
266
+ resolve();
267
+ };
268
+ stdin.once("end", done);
269
+ stdin.once("close", done);
270
+ stdin.once("error", done);
271
+ });
272
+ const { tokenDeadlineMs = TOKEN_DEADLINE_MS, ...serveOptions } = options;
273
+ const token = await new Promise((resolve) => {
274
+ let text = "";
275
+ const timer = setTimeout(() => onStop(), tokenDeadlineMs);
276
+ const onData = (chunk) => {
277
+ text += typeof chunk === "string" ? chunk : chunk.toString("latin1");
278
+ const nl = text.indexOf("\n");
279
+ if (nl !== -1 || text.length > TOKEN_LINE_MAX) {
280
+ cleanup();
281
+ resolve(nl !== -1 && nl <= TOKEN_LINE_MAX ? text.slice(0, nl).replace(/\r$/, "") : undefined);
282
+ }
283
+ };
284
+ const onStop = () => {
285
+ cleanup();
286
+ resolve(undefined);
287
+ };
288
+ const cleanup = () => {
289
+ clearTimeout(timer);
290
+ stdin.off("data", onData);
291
+ stdin.off("end", onStop);
292
+ stdin.off("close", onStop);
293
+ stdin.off("error", onStop);
294
+ };
295
+ stdin.on("data", onData);
296
+ stdin.once("end", onStop);
297
+ stdin.once("close", onStop);
298
+ stdin.once("error", onStop);
299
+ });
300
+ const drain = () => { };
301
+ try {
302
+ if (token === undefined)
303
+ refuse("the MCP token was not received on stdin");
304
+ // Keep draining so EOF is observed, but never keep anything after the token line.
305
+ stdin.on("data", drain);
306
+ if (ended)
307
+ refuse("stdin closed before the server started");
308
+ const handle = await serveDesktopLocalHttp({ ...serveOptions, token });
309
+ onListening?.(handle);
310
+ const aborted = new Promise((resolve) => {
311
+ if (serveOptions.signal?.aborted)
312
+ return resolve();
313
+ serveOptions.signal?.addEventListener("abort", () => resolve(), { once: true });
314
+ });
315
+ await Promise.race([endedPromise, aborted]);
316
+ await handle.close();
317
+ }
318
+ finally {
319
+ // A failed start must not leave an open stdin keeping the process alive.
320
+ stdin.off("data", drain);
321
+ stdin.pause();
322
+ }
323
+ }
324
+ //# sourceMappingURL=http-local.js.map
package/dist/http.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { type IncomingMessage } from "node:http";
2
+ import { type DiscoveryOptions } from "./connection.js";
3
+ /** OAuth scopes this resource server understands. Nothing else widens or changes the tool set. */
4
+ export declare const HTTP_SCOPE_READ = "ant0.read";
5
+ export declare const HTTP_SCOPE_RUN = "ant0.run";
6
+ export declare const HTTP_SCOPES: readonly string[];
7
+ /**
8
+ * The tools one token scope may reach, before intersecting with the key's own grant:
9
+ * `ant0.read` is every key read tool (status, licence, profiles, sessions, proxies) and
10
+ * `ant0.run` is profile_run and profile_stop. No scope reaches a local-only tool.
11
+ */
12
+ export declare function toolsForHttpScope(scope: string): readonly string[];
13
+ export interface AuthorizationServer {
14
+ /** The `iss` a token must carry, and the value listed in the protected resource metadata. */
15
+ issuer: string;
16
+ /** Where the issuer's signing keys (a JWKS) are fetched. https, or loopback for local tests. */
17
+ jwksUrl: string;
18
+ }
19
+ export interface HttpOptions extends DiscoveryOptions {
20
+ /** Listen address. Default 127.0.0.1; anything else needs `allowNonLoopback`. */
21
+ host?: string;
22
+ /** Listen port. Default 27180; 0 picks a free port (programmatic use only). */
23
+ listenPort?: number;
24
+ allowNonLoopback?: boolean;
25
+ /**
26
+ * The canonical URL of this MCP endpoint (RFC 8707 resource). A token's audience must equal
27
+ * it. Its path is the endpoint path. https, or http only for a loopback host.
28
+ */
29
+ resource: string;
30
+ authorizationServers: readonly AuthorizationServer[];
31
+ /**
32
+ * Full origins (scheme, host and port, e.g. `https://app.example.test:8443`) allowed to call
33
+ * from browser or extension contexts. Default none. Entries are compared whole; a bare
34
+ * hostname is refused at start.
35
+ */
36
+ allowedOrigins?: readonly string[];
37
+ /** Largest accepted request body in bytes. Default 1 MiB. */
38
+ maxBodyBytes?: number;
39
+ signal?: AbortSignal;
40
+ }
41
+ export interface HttpServerHandle {
42
+ readonly url: string;
43
+ readonly port: number;
44
+ close(): Promise<void>;
45
+ }
46
+ export declare const MAX_TOKEN_CHARS = 8192;
47
+ /**
48
+ * HTTP options from the environment, or undefined unless `ANT0_MCP_HTTP=1`.
49
+ * ANT0_MCP_HTTP_HOST / ANT0_MCP_HTTP_PORT (default 127.0.0.1:27180),
50
+ * ANT0_MCP_HTTP_ALLOW_NON_LOOPBACK=1, ANT0_MCP_RESOURCE (canonical resource URL),
51
+ * ANT0_MCP_AUTH_ISSUERS and ANT0_MCP_AUTH_JWKS_URLS (comma lists, same length, paired by
52
+ * position), ANT0_MCP_ALLOWED_ORIGINS (comma list of full origins, e.g. https://app.example.test).
53
+ */
54
+ export declare function httpOptionsFromEnv(env?: Record<string, string | undefined>): HttpOptions | undefined;
55
+ /** Rewrites every JSON-RPC error in a JSON or SSE response; results and other bodies pass. */
56
+ export declare function sanitizeResponse(response: Response): Promise<Response>;
57
+ /** Read a body of at most `limit` bytes, or undefined when it is larger (or the client aborts). */
58
+ export declare function boundedBody(req: IncomingMessage, limit: number): Promise<Buffer | undefined>;
59
+ export declare function webHeaders(req: IncomingMessage): Headers;
60
+ /**
61
+ * Serve the Streamable HTTP endpoint as an OAuth resource server. Opt-in only; it refuses to
62
+ * start without a delegated API key credential, a canonical resource URL and at least one
63
+ * authorization server. The key (never the OAuth token) is what authenticates to ant0d.
64
+ */
65
+ export declare function serveHttp(options: HttpOptions): Promise<HttpServerHandle>;
66
+ //# sourceMappingURL=http.d.ts.map