@ant0/mcp 0.0.0-stage → 0.3.22-beta.2
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/LICENSE +28 -0
- package/README.md +95 -2
- package/THIRD_PARTY_NOTICES +311 -0
- package/dist/api/generated/schema.d.ts +3856 -0
- package/dist/api/generated/schema.js +6 -0
- package/dist/api/index.d.ts +171 -0
- package/dist/api/index.js +332 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.js +59 -0
- package/dist/call-permits.d.ts +10 -0
- package/dist/call-permits.js +67 -0
- package/dist/connection.d.ts +20 -0
- package/dist/connection.js +157 -0
- package/dist/credential-file.d.ts +33 -0
- package/dist/credential-file.js +773 -0
- package/dist/daemon.d.ts +7 -0
- package/dist/daemon.js +260 -0
- package/dist/errors.d.ts +69 -0
- package/dist/errors.js +78 -0
- package/dist/export-files.d.ts +37 -0
- package/dist/export-files.js +167 -0
- package/dist/grant.d.ts +5 -0
- package/dist/grant.js +11 -0
- package/dist/http.d.ts +59 -0
- package/dist/http.js +556 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +85 -0
- package/dist/key-contract.d.ts +325 -0
- package/dist/key-contract.js +241 -0
- package/dist/limits.d.ts +22 -0
- package/dist/limits.js +22 -0
- package/dist/local-routes.d.ts +26 -0
- package/dist/local-routes.js +146 -0
- package/dist/output-descriptor.d.ts +3 -0
- package/dist/output-descriptor.js +19 -0
- package/dist/output-worker-body.d.ts +3 -0
- package/dist/output-worker-body.js +77 -0
- package/dist/output-worker.d.ts +2 -0
- package/dist/output-worker.js +4 -0
- package/dist/output-writer.d.ts +39 -0
- package/dist/output-writer.js +199 -0
- package/dist/peer-watchdog.d.ts +4 -0
- package/dist/peer-watchdog.js +55 -0
- package/dist/server.d.ts +28 -0
- package/dist/server.js +33 -0
- package/dist/text-budget.d.ts +13 -0
- package/dist/text-budget.js +42 -0
- package/dist/tools.d.ts +38 -0
- package/dist/tools.js +1284 -0
- package/dist/transport.d.ts +45 -0
- package/dist/transport.js +313 -0
- package/package.json +66 -4
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { type Client, type Middleware } from "openapi-fetch";
|
|
2
|
+
import type { paths } from "./generated/schema.js";
|
|
3
|
+
/** `GET /v1/health` response. */
|
|
4
|
+
export type Health = paths["/v1/health"]["get"]["responses"][200]["content"]["application/json"];
|
|
5
|
+
export declare const DEFAULT_HOST = "127.0.0.1";
|
|
6
|
+
/** `127.x.x.x`, `localhost`, or `::1` (with or without brackets). */
|
|
7
|
+
export declare function isLoopbackHost(host: string): boolean;
|
|
8
|
+
export declare const DEFAULT_PORT = 27100;
|
|
9
|
+
export interface DiscoveredPidFile {
|
|
10
|
+
pid: number;
|
|
11
|
+
port: number;
|
|
12
|
+
host: string;
|
|
13
|
+
}
|
|
14
|
+
export interface DiscoverOptions {
|
|
15
|
+
/** Data directory; default `$ANT0_HOME`, else the platform data folder (see `resolveHome`). */
|
|
16
|
+
home?: string;
|
|
17
|
+
/** Environment to consult; default `process.env`. */
|
|
18
|
+
env?: Record<string, string | undefined>;
|
|
19
|
+
/** Port override (e.g. a `--port` flag); wins over the pid file and the environment. */
|
|
20
|
+
port?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface DiscoveredDaemon {
|
|
23
|
+
/** `http://<host>:<port>` without a trailing slash. */
|
|
24
|
+
baseUrl: string;
|
|
25
|
+
/** Contents of `ant0d.token`, or undefined when the file is missing or empty. */
|
|
26
|
+
token: string | undefined;
|
|
27
|
+
/** Resolved data directory. */
|
|
28
|
+
home: string;
|
|
29
|
+
/** Parsed `ant0d.pid` when present and well-formed. Liveness is not checked here. */
|
|
30
|
+
pidFile?: DiscoveredPidFile;
|
|
31
|
+
}
|
|
32
|
+
export interface ResolveHomeOptions {
|
|
33
|
+
/** Explicit data directory (a `--home` flag); wins over everything. */
|
|
34
|
+
home?: string;
|
|
35
|
+
env?: Record<string, string | undefined>;
|
|
36
|
+
/** `process.platform`; `win32`, `darwin`, anything else counts as Linux/Unix. */
|
|
37
|
+
platform?: string;
|
|
38
|
+
/** `os.homedir()`. */
|
|
39
|
+
homedir?: () => string;
|
|
40
|
+
/** Whether a candidate data folder counts as existing; default `homeExists`. */
|
|
41
|
+
exists?: (path: string) => boolean;
|
|
42
|
+
/** `process.execPath`; the folder holding it is refused as a data folder. */
|
|
43
|
+
execPath?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* A data folder exists for the legacy rule only when a daemon has run on it (`ant0.db` or
|
|
47
|
+
* `profiles/` present); an empty directory does not shadow a populated `~/.ant0`. Same rule as the
|
|
48
|
+
* Ant0 desktop app.
|
|
49
|
+
*/
|
|
50
|
+
export declare function homeExists(dir: string): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Refuse a data folder that is the directory holding the running executable (an installer that
|
|
53
|
+
* unpacks into the data folder would put the database next to the binary). Resolved paths,
|
|
54
|
+
* case-insensitive on Windows.
|
|
55
|
+
*/
|
|
56
|
+
export declare function assertNotExecutableDir(home: string, execPath: string, platform: string): void;
|
|
57
|
+
/**
|
|
58
|
+
* The platform data folder: Windows `%LOCALAPPDATA%\Ant0`; macOS
|
|
59
|
+
* `~/Library/Application Support/Ant0`; Linux `$XDG_DATA_HOME/ant0` or `~/.local/share/ant0`.
|
|
60
|
+
*/
|
|
61
|
+
export declare function platformDefaultHome(platform: string, env: Record<string, string | undefined>, userHome: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* Resolve the data directory with the same rule as the Ant0 desktop app: the explicit `home`, then `ANT0_HOME`, then the
|
|
64
|
+
* platform default; an existing legacy `~/.ant0` is kept while the platform default does not
|
|
65
|
+
* exist, so the CLI keeps finding a daemon that still runs there.
|
|
66
|
+
*/
|
|
67
|
+
export declare function resolveHome(opts?: ResolveHomeOptions): string;
|
|
68
|
+
/**
|
|
69
|
+
* Locate the daemon from the Ant0 data folder (`ant0d.pid`, `ant0d.token`). Does not throw for a missing file: an
|
|
70
|
+
* unreadable pid file falls back to a loopback `ANT0D_HOST`, `ANT0D_PORT` or `127.0.0.1:27100`, and a
|
|
71
|
+
* missing token yields `token: undefined` (callers treat that as "daemon not running"). The one
|
|
72
|
+
* exception is a token file that exists but is not private: that throws `TokenFileNotPrivateError`.
|
|
73
|
+
*/
|
|
74
|
+
export declare function discoverDaemon(opts?: DiscoverOptions): DiscoveredDaemon;
|
|
75
|
+
/** `ant0d.token` exists but other users could read it, or it is not a plain file of this user. */
|
|
76
|
+
export declare class TokenFileNotPrivateError extends Error {
|
|
77
|
+
readonly name = "TokenFileNotPrivateError";
|
|
78
|
+
readonly path: string;
|
|
79
|
+
readonly reason: string;
|
|
80
|
+
/**
|
|
81
|
+
* Whether `ANT0_ALLOW_SHARED_TOKEN_FILE=1` may waive this refusal: only a wide mode or a foreign
|
|
82
|
+
* owner. A symbolic link or a file that is not a regular file is always refused.
|
|
83
|
+
*/
|
|
84
|
+
readonly waivable: boolean;
|
|
85
|
+
constructor(path: string, reason: string, opts?: {
|
|
86
|
+
optOutHint?: boolean;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/** Set to `1` to turn the token privacy refusal into a stderr warning. */
|
|
90
|
+
export declare const SHARED_TOKEN_FILE_ENV = "ANT0_ALLOW_SHARED_TOKEN_FILE";
|
|
91
|
+
/** The parts of `fs.Stats` that decide whether a token file is private. */
|
|
92
|
+
export interface TokenFileStat {
|
|
93
|
+
isFile(): boolean;
|
|
94
|
+
isSymbolicLink(): boolean;
|
|
95
|
+
uid: number;
|
|
96
|
+
mode: number;
|
|
97
|
+
}
|
|
98
|
+
export interface PrivateTokenOptions {
|
|
99
|
+
/** Default: `process.platform`. */
|
|
100
|
+
platform?: NodeJS.Platform;
|
|
101
|
+
/** Default: `process.geteuid()`. Root (0) may read a token owned by any user, as with OpenSSH. */
|
|
102
|
+
uid?: number | undefined;
|
|
103
|
+
/** Default: `process.env`. */
|
|
104
|
+
env?: Record<string, string | undefined>;
|
|
105
|
+
/** Default: writes to stderr. Called instead of throwing when the opt-out is set. */
|
|
106
|
+
warn?: (message: string) => void;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Why a token file's `lstat` result is not private, or `undefined` when it is. Not Windows: a
|
|
110
|
+
* regular file (not a link), owned by the current user, with no group or other permission bits.
|
|
111
|
+
* On Windows this returns `undefined`: this adapter cannot check Windows file ACLs, so the file goes
|
|
112
|
+
* unverified.
|
|
113
|
+
*/
|
|
114
|
+
export declare function privateTokenProblem(stat: TokenFileStat, opts?: PrivateTokenOptions): string | undefined;
|
|
115
|
+
/**
|
|
116
|
+
* Refuse a token file that is not private. A missing file, or one that cannot be inspected, passes
|
|
117
|
+
* (the caller then sees "no token" as before); a file that is there but fails
|
|
118
|
+
* {@link privateTokenProblem} throws {@link TokenFileNotPrivateError}. Never reads the contents.
|
|
119
|
+
*/
|
|
120
|
+
export declare function checkPrivateTokenFile(file: string, opts?: PrivateTokenOptions): void;
|
|
121
|
+
/**
|
|
122
|
+
* Where the daemon's token is about to be sent: refuse (or, with the opt-out, warn about) a token
|
|
123
|
+
* file that is not private. Does nothing when discovery found no token. Never reads the contents.
|
|
124
|
+
*/
|
|
125
|
+
export declare function checkDiscoveredToken(discovered: Pick<DiscoveredDaemon, "home" | "token">, opts?: PrivateTokenOptions): void;
|
|
126
|
+
export interface ClientOptions {
|
|
127
|
+
/** Default: discovered from the pid file / environment. */
|
|
128
|
+
baseUrl?: string;
|
|
129
|
+
/** Default: `~/.ant0/ant0d.token`. When neither is available, requests go out unauthenticated. */
|
|
130
|
+
token?: string;
|
|
131
|
+
/**
|
|
132
|
+
* No authentication: the token is never discovered, checked or sent (a given `token` is
|
|
133
|
+
* ignored). For health checks and other routes that need none. `baseUrl` is still discovered
|
|
134
|
+
* when omitted.
|
|
135
|
+
*/
|
|
136
|
+
anonymous?: boolean;
|
|
137
|
+
/** `ANT0_HOME` used for discovery when `baseUrl` or `token` are omitted. */
|
|
138
|
+
home?: string;
|
|
139
|
+
/** Injected fetch (tests, custom dispatchers). Default: `globalThis.fetch`. */
|
|
140
|
+
fetch?: typeof fetch;
|
|
141
|
+
}
|
|
142
|
+
export type Ant0Client = Client<paths>;
|
|
143
|
+
/** Middleware that adds `Authorization: Bearer <token>` to every request. */
|
|
144
|
+
export declare function bearerMiddleware(token: string): Middleware;
|
|
145
|
+
/**
|
|
146
|
+
* An `openapi-fetch` client for the daemon. Missing `baseUrl`/`token` are discovered from
|
|
147
|
+
* `opts.home` (see `discoverDaemon`). Connection failures surface as the `fetch` rejection
|
|
148
|
+
* (`TypeError: fetch failed` with `cause.code === "ECONNREFUSED"` when nothing listens).
|
|
149
|
+
*/
|
|
150
|
+
export declare function createAnt0Client(opts?: ClientOptions): Ant0Client;
|
|
151
|
+
/** A non-2xx answer from the daemon, decoded from the `{ error, message, details? }` envelope. */
|
|
152
|
+
export declare class Ant0ApiError extends Error {
|
|
153
|
+
readonly name = "Ant0ApiError";
|
|
154
|
+
readonly status: number;
|
|
155
|
+
/** Namespaced code such as `profile.not_found`; `http_<status>` when the body was not JSON. */
|
|
156
|
+
readonly code: string;
|
|
157
|
+
readonly details?: unknown;
|
|
158
|
+
constructor(status: number, code: string, message: string, details?: unknown);
|
|
159
|
+
static fromEnvelope(status: number, body: unknown, statusText?: string): Ant0ApiError;
|
|
160
|
+
}
|
|
161
|
+
export declare function isAnt0ApiError(value: unknown): value is Ant0ApiError;
|
|
162
|
+
/**
|
|
163
|
+
* Turn an `openapi-fetch` result into its data or throw `Ant0ApiError`. `openapi-fetch` yields
|
|
164
|
+
* `data: {}` for 204 responses, so `unwrap` on a DELETE resolves to an empty object.
|
|
165
|
+
*/
|
|
166
|
+
export declare function unwrap<T>(result: {
|
|
167
|
+
data?: T;
|
|
168
|
+
error?: unknown;
|
|
169
|
+
response: Response;
|
|
170
|
+
}): T;
|
|
171
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed client for the Ant0 desktop local API, reduced to what this adapter needs.
|
|
3
|
+
*
|
|
4
|
+
* `generated/schema.ts` is produced from `openapi.json` (the subset of the local API that the
|
|
5
|
+
* adapter calls) by `scripts/generate-api.mjs` and is never edited by hand. This module adds
|
|
6
|
+
* discovery of the local daemon (`<ANT0_HOME>/ant0d.pid` + `ant0d.token`), a bearer-token
|
|
7
|
+
* middleware and an error type for the `{ error, message, details? }` envelope.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, lstatSync, readFileSync } from "node:fs";
|
|
10
|
+
import { homedir, platform as osPlatform } from "node:os";
|
|
11
|
+
import { dirname, join, posix, resolve, win32 } from "node:path";
|
|
12
|
+
import createClient, {} from "openapi-fetch";
|
|
13
|
+
// ---------------------------------------------------------------------------------------------
|
|
14
|
+
// Discovery
|
|
15
|
+
// ---------------------------------------------------------------------------------------------
|
|
16
|
+
export const DEFAULT_HOST = "127.0.0.1";
|
|
17
|
+
/** `127.x.x.x`, `localhost`, or `::1` (with or without brackets). */
|
|
18
|
+
export function isLoopbackHost(host) {
|
|
19
|
+
const h = host
|
|
20
|
+
.trim()
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.replace(/^\[|\]$/g, "");
|
|
23
|
+
return (h === "localhost" ||
|
|
24
|
+
h === "::1" ||
|
|
25
|
+
(/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h) &&
|
|
26
|
+
h.split(".").every((part) => Number(part) <= 255)));
|
|
27
|
+
}
|
|
28
|
+
export const DEFAULT_PORT = 27100;
|
|
29
|
+
/**
|
|
30
|
+
* A data folder exists for the legacy rule only when a daemon has run on it (`ant0.db` or
|
|
31
|
+
* `profiles/` present); an empty directory does not shadow a populated `~/.ant0`. Same rule as the
|
|
32
|
+
* Ant0 desktop app.
|
|
33
|
+
*/
|
|
34
|
+
export function homeExists(dir) {
|
|
35
|
+
return existsSync(join(dir, "ant0.db")) || existsSync(join(dir, "profiles"));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Refuse a data folder that is the directory holding the running executable (an installer that
|
|
39
|
+
* unpacks into the data folder would put the database next to the binary). Resolved paths,
|
|
40
|
+
* case-insensitive on Windows.
|
|
41
|
+
*/
|
|
42
|
+
export function assertNotExecutableDir(home, execPath, platform) {
|
|
43
|
+
const exeDir = resolve(dirname(execPath));
|
|
44
|
+
const target = resolve(home);
|
|
45
|
+
const same = platform === "win32" ? exeDir.toLowerCase() === target.toLowerCase() : exeDir === target;
|
|
46
|
+
if (same) {
|
|
47
|
+
throw new Error(`refusing to use ${target} as the data folder: it contains the running executable ` +
|
|
48
|
+
`(${execPath}); set ANT0_HOME or --home to a separate folder`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The platform data folder: Windows `%LOCALAPPDATA%\Ant0`; macOS
|
|
53
|
+
* `~/Library/Application Support/Ant0`; Linux `$XDG_DATA_HOME/ant0` or `~/.local/share/ant0`.
|
|
54
|
+
*/
|
|
55
|
+
export function platformDefaultHome(platform, env, userHome) {
|
|
56
|
+
if (platform === "win32") {
|
|
57
|
+
const local = env.LOCALAPPDATA && env.LOCALAPPDATA.length > 0 ? env.LOCALAPPDATA : undefined;
|
|
58
|
+
return local ? win32.join(local, "Ant0") : win32.join(userHome, "AppData", "Local", "Ant0");
|
|
59
|
+
}
|
|
60
|
+
if (platform === "darwin")
|
|
61
|
+
return posix.join(userHome, "Library", "Application Support", "Ant0");
|
|
62
|
+
const xdg = env.XDG_DATA_HOME && env.XDG_DATA_HOME.length > 0 ? env.XDG_DATA_HOME : undefined;
|
|
63
|
+
return xdg ? posix.join(xdg, "ant0") : posix.join(userHome, ".local", "share", "ant0");
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Resolve the data directory with the same rule as the Ant0 desktop app: the explicit `home`, then `ANT0_HOME`, then the
|
|
67
|
+
* platform default; an existing legacy `~/.ant0` is kept while the platform default does not
|
|
68
|
+
* exist, so the CLI keeps finding a daemon that still runs there.
|
|
69
|
+
*/
|
|
70
|
+
export function resolveHome(opts = {}) {
|
|
71
|
+
const env = opts.env ?? process.env;
|
|
72
|
+
const platform = opts.platform ?? osPlatform();
|
|
73
|
+
const execPath = opts.execPath ?? process.execPath;
|
|
74
|
+
const explicit = opts.home ?? env.ANT0_HOME?.trim();
|
|
75
|
+
if (explicit && explicit.length > 0) {
|
|
76
|
+
assertNotExecutableDir(explicit, execPath, platform);
|
|
77
|
+
return explicit;
|
|
78
|
+
}
|
|
79
|
+
const exists = opts.exists ?? homeExists;
|
|
80
|
+
const userHome = (opts.homedir ?? homedir)();
|
|
81
|
+
const def = platformDefaultHome(platform, env, userHome);
|
|
82
|
+
const legacy = (platform === "win32" ? win32 : posix).join(userHome, ".ant0");
|
|
83
|
+
const home = !exists(def) && exists(legacy) ? legacy : def;
|
|
84
|
+
assertNotExecutableDir(home, execPath, platform);
|
|
85
|
+
return home;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Locate the daemon from the Ant0 data folder (`ant0d.pid`, `ant0d.token`). Does not throw for a missing file: an
|
|
89
|
+
* unreadable pid file falls back to a loopback `ANT0D_HOST`, `ANT0D_PORT` or `127.0.0.1:27100`, and a
|
|
90
|
+
* missing token yields `token: undefined` (callers treat that as "daemon not running"). The one
|
|
91
|
+
* exception is a token file that exists but is not private: that throws `TokenFileNotPrivateError`.
|
|
92
|
+
*/
|
|
93
|
+
export function discoverDaemon(opts = {}) {
|
|
94
|
+
const env = opts.env ?? process.env;
|
|
95
|
+
const home = resolveHome({ ...(opts.home !== undefined ? { home: opts.home } : {}), env });
|
|
96
|
+
const pidFile = readPidFile(join(home, "ant0d.pid"));
|
|
97
|
+
const envPort = parsePort(env.ANT0D_PORT);
|
|
98
|
+
// The daemon only ever listens on loopback; a pid file naming another host is tampered or
|
|
99
|
+
// stale and must not redirect the bearer token anywhere (mirrors the desktop shell's rule).
|
|
100
|
+
const pidHost = pidFile && isLoopbackHost(pidFile.host) ? pidFile.host : undefined;
|
|
101
|
+
// The same rule applies to ANT0D_HOST: only a loopback address is accepted (as in
|
|
102
|
+
// `canonicalOrigin` of the MCP connection); anything else is ignored.
|
|
103
|
+
const envHost = env.ANT0D_HOST?.trim();
|
|
104
|
+
const host = pidHost ??
|
|
105
|
+
(envHost && isLoopbackHost(envHost) ? envHost.replace(/^\[|\]$/g, "") : DEFAULT_HOST);
|
|
106
|
+
const port = opts.port ?? pidFile?.port ?? envPort ?? DEFAULT_PORT;
|
|
107
|
+
const token = readToken(join(home, "ant0d.token"));
|
|
108
|
+
const result = { baseUrl: baseUrlFor(host, port), token, home };
|
|
109
|
+
if (pidFile)
|
|
110
|
+
result.pidFile = pidFile;
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
function baseUrlFor(host, port) {
|
|
114
|
+
const h = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
|
115
|
+
return `http://${h}:${port}`;
|
|
116
|
+
}
|
|
117
|
+
function parsePort(value) {
|
|
118
|
+
if (value === undefined || value.trim() === "")
|
|
119
|
+
return undefined;
|
|
120
|
+
const n = Number(value);
|
|
121
|
+
return Number.isInteger(n) && n > 0 && n <= 65535 ? n : undefined;
|
|
122
|
+
}
|
|
123
|
+
function readPidFile(file) {
|
|
124
|
+
try {
|
|
125
|
+
if (!existsSync(file))
|
|
126
|
+
return undefined;
|
|
127
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
128
|
+
if (typeof parsed.pid !== "number" || typeof parsed.port !== "number")
|
|
129
|
+
return undefined;
|
|
130
|
+
return {
|
|
131
|
+
pid: parsed.pid,
|
|
132
|
+
port: parsed.port,
|
|
133
|
+
host: typeof parsed.host === "string" && parsed.host.length > 0 ? parsed.host : DEFAULT_HOST,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function readToken(file) {
|
|
141
|
+
// Discovery only reads: daemon start/stop/status and health checks never send the token. The
|
|
142
|
+
// privacy check runs where the token is sent (`checkDiscoveredToken`).
|
|
143
|
+
try {
|
|
144
|
+
if (!existsSync(file))
|
|
145
|
+
return undefined;
|
|
146
|
+
const token = readFileSync(file, "utf8").trim();
|
|
147
|
+
return token.length > 0 ? token : undefined;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** `ant0d.token` exists but other users could read it, or it is not a plain file of this user. */
|
|
154
|
+
export class TokenFileNotPrivateError extends Error {
|
|
155
|
+
name = "TokenFileNotPrivateError";
|
|
156
|
+
path;
|
|
157
|
+
reason;
|
|
158
|
+
/**
|
|
159
|
+
* Whether `ANT0_ALLOW_SHARED_TOKEN_FILE=1` may waive this refusal: only a wide mode or a foreign
|
|
160
|
+
* owner. A symbolic link or a file that is not a regular file is always refused.
|
|
161
|
+
*/
|
|
162
|
+
waivable;
|
|
163
|
+
constructor(path, reason, opts = {}) {
|
|
164
|
+
const waivable = reason.startsWith("mode") || reason.startsWith("owned by another user");
|
|
165
|
+
super(`token file ${path} is not private (${reason}). ${tokenFileFix(path, reason, waivable && opts.optOutHint !== false)}`);
|
|
166
|
+
this.waivable = waivable;
|
|
167
|
+
this.path = path;
|
|
168
|
+
this.reason = reason;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** How to put a token file right; mentions the path, never the token. */
|
|
172
|
+
function tokenFileFix(path, reason, optOutHint) {
|
|
173
|
+
const q = shellQuote(path);
|
|
174
|
+
const optOut = optOutHint
|
|
175
|
+
? ` Or set ${SHARED_TOKEN_FILE_ENV}=1 to warn instead of refusing (for file systems without Unix modes).`
|
|
176
|
+
: "";
|
|
177
|
+
if (reason.startsWith("mode"))
|
|
178
|
+
return `Fix: chmod 600 ${q}.${optOut}`;
|
|
179
|
+
if (reason.startsWith("owned by another user"))
|
|
180
|
+
return `Run ant0 as the file's owner, or chown it to your user (chown "$(id -un)" ${q}) and chmod 600 it.${optOut}`;
|
|
181
|
+
return `Fix: remove it and run \`ant0 daemon start\` to recreate it as a private file.${optOut}`;
|
|
182
|
+
}
|
|
183
|
+
/** POSIX single quotes: safe for spaces, `$`, backticks and double quotes in the path. */
|
|
184
|
+
function shellQuote(path) {
|
|
185
|
+
return `'${path.replaceAll("'", `'\\''`)}'`;
|
|
186
|
+
}
|
|
187
|
+
/** Set to `1` to turn the token privacy refusal into a stderr warning. */
|
|
188
|
+
export const SHARED_TOKEN_FILE_ENV = "ANT0_ALLOW_SHARED_TOKEN_FILE";
|
|
189
|
+
/**
|
|
190
|
+
* Why a token file's `lstat` result is not private, or `undefined` when it is. Not Windows: a
|
|
191
|
+
* regular file (not a link), owned by the current user, with no group or other permission bits.
|
|
192
|
+
* On Windows this returns `undefined`: this adapter cannot check Windows file ACLs, so the file goes
|
|
193
|
+
* unverified.
|
|
194
|
+
*/
|
|
195
|
+
export function privateTokenProblem(stat, opts = {}) {
|
|
196
|
+
if ((opts.platform ?? process.platform) === "win32")
|
|
197
|
+
return undefined;
|
|
198
|
+
if (stat.isSymbolicLink())
|
|
199
|
+
return "a symbolic link";
|
|
200
|
+
if (!stat.isFile())
|
|
201
|
+
return "not a regular file";
|
|
202
|
+
const uid = "uid" in opts ? opts.uid : process.geteuid?.();
|
|
203
|
+
if (uid !== undefined && uid !== 0 && stat.uid !== uid)
|
|
204
|
+
return "owned by another user";
|
|
205
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
206
|
+
return `mode ${(stat.mode & 0o777).toString(8).padStart(3, "0")} gives group or others access`;
|
|
207
|
+
}
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Refuse a token file that is not private. A missing file, or one that cannot be inspected, passes
|
|
212
|
+
* (the caller then sees "no token" as before); a file that is there but fails
|
|
213
|
+
* {@link privateTokenProblem} throws {@link TokenFileNotPrivateError}. Never reads the contents.
|
|
214
|
+
*/
|
|
215
|
+
export function checkPrivateTokenFile(file, opts = {}) {
|
|
216
|
+
let stat;
|
|
217
|
+
try {
|
|
218
|
+
stat = lstatSync(file);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const problem = privateTokenProblem(stat, opts);
|
|
224
|
+
if (problem === undefined)
|
|
225
|
+
return;
|
|
226
|
+
const optedOut = (opts.env ?? process.env)[SHARED_TOKEN_FILE_ENV] === "1";
|
|
227
|
+
const error = new TokenFileNotPrivateError(file, problem, { optOutHint: !optedOut });
|
|
228
|
+
if (optedOut && error.waivable) {
|
|
229
|
+
const text = `ant0: warning: ${error.message} (continuing: ${SHARED_TOKEN_FILE_ENV}=1)\n`;
|
|
230
|
+
if (opts.warn)
|
|
231
|
+
opts.warn(text);
|
|
232
|
+
else
|
|
233
|
+
process.stderr.write(text);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Where the daemon's token is about to be sent: refuse (or, with the opt-out, warn about) a token
|
|
240
|
+
* file that is not private. Does nothing when discovery found no token. Never reads the contents.
|
|
241
|
+
*/
|
|
242
|
+
export function checkDiscoveredToken(discovered, opts = {}) {
|
|
243
|
+
if (discovered.token === undefined)
|
|
244
|
+
return;
|
|
245
|
+
checkPrivateTokenFile(join(discovered.home, "ant0d.token"), opts);
|
|
246
|
+
}
|
|
247
|
+
/** Middleware that adds `Authorization: Bearer <token>` to every request. */
|
|
248
|
+
export function bearerMiddleware(token) {
|
|
249
|
+
return {
|
|
250
|
+
onRequest({ request }) {
|
|
251
|
+
request.headers.set("authorization", `Bearer ${token}`);
|
|
252
|
+
return request;
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* An `openapi-fetch` client for the daemon. Missing `baseUrl`/`token` are discovered from
|
|
258
|
+
* `opts.home` (see `discoverDaemon`). Connection failures surface as the `fetch` rejection
|
|
259
|
+
* (`TypeError: fetch failed` with `cause.code === "ECONNREFUSED"` when nothing listens).
|
|
260
|
+
*/
|
|
261
|
+
export function createAnt0Client(opts = {}) {
|
|
262
|
+
let baseUrl = opts.baseUrl;
|
|
263
|
+
let token = opts.token;
|
|
264
|
+
if (opts.anonymous === true)
|
|
265
|
+
token = undefined;
|
|
266
|
+
if (baseUrl === undefined || (token === undefined && opts.anonymous !== true)) {
|
|
267
|
+
const discovered = discoverDaemon(opts.home !== undefined ? { home: opts.home } : {});
|
|
268
|
+
baseUrl ??= discovered.baseUrl;
|
|
269
|
+
if (token === undefined && opts.anonymous !== true) {
|
|
270
|
+
// The token is about to be sent: refuse a token file that is not private.
|
|
271
|
+
checkDiscoveredToken(discovered);
|
|
272
|
+
token = discovered.token;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const fetchFn = opts.fetch;
|
|
276
|
+
const client = createClient({
|
|
277
|
+
baseUrl,
|
|
278
|
+
...(fetchFn ? { fetch: (request) => fetchFn(request) } : {}),
|
|
279
|
+
});
|
|
280
|
+
if (token !== undefined)
|
|
281
|
+
client.use(bearerMiddleware(token));
|
|
282
|
+
return client;
|
|
283
|
+
}
|
|
284
|
+
// ---------------------------------------------------------------------------------------------
|
|
285
|
+
// Errors
|
|
286
|
+
// ---------------------------------------------------------------------------------------------
|
|
287
|
+
/** A non-2xx answer from the daemon, decoded from the `{ error, message, details? }` envelope. */
|
|
288
|
+
export class Ant0ApiError extends Error {
|
|
289
|
+
name = "Ant0ApiError";
|
|
290
|
+
status;
|
|
291
|
+
/** Namespaced code such as `profile.not_found`; `http_<status>` when the body was not JSON. */
|
|
292
|
+
code;
|
|
293
|
+
details;
|
|
294
|
+
constructor(status, code, message, details) {
|
|
295
|
+
super(message);
|
|
296
|
+
this.status = status;
|
|
297
|
+
this.code = code;
|
|
298
|
+
if (details !== undefined)
|
|
299
|
+
this.details = details;
|
|
300
|
+
}
|
|
301
|
+
static fromEnvelope(status, body, statusText = "") {
|
|
302
|
+
if (body !== null && typeof body === "object") {
|
|
303
|
+
const env = body;
|
|
304
|
+
const code = typeof env.error === "string" ? env.error : `http_${status}`;
|
|
305
|
+
const message = typeof env.message === "string"
|
|
306
|
+
? env.message
|
|
307
|
+
: typeof env.error === "string"
|
|
308
|
+
? env.error
|
|
309
|
+
: statusText || `HTTP ${status}`;
|
|
310
|
+
return new Ant0ApiError(status, code, message, env.details);
|
|
311
|
+
}
|
|
312
|
+
const text = typeof body === "string" && body.trim().length > 0 ? body.trim() : "";
|
|
313
|
+
return new Ant0ApiError(status, `http_${status}`, text || statusText || `HTTP ${status}`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
export function isAnt0ApiError(value) {
|
|
317
|
+
return value instanceof Ant0ApiError;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Turn an `openapi-fetch` result into its data or throw `Ant0ApiError`. `openapi-fetch` yields
|
|
321
|
+
* `data: {}` for 204 responses, so `unwrap` on a DELETE resolves to an empty object.
|
|
322
|
+
*/
|
|
323
|
+
export function unwrap(result) {
|
|
324
|
+
if (result.error !== undefined) {
|
|
325
|
+
throw Ant0ApiError.fromEnvelope(result.response.status, result.error, result.response.statusText);
|
|
326
|
+
}
|
|
327
|
+
if (result.data === undefined && !result.response.ok) {
|
|
328
|
+
throw new Ant0ApiError(result.response.status, `http_${result.response.status}`, result.response.statusText || `HTTP ${result.response.status}`);
|
|
329
|
+
}
|
|
330
|
+
return result.data;
|
|
331
|
+
}
|
|
332
|
+
//# sourceMappingURL=index.js.map
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `ant0-mcp`: serve the Ant0 MCP adapter over stdio against an already-running Ant0 desktop app.
|
|
4
|
+
*
|
|
5
|
+
* ant0-mcp [serve] [--stdio] [--home <dir>] [--port <n>] [--credential-file <path>]
|
|
6
|
+
*
|
|
7
|
+
* An API key, when used, comes from ANT0_API_KEY or a private credential file; stdin carries the
|
|
8
|
+
* MCP protocol and nothing else.
|
|
9
|
+
*/
|
|
10
|
+
import { McpFailure, serveStdio } from "./index.js";
|
|
11
|
+
function usage(message) {
|
|
12
|
+
if (message)
|
|
13
|
+
process.stderr.write(`ant0-mcp: ${message}\n`);
|
|
14
|
+
process.stderr.write("usage: ant0-mcp [serve] [--stdio] [--home <dir>] [--port <n>] [--credential-file <path>]\n");
|
|
15
|
+
process.exit(2);
|
|
16
|
+
}
|
|
17
|
+
const args = process.argv.slice(2);
|
|
18
|
+
if (args[0] === "serve")
|
|
19
|
+
args.shift();
|
|
20
|
+
let home;
|
|
21
|
+
let port;
|
|
22
|
+
let credentialFile;
|
|
23
|
+
for (let i = 0; i < args.length; i++) {
|
|
24
|
+
const arg = args[i];
|
|
25
|
+
const value = () => {
|
|
26
|
+
const v = args[++i];
|
|
27
|
+
if (v === undefined || v === "")
|
|
28
|
+
usage(`${arg} needs a value`);
|
|
29
|
+
return v;
|
|
30
|
+
};
|
|
31
|
+
if (arg === "--stdio")
|
|
32
|
+
continue;
|
|
33
|
+
else if (arg === "--home")
|
|
34
|
+
home = value();
|
|
35
|
+
else if (arg === "--credential-file")
|
|
36
|
+
credentialFile = value();
|
|
37
|
+
else if (arg === "--port") {
|
|
38
|
+
const n = Number(value());
|
|
39
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535)
|
|
40
|
+
usage("--port expects a port number (1-65535)");
|
|
41
|
+
port = n;
|
|
42
|
+
}
|
|
43
|
+
else if (arg === "--help" || arg === "-h")
|
|
44
|
+
usage();
|
|
45
|
+
else
|
|
46
|
+
usage("unknown argument");
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
await serveStdio({
|
|
50
|
+
...(home !== undefined ? { home } : {}),
|
|
51
|
+
...(port !== undefined ? { port } : {}),
|
|
52
|
+
...(credentialFile !== undefined ? { credentialFile } : {}),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
process.stderr.write(`ant0-mcp: ${error instanceof McpFailure ? error.message : "adapter failed"}\n`);
|
|
57
|
+
process.exitCode = 1;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=bin.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Eight executing handlers and at most eight accepted replacements waiting for HTTP drain. */
|
|
2
|
+
export declare class CallPermits {
|
|
3
|
+
private active;
|
|
4
|
+
private readonly waiting;
|
|
5
|
+
run<T>(signal: AbortSignal, action: () => Promise<T>): Promise<T>;
|
|
6
|
+
private acquire;
|
|
7
|
+
private grant;
|
|
8
|
+
private drain;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=call-permits.d.ts.map
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { McpFailure } from "./errors.js";
|
|
2
|
+
import { LIMITS } from "./limits.js";
|
|
3
|
+
/** Eight executing handlers and at most eight accepted replacements waiting for HTTP drain. */
|
|
4
|
+
export class CallPermits {
|
|
5
|
+
active = 0;
|
|
6
|
+
waiting = new Set(); // Insertion order is the admission FIFO.
|
|
7
|
+
async run(signal, action) {
|
|
8
|
+
const release = await this.acquire(signal);
|
|
9
|
+
try {
|
|
10
|
+
// Cancellation can happen after grant but before this continuation starts. The permit
|
|
11
|
+
// still has exactly one owner; no HTTP is started for that cancelled request.
|
|
12
|
+
if (signal.aborted)
|
|
13
|
+
throw new McpFailure("cancelled");
|
|
14
|
+
return await action();
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
release();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
acquire(signal) {
|
|
21
|
+
if (signal.aborted)
|
|
22
|
+
return Promise.reject(new McpFailure("cancelled"));
|
|
23
|
+
if (this.active < LIMITS.concurrentCalls && this.waiting.size === 0) {
|
|
24
|
+
return Promise.resolve(this.grant());
|
|
25
|
+
}
|
|
26
|
+
if (this.waiting.size >= LIMITS.concurrentCalls)
|
|
27
|
+
return Promise.reject(new McpFailure("busy"));
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
const waiter = {
|
|
30
|
+
signal,
|
|
31
|
+
resolve,
|
|
32
|
+
reject,
|
|
33
|
+
abort: () => {
|
|
34
|
+
if (!this.waiting.delete(waiter))
|
|
35
|
+
return;
|
|
36
|
+
signal.removeEventListener("abort", waiter.abort);
|
|
37
|
+
reject(new McpFailure("cancelled"));
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
this.waiting.add(waiter);
|
|
41
|
+
signal.addEventListener("abort", waiter.abort, { once: true });
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
grant() {
|
|
45
|
+
this.active++;
|
|
46
|
+
let released = false;
|
|
47
|
+
return () => {
|
|
48
|
+
if (released)
|
|
49
|
+
return;
|
|
50
|
+
released = true;
|
|
51
|
+
this.active--;
|
|
52
|
+
this.drain();
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
drain() {
|
|
56
|
+
while (this.active < LIMITS.concurrentCalls && this.waiting.size) {
|
|
57
|
+
const waiter = this.waiting.values().next().value;
|
|
58
|
+
this.waiting.delete(waiter);
|
|
59
|
+
waiter.signal.removeEventListener("abort", waiter.abort);
|
|
60
|
+
if (waiter.signal.aborted)
|
|
61
|
+
waiter.reject(new McpFailure("cancelled"));
|
|
62
|
+
else
|
|
63
|
+
waiter.resolve(this.grant());
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=call-permits.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type CredentialSnapshot } from "./credential-file.js";
|
|
2
|
+
export interface DiscoveryOptions {
|
|
3
|
+
credentialFile?: string;
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
home?: string;
|
|
6
|
+
port?: number;
|
|
7
|
+
env?: Record<string, string | undefined>;
|
|
8
|
+
}
|
|
9
|
+
export interface Connection {
|
|
10
|
+
origin: string;
|
|
11
|
+
token: string;
|
|
12
|
+
credential?: CredentialSnapshot;
|
|
13
|
+
apiKey?: true;
|
|
14
|
+
}
|
|
15
|
+
export declare function keyMode(connection: Connection): boolean;
|
|
16
|
+
/** Exact syntax first: URL parsing alone accepts short/octal/hex IPv4 and strips URL parts. */
|
|
17
|
+
export declare function canonicalOrigin(value: string): string;
|
|
18
|
+
/** Same home and flag > pid > env > default precedence as the CLI, with fail-closed validation. */
|
|
19
|
+
export declare function discoverConnection(options: DiscoveryOptions): Connection;
|
|
20
|
+
//# sourceMappingURL=connection.d.ts.map
|