alineo-mcp 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +191 -0
  2. package/dist/index.mjs +968 -0
  3. package/package.json +45 -0
package/README.md ADDED
@@ -0,0 +1,191 @@
1
+ # alineo-mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that lets any MCP client (Claude Code, Claude
4
+ Desktop, Cursor, a scripted client, …) orchestrate swarms of sandboxed coding agents through
5
+ [alineod](../../apps/alineod), alineo's HTTP + SSE control daemon, plus manage the local
6
+ agent-spec cache.
7
+
8
+ Stdio transport, launched as a local process by the MCP client — the same shape as most MCP
9
+ servers (filesystem, GitHub, …), not a hosted worker like [`@alineo-labs/docs-mcp`](../../apps/docs-mcp).
10
+
11
+ ## Tools
12
+
13
+ **alineod — swarm control** (requires alineod running, default `http://127.0.0.1:4600`, override
14
+ with `ALINEOD_URL`):
15
+
16
+ | Tool | Route | |
17
+ | ---------------------- | ------------------------------- | ------------------------------------------------------- |
18
+ | `alineod_create_run` | `POST /runs` | Load the root agent from an AgentSpec, start a run |
19
+ | `alineod_get_run` | `GET /runs/:runId` | The spawn tree — every agent, state, parent pointers |
20
+ | `alineod_delete_run` | `DELETE /runs/:runId` | Abort + close every live agent in the run |
21
+ | `alineod_watch_events` | `GET /runs/:runId/events` (SSE) | Collect lifecycle + harness events for a bounded window |
22
+ | `alineod_spawn_agent` | `POST /runs/:runId/agents` | Fork a child under a live parent |
23
+ | `alineod_get_agent` | `GET /agents/:agentId` | Inspect an agent + session stats |
24
+ | `alineod_prompt_agent` | `POST /agents/:agentId/prompt` | Drive one turn |
25
+ | `alineod_steer_agent` | `POST /agents/:agentId/steer` | Redirect the current turn |
26
+ | `alineod_pause_agent` | `POST /agents/:agentId/pause` | Freeze the sandbox container |
27
+ | `alineod_resume_agent` | `POST /agents/:agentId/resume` | Thaw a paused container |
28
+ | `alineod_stop_agent` | `POST /agents/:agentId/stop` | Abort + close one agent |
29
+ | `alineod_get_result` | `GET /agents/:agentId/result` | Resolve a settled agent's output (optional long-poll) |
30
+
31
+ **alineo — local bootstrap + spec management** (no alineod required for these):
32
+
33
+ | Tool | |
34
+ | -------------------- | ------------------------------------------------------------ |
35
+ | `alineo_init` | Start OpenSandbox + alineod locally via Docker |
36
+ | `alineo_add_spec` | Fetch an AgentSpec (URL or local file), validate it, save it |
37
+ | `alineo_list_specs` | List saved agent specs |
38
+ | `alineo_remove_spec` | Remove a saved agent spec |
39
+
40
+ This mirrors every alineod HTTP route and every `alineo-cli` subcommand except `telemetry`
41
+ (local opt-in/out toggle, not an orchestration feature) and the CLI's direct-sandbox commands
42
+ (`spawn`/`prompt`/`fork`/`agents`/`kill`/`logs`) — those drive a sandbox from _this_ process via
43
+ `Alineo.load()`; alineod's routes are the equivalent, network-addressable operations for a
44
+ swarm run through the daemon, which is what an MCP client actually talks to.
45
+
46
+ ## Install
47
+
48
+ Not published to npm yet on this branch — for now, build it locally from the repo:
49
+
50
+ ```bash
51
+ git clone https://github.com/DrejT/alineo.git && cd alineo
52
+ bun install && bun run --cwd packages/mcp build # → packages/mcp/dist/index.mjs
53
+ ```
54
+
55
+ Once published, `npx -y alineo-mcp` (or `bunx alineo-mcp`) will fetch and run it with no local
56
+ checkout needed — the client configs below assume that form; swap in
57
+ `bun /absolute/path/to/alineo/packages/mcp/dist/index.mjs` for a local build.
58
+
59
+ ## Configure a client
60
+
61
+ Every MCP client uses the same JSON shape — an entry under `mcpServers` naming the command to
62
+ launch and (optionally) environment variables to set. Where that JSON lives differs per client:
63
+
64
+ | Client | Config file |
65
+ | -------------------- | --------------------------------------------------------------------------------------------------------------------------- |
66
+ | Claude Desktop | `claude_desktop_config.json` ([platform paths](https://modelcontextprotocol.io/quickstart/user)) |
67
+ | Claude Code (CLI) | `~/.claude.json` (user scope) or `.mcp.json` in a project (project scope) — or skip the file and run `claude mcp add` below |
68
+ | Cursor | `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` in a project |
69
+ | Any other MCP client | Its own equivalent `mcpServers` config, or point it at the stdio command directly |
70
+
71
+ ```json
72
+ {
73
+ "mcpServers": {
74
+ "alineo": {
75
+ "command": "npx",
76
+ "args": ["-y", "alineo-mcp"],
77
+ "env": {
78
+ "ALINEOD_URL": "http://127.0.0.1:4600"
79
+ }
80
+ }
81
+ }
82
+ }
83
+ ```
84
+
85
+ `env` is optional — omit it to use the default `http://127.0.0.1:4600`, which is what
86
+ `alineo_init` (see below) starts alineod on.
87
+
88
+ **Claude Code CLI**, no file editing needed:
89
+
90
+ ```bash
91
+ claude mcp add alineo -- npx -y alineo-mcp
92
+ # scope to just this project instead of every session:
93
+ claude mcp add alineo --scope project -- npx -y alineo-mcp
94
+ # with a non-default alineod URL:
95
+ claude mcp add alineo --env ALINEOD_URL=http://127.0.0.1:4600 -- npx -y alineo-mcp
96
+ ```
97
+
98
+ **A local build** (this branch, before publishing), in any of the configs above:
99
+
100
+ ```json
101
+ {
102
+ "mcpServers": {
103
+ "alineo": {
104
+ "command": "bun",
105
+ "args": ["D:/path/to/alineo/packages/mcp/dist/index.mjs"],
106
+ "env": { "ALINEOD_URL": "http://127.0.0.1:4600" }
107
+ }
108
+ }
109
+ }
110
+ ```
111
+
112
+ **Scripted / programmatic client** — connect over stdio from your own code instead of a chat
113
+ client; see [`cookbooks/mcp-agent-swarm`](../../cookbooks/mcp-agent-swarm) for a full runnable
114
+ recipe using `@modelcontextprotocol/client`'s `StdioClientTransport`.
115
+
116
+ ## Configuration reference
117
+
118
+ | Setting | Where | Default | Affects |
119
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------- |
120
+ | `ALINEOD_URL` | env var on the `alineo-mcp` process | `http://127.0.0.1:4600` | Every `alineod_*` tool |
121
+ | `alineo.config.json` | project-local file, or `~/.config/alineo/config.json` global fallback (same resolution as `alineo-cli`) | written by `alineo_init` | `agentsDir` for `alineo_add_spec` / `list_specs` / `remove_spec` |
122
+ | Docker | must be installed and running | — | `alineo_init` only |
123
+ | Model provider API key | in the _caller's_ shell when running `alineo_init` (forwarded into the alineod container) — see the list in `@alineo-labs/cli-shared`'s `pi-model-keys.ts` | none | Whether spawned agents can actually call a model |
124
+
125
+ `alineo.config.json`'s `agentsDir` is shared with `alineo-cli` — specs added via either tool show
126
+ up in both, since they resolve the same config file and directory.
127
+
128
+ ## Use
129
+
130
+ ```bash
131
+ alineo_init # once, if alineod isn't already running (needs Docker)
132
+ ```
133
+
134
+ Typical flow, as a client would call the tools:
135
+
136
+ 1. `alineo_add_spec` (or `alineo_list_specs` if you've already added one) → get an AgentSpec.
137
+ 2. `alineod_create_run` with that spec → get back a `runId` + `rootAgentId`.
138
+ 3. `alineod_spawn_agent` with `parentAgentId: rootAgentId` to fan out children — repeat per
139
+ worker; pass `waitFor` on a later spawn to hold it until earlier agents settle.
140
+ 4. `alineod_prompt_agent` / `alineod_steer_agent` to drive them; `alineod_pause_agent` /
141
+ `alineod_resume_agent` to freeze/thaw without losing state.
142
+ 5. `alineod_watch_events` (poll as needed) or `alineod_get_run` to observe progress.
143
+ 6. `alineod_get_result` (optionally with `waitSeconds` to long-poll) to read each settled
144
+ agent's output.
145
+ 7. `alineod_stop_agent` per agent and/or `alineod_delete_run` to tear the whole run down.
146
+
147
+ See [`cookbooks/mcp-agent-swarm`](../../cookbooks/mcp-agent-swarm) for this flow as a complete,
148
+ runnable script — a lead agent forks two reviewers, one gets paused/resumed and the other
149
+ steered mid-turn, and an editor gathers both results into a report, all driven through these
150
+ MCP tools instead of raw HTTP.
151
+
152
+ ## Troubleshooting
153
+
154
+ | Symptom | Cause | Fix |
155
+ | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
156
+ | Every `alineod_*` call returns `alineod error (network): Could not reach alineod...` | alineod isn't running, or `ALINEOD_URL` points at the wrong address | Run `alineo_init` (needs Docker), or check what's actually listening on the configured URL |
157
+ | `alineod error (404): no run ...` / `no agent ...` | Wrong ID, or the run/agent was already deleted/stopped | Re-check the ID from the tool result that created it; `alineod_get_run` lists current agents |
158
+ | `alineod error (409): agent ... is not live` | The agent's sandbox already ended | Check `alineod_get_agent`'s `state`/`outcome` before prompting again |
159
+ | `alineo_init` fails at "Checking Docker..." | Docker isn't installed or the daemon isn't running | Start Docker Desktop (or your Docker daemon) and retry |
160
+ | A spawned agent never produces a result | No model provider key was forwarded to alineod | Set the relevant key (e.g. `NVIDIA_API_KEY`) in the shell _before_ running `alineo_init`, or add it to the running alineod container's env directly |
161
+ | Raw `@alineo-labs/sandbox` SDK code on the host can't follow a sandbox's proxy URL, even though `alineo_init` succeeded | Windows/Mac: alineod reaches OpenSandbox via `host.docker.internal`, which the host itself can't reliably resolve back to itself — see `packages/cli/src/commands/init.ts`'s doc comment | Use `alineod_*` tools instead of the raw SDK against this same OpenSandbox instance, or run OpenSandbox via `uvx opensandbox-server` for direct host-based SDK access |
162
+
163
+ ## Local development
164
+
165
+ ```bash
166
+ bun install
167
+ bun run dev # bun run src/index.ts, stdio server on this process's stdin/stdout
168
+ bun run typecheck
169
+ bun run test
170
+ bun run build # tsdown → dist/index.mjs
171
+ ```
172
+
173
+ `src/server.ts` builds the `McpServer` independently of the stdio transport (`src/index.ts`), so
174
+ tests connect it to an in-memory client over `InMemoryTransport` instead of spawning a process —
175
+ see `test/server.test.ts`.
176
+
177
+ ## Design notes
178
+
179
+ - **stdio, not HTTP.** An MCP client launches this as a subprocess; `stdout` is the JSON-RPC
180
+ channel, so nothing in this package may `console.log` — diagnostics go to `console.error`.
181
+ - **Thin HTTP client, not the `alineo` SDK.** `src/alineod-client.ts` talks to alineod purely
182
+ over its documented wire contract (`apps/alineod/src/schema.ts`,
183
+ `specs/alineod/openapi.json`), the same way any external MCP client would — alineod is
184
+ "standalone by design" (its own README), and this package doesn't reach into its internals.
185
+ - **Every tool handler is error-safe.** A thrown error (alineod unreachable, a 404, invalid
186
+ input) becomes an `isError` tool result, never an uncaught rejection that could take the
187
+ server down mid-session.
188
+ - **`alineod_watch_events` is poll-and-collect, not a live stream.** An MCP tool call is
189
+ request/response; the tool collects SSE events for a bounded window (default 20s, capped at
190
+ 120s) and returns them, honoring `Last-Event-ID` via `sinceEventId` so repeated calls don't
191
+ miss anything persisted.
package/dist/index.mjs ADDED
@@ -0,0 +1,968 @@
1
+ #!/usr/bin/env bun
2
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
+ import { McpServer } from "@modelcontextprotocol/server";
4
+ import { z } from "zod";
5
+ import { join } from "path";
6
+ import { homedir } from "os";
7
+ import { existsSync, readdirSync } from "fs";
8
+ import { mkdir, unlink } from "fs/promises";
9
+ import { validateAgentSpec } from "alineo";
10
+ //#region src/alineod-client.ts
11
+ /**
12
+ * Thin HTTP + SSE client for alineod's wire contract (`apps/alineod/src/schema.ts`,
13
+ * `specs/alineod/openapi.json`). Deliberately typed against the wire contract, not against
14
+ * alineod's internal Zod schemas — alineod is "standalone by design" (its own README) and this
15
+ * package talks to it the same way any external MCP client would: over HTTP.
16
+ *
17
+ * `spec` fields below are `Record<string, unknown>`, not `AgentSpec` from `alineo` — an MCP
18
+ * tool receives arbitrary unvalidated JSON from the caller, and alineod's own wire schema
19
+ * (`apps/alineod/src/schema.ts`'s `AgentSpec = z.record(z.string(), z.unknown())`) treats it
20
+ * the same way: opaque here, validated server-side by the SDK's own `Alineo.load()`/`.spawn()`.
21
+ */
22
+ var AlineodError = class extends Error {
23
+ status;
24
+ constructor(status, message) {
25
+ super(message);
26
+ this.status = status;
27
+ this.name = "AlineodError";
28
+ }
29
+ };
30
+ const DEFAULT_BASE_URL = "http://127.0.0.1:4600";
31
+ var AlineodClient = class {
32
+ baseUrl;
33
+ fetchImpl;
34
+ constructor(opts = {}) {
35
+ this.baseUrl = (opts.baseUrl ?? process.env.ALINEOD_URL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
36
+ this.fetchImpl = opts.fetchImpl ?? fetch;
37
+ }
38
+ async request(method, path, body) {
39
+ let res;
40
+ try {
41
+ res = await this.fetchImpl(`${this.baseUrl}${path}`, {
42
+ method,
43
+ headers: body !== void 0 ? { "content-type": "application/json" } : void 0,
44
+ body: body !== void 0 ? JSON.stringify(body) : void 0
45
+ });
46
+ } catch (err) {
47
+ throw new AlineodError(0, `Could not reach alineod at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}. Is it running? Try the alineo_init tool, or set ALINEOD_URL.`);
48
+ }
49
+ if (res.status === 204) return void 0;
50
+ const text = await res.text();
51
+ const data = text.length > 0 ? JSON.parse(text) : void 0;
52
+ if (!res.ok) {
53
+ const message = data?.error ?? res.statusText;
54
+ throw new AlineodError(res.status, message);
55
+ }
56
+ return data;
57
+ }
58
+ createRun(body) {
59
+ return this.request("POST", "/runs", body);
60
+ }
61
+ getRun(runId) {
62
+ return this.request("GET", `/runs/${encodeURIComponent(runId)}`);
63
+ }
64
+ deleteRun(runId) {
65
+ return this.request("DELETE", `/runs/${encodeURIComponent(runId)}`);
66
+ }
67
+ spawnAgent(runId, body) {
68
+ return this.request("POST", `/runs/${encodeURIComponent(runId)}/agents`, body);
69
+ }
70
+ getAgent(agentId) {
71
+ return this.request("GET", `/agents/${encodeURIComponent(agentId)}`);
72
+ }
73
+ promptAgent(agentId, text) {
74
+ return this.request("POST", `/agents/${encodeURIComponent(agentId)}/prompt`, { text });
75
+ }
76
+ steerAgent(agentId, message) {
77
+ return this.request("POST", `/agents/${encodeURIComponent(agentId)}/steer`, { message });
78
+ }
79
+ pauseAgent(agentId) {
80
+ return this.request("POST", `/agents/${encodeURIComponent(agentId)}/pause`);
81
+ }
82
+ resumeAgent(agentId) {
83
+ return this.request("POST", `/agents/${encodeURIComponent(agentId)}/resume`);
84
+ }
85
+ stopAgent(agentId, mode) {
86
+ return this.request("POST", `/agents/${encodeURIComponent(agentId)}/stop`, mode ? { mode } : void 0);
87
+ }
88
+ getResult(agentId, waitSeconds) {
89
+ const qs = waitSeconds ? `?wait=${encodeURIComponent(String(waitSeconds))}` : "";
90
+ return this.request("GET", `/agents/${encodeURIComponent(agentId)}/result${qs}`);
91
+ }
92
+ /**
93
+ * Collects SSE events from `/runs/:runId/events` for at most `maxWaitMs` (default 20s, capped
94
+ * at 120s) or until `maxEvents` (default 50) have been read, whichever comes first — an MCP
95
+ * tool call is request/response, so this turns the daemon's open-ended stream into a bounded
96
+ * poll-and-collect instead of hanging the connection indefinitely.
97
+ */
98
+ async watchEvents(runId, opts = {}) {
99
+ const maxWaitMs = Math.min(opts.maxWaitMs ?? 2e4, 12e4);
100
+ const maxEvents = opts.maxEvents ?? 50;
101
+ const controller = new AbortController();
102
+ const timer = setTimeout(() => {
103
+ controller.abort();
104
+ }, maxWaitMs);
105
+ let res;
106
+ try {
107
+ res = await this.fetchImpl(`${this.baseUrl}/runs/${encodeURIComponent(runId)}/events`, {
108
+ headers: { "last-event-id": String(opts.sinceEventId ?? 0) },
109
+ signal: controller.signal
110
+ });
111
+ } catch (err) {
112
+ clearTimeout(timer);
113
+ if (err instanceof Error && err.name === "AbortError") return [];
114
+ throw new AlineodError(0, `Could not reach alineod at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}.`);
115
+ }
116
+ if (!res.ok || !res.body) {
117
+ clearTimeout(timer);
118
+ throw new AlineodError(res.status, `Failed to open event stream (${res.status})`);
119
+ }
120
+ const events = [];
121
+ const reader = res.body.getReader();
122
+ const decoder = new TextDecoder();
123
+ let buffer = "";
124
+ try {
125
+ while (events.length < maxEvents) {
126
+ const { value, done } = await reader.read();
127
+ if (done) break;
128
+ buffer += decoder.decode(value, { stream: true });
129
+ let sep;
130
+ while ((sep = buffer.indexOf("\n\n")) !== -1) {
131
+ const frame = buffer.slice(0, sep);
132
+ buffer = buffer.slice(sep + 2);
133
+ const parsed = parseSseFrame(frame);
134
+ if (parsed) events.push(parsed);
135
+ if (events.length >= maxEvents) break;
136
+ }
137
+ }
138
+ } catch (err) {
139
+ if (!(err instanceof Error && err.name === "AbortError")) throw err;
140
+ } finally {
141
+ clearTimeout(timer);
142
+ controller.abort();
143
+ reader.releaseLock();
144
+ }
145
+ return events;
146
+ }
147
+ };
148
+ function parseSseFrame(frame) {
149
+ let id;
150
+ let event = "message";
151
+ const dataLines = [];
152
+ for (const line of frame.split("\n")) {
153
+ if (line.startsWith(":")) continue;
154
+ if (line.startsWith("id:")) id = Number(line.slice(3).trim()) || void 0;
155
+ else if (line.startsWith("event:")) event = line.slice(6).trim();
156
+ else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
157
+ }
158
+ if (dataLines.length === 0) return null;
159
+ let data;
160
+ try {
161
+ data = JSON.parse(dataLines.join("\n"));
162
+ } catch {
163
+ data = dataLines.join("\n");
164
+ }
165
+ return {
166
+ id,
167
+ event,
168
+ data
169
+ };
170
+ }
171
+ //#endregion
172
+ //#region ../cli-shared/dist/index.mjs
173
+ async function spawn(cmd) {
174
+ let proc;
175
+ try {
176
+ proc = Bun.spawn(cmd, {
177
+ stdout: "pipe",
178
+ stderr: "pipe"
179
+ });
180
+ } catch {
181
+ throw new Error(`'${cmd[0]}' not found — is Docker installed?`);
182
+ }
183
+ const [stdout, stderr, exitCode] = await Promise.all([
184
+ new Response(proc.stdout).text(),
185
+ new Response(proc.stderr).text(),
186
+ proc.exited
187
+ ]);
188
+ return {
189
+ ok: exitCode === 0,
190
+ stdout,
191
+ stderr
192
+ };
193
+ }
194
+ async function checkDocker() {
195
+ const { ok, stderr } = await spawn(["docker", "info"]);
196
+ if (!ok) {
197
+ if (stderr.includes("Cannot connect") || stderr.includes("daemon") || stderr.includes("socket")) throw new Error("Docker daemon is not running. Start Docker and try again.");
198
+ throw new Error("Docker is not available. Install Docker and try again.");
199
+ }
200
+ }
201
+ async function getContainerState(name) {
202
+ const { ok, stdout } = await spawn([
203
+ "docker",
204
+ "inspect",
205
+ name,
206
+ "--format",
207
+ "{{.State.Status}}"
208
+ ]);
209
+ if (!ok) return "missing";
210
+ return stdout.trim() === "running" ? "running" : "stopped";
211
+ }
212
+ async function startContainer(name) {
213
+ const { ok, stderr } = await spawn([
214
+ "docker",
215
+ "start",
216
+ name
217
+ ]);
218
+ if (!ok) throw new Error(`Failed to start container '${name}': ${stderr.trim()}`);
219
+ }
220
+ async function restartContainer(name) {
221
+ const { ok, stderr } = await spawn([
222
+ "docker",
223
+ "restart",
224
+ name
225
+ ]);
226
+ if (!ok) throw new Error(`Failed to restart container '${name}': ${stderr.trim()}`);
227
+ }
228
+ /** Force-removes a container regardless of running/stopped state — used to recreate one whose
229
+ * config (network mode, env) needs to change, since `docker run` args can't be applied in place. */
230
+ async function removeContainer(name) {
231
+ const { ok, stderr } = await spawn([
232
+ "docker",
233
+ "rm",
234
+ "-f",
235
+ name
236
+ ]);
237
+ if (!ok) throw new Error(`Failed to remove container '${name}': ${stderr.trim()}`);
238
+ }
239
+ async function runContainer(args, label = "container") {
240
+ const { ok, stderr } = await spawn([
241
+ "docker",
242
+ "run",
243
+ ...args
244
+ ]);
245
+ if (!ok) throw new Error(`Failed to start ${label}: ${stderr.trim()}`);
246
+ }
247
+ async function pullImage(image) {
248
+ const { ok, stderr } = await spawn([
249
+ "docker",
250
+ "pull",
251
+ image
252
+ ]);
253
+ if (!ok) throw new Error(`Failed to pull '${image}': ${stderr.trim()}`);
254
+ }
255
+ /** Default health predicate: OpenSandbox's `/health` returns `{ status: "healthy" }`. */
256
+ const isOpenSandboxHealthy = (body) => body?.status === "healthy";
257
+ async function pollHealth(url, timeoutMs = 6e4, isHealthy = isOpenSandboxHealthy) {
258
+ const deadline = Date.now() + timeoutMs;
259
+ while (Date.now() < deadline) {
260
+ try {
261
+ const res = await fetch(url);
262
+ if (res.ok && isHealthy(await res.json())) return;
263
+ } catch {}
264
+ await new Promise((r) => setTimeout(r, 1e3));
265
+ }
266
+ throw new Error(`${url} did not become healthy within ${timeoutMs / 1e3}s`);
267
+ }
268
+ /** A quick one-shot version of `pollHealth` for deciding whether an already-`running`
269
+ * container is actually reachable, not just started — a container can report "running" to
270
+ * Docker while its service is unreachable (wrong network mode, crashed process, stale config).
271
+ * 10s (not 3s) so a slow-but-healthy service (host under load, cold Bun startup after reboot,
272
+ * bridge networking still settling) doesn't get misread as unreachable and trigger a destructive
273
+ * `docker rm -f` of an otherwise-fine container. */
274
+ async function isReachable(url, isHealthy, timeoutMs = 1e4) {
275
+ try {
276
+ await pollHealth(url, timeoutMs, isHealthy);
277
+ return true;
278
+ } catch {
279
+ return false;
280
+ }
281
+ }
282
+ const CONFIG_DIR = ".alineo";
283
+ const CONFIG_FILE = "alineo.config.json";
284
+ function configPath() {
285
+ return CONFIG_FILE;
286
+ }
287
+ function globalConfigPath() {
288
+ return join(serverConfigDir(), "config.json");
289
+ }
290
+ function fillDefaults(data) {
291
+ return {
292
+ serverUrl: data.serverUrl ?? "http://127.0.0.1:8080",
293
+ useServerProxy: data.useServerProxy ?? true,
294
+ apiKey: data.apiKey ?? "",
295
+ adapterPath: data.adapterPath ?? "./.alineo/ledger.db",
296
+ agentsDir: data.agentsDir ?? "./agents",
297
+ defaults: { resources: {
298
+ cpu: data.defaults?.resources?.cpu ?? "1000m",
299
+ memory: data.defaults?.resources?.memory ?? "1Gi"
300
+ } }
301
+ };
302
+ }
303
+ /**
304
+ * Resolves, in order: a project-local `alineo.config.json` (written by `alineo init`
305
+ * for repos that want their own agents dir / ledger), then a global
306
+ * `~/.config/alineo/config.json`. If neither exists yet, bootstraps the global
307
+ * one so a fresh `bunx alineo-cli` works without requiring `init` in every directory.
308
+ */
309
+ async function readConfig() {
310
+ const localFile = Bun.file(configPath());
311
+ if (await localFile.exists()) return fillDefaults(await localFile.json());
312
+ const globalPath = globalConfigPath();
313
+ const globalFile = Bun.file(globalPath);
314
+ if (await globalFile.exists()) return fillDefaults(await globalFile.json());
315
+ const dir = serverConfigDir();
316
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true });
317
+ const config = {
318
+ serverUrl: "http://127.0.0.1:8080",
319
+ useServerProxy: true,
320
+ apiKey: "",
321
+ adapterPath: join(dir, "ledger.db"),
322
+ agentsDir: join(dir, "agents"),
323
+ defaults: { resources: {
324
+ cpu: "1000m",
325
+ memory: "1Gi"
326
+ } }
327
+ };
328
+ await Bun.write(globalPath, JSON.stringify(config, null, 2) + "\n");
329
+ return config;
330
+ }
331
+ async function writeConfig(config) {
332
+ if (!existsSync(CONFIG_DIR)) await mkdir(CONFIG_DIR, { recursive: true });
333
+ await Bun.write(configPath(), JSON.stringify(config, null, 2) + "\n");
334
+ }
335
+ function serverConfigDir() {
336
+ return join(homedir(), ".config", "alineo");
337
+ }
338
+ function serverConfigPath() {
339
+ return join(serverConfigDir(), "server.toml");
340
+ }
341
+ /**
342
+ * Host directory bind-mounted into the OpenSandbox container at `/data` (see `init.ts`),
343
+ * backing the `[store].path` set below. OpenSandbox itself persists
344
+ * snapshot metadata durably (a SQLite db, meant to survive the server process restarting —
345
+ * see opensandbox-group/OpenSandbox's `PersistedSnapshotService`), but that guarantee is
346
+ * only as good as where the db file actually lives: without this mount, it sits in the
347
+ * `alineo-opensandbox` container's own writable layer, so restart is fine but any time the
348
+ * container itself is recreated (host reboot with no restart policy, `docker system prune`,
349
+ * a stray `docker rm`) silently loses every cached snapshot record — every `Alineo.load()`
350
+ * snapshot fast path pays a full cold rebuild next time, indistinguishable from a genuinely
351
+ * changed spec (see issue #20). Bind-mounting this directory makes that data outlive the
352
+ * container's own lifecycle, matching OpenSandbox's own intent.
353
+ */
354
+ function serverDataDir() {
355
+ return join(serverConfigDir(), "opensandbox-data");
356
+ }
357
+ /**
358
+ * v1.0.19 (the previous pin) predates cached bwrap-archive support, so every sandbox logged
359
+ * "bwrap archive not cached for linux/amd64 -- isolation will be unavailable" and isolation
360
+ * sessions (and anything that depends on them, e.g. pause()/resume()) hung indefinitely
361
+ * instead of failing cleanly. OpenSandbox's own docs: >=v1.0.20 has base isolation-session
362
+ * support, >=v1.0.21 is recommended for full functionality -- the "v1.1.0+" the warning
363
+ * message itself suggests does not exist as a published tag. v1.0.22 is the latest.
364
+ */
365
+ /**
366
+ * `egress.image`/`egress.mode` are configured unconditionally, not opt-in. Per OpenSandbox's
367
+ * own control flow, a configured `egress.image` is inert for any sandbox created without a
368
+ * `networkPolicy` — no sidecar is attached, no behavior changes for anyone not touching
369
+ * `SandboxOptions.networkPolicy`/`credentialProxy`. Without this block, a fresh `alineo init`
370
+ * server rejects any `networkPolicy`/`credentialProxy` request outright with
371
+ * "egress.image must be configured" — this is what closes that gap (see issue #203,
372
+ * plans/credential-injection.md Phase 4). `dns+nft` (rather than `dns`) is required for
373
+ * `credentialProxy`'s Credential Vault to activate at all.
374
+ */
375
+ function serverConfigContent(eip) {
376
+ return `[server]
377
+ host = "0.0.0.0"
378
+ port = 8080
379
+ eip = "${eip}"
380
+
381
+ [runtime]
382
+ type = "docker"
383
+ execd_image = "opensandbox/execd:v1.0.22"
384
+
385
+ [docker]
386
+ network_mode = "bridge"
387
+
388
+ [store]
389
+ type = "sqlite"
390
+ path = "/data/opensandbox.db"
391
+
392
+ [egress]
393
+ image = "opensandbox/egress:v1.1.7"
394
+ mode = "dns+nft"
395
+ `;
396
+ }
397
+ /**
398
+ * Model API key env vars Pi's coding-agent runtime resolves providers from — mirrors the
399
+ * `envMap` in earendil-works/pi's `packages/ai/src/env-api-keys.ts` (plus Anthropic's three,
400
+ * handled separately there). An `AgentSpec`'s env map (`{ NVIDIA_API_KEY: "${NVIDIA_API_KEY}" }`,
401
+ * see `packages/agent/src/schema.ts`) is resolved from `process.env` inside whatever process
402
+ * calls `Alineo.load()`/`.spawn()` — for a swarm run through alineod, that's alineod's own
403
+ * container. `alineo init` forwards whichever of these are set in the operator's shell into
404
+ * that container so any Pi-supported model works, not just NVIDIA's free tier.
405
+ *
406
+ * Deliberately excludes ambient/file-based credential mechanisms (AWS IAM role chains,
407
+ * `AWS_PROFILE`, Google Application Default Credentials) — those need a mounted file or
408
+ * assumed-role wiring, not just a passed-through env var. Amazon Bedrock and Google Vertex
409
+ * are not yet supported by `init`'s auto-start for that reason.
410
+ *
411
+ * Keep in sync with pi's `env-api-keys.ts` `envMap` as it adds providers.
412
+ */
413
+ const PI_MODEL_API_KEY_ENV_VARS = [
414
+ "ANTHROPIC_API_KEY",
415
+ "ANTHROPIC_OAUTH_TOKEN",
416
+ "ANTHROPIC_AUTH_TOKEN",
417
+ "OPENAI_API_KEY",
418
+ "AZURE_OPENAI_API_KEY",
419
+ "GEMINI_API_KEY",
420
+ "NVIDIA_API_KEY",
421
+ "DEEPSEEK_API_KEY",
422
+ "MISTRAL_API_KEY",
423
+ "GROQ_API_KEY",
424
+ "CEREBRAS_API_KEY",
425
+ "XAI_API_KEY",
426
+ "OPENROUTER_API_KEY",
427
+ "AI_GATEWAY_API_KEY",
428
+ "CLOUDFLARE_API_KEY",
429
+ "CLOUDFLARE_ACCOUNT_ID",
430
+ "CLOUDFLARE_GATEWAY_ID",
431
+ "RADIUS_API_KEY",
432
+ "OPENCODE_API_KEY",
433
+ "QWEN_TOKEN_PLAN_API_KEY",
434
+ "QWEN_TOKEN_PLAN_CN_API_KEY",
435
+ "MOONSHOT_API_KEY",
436
+ "KIMI_API_KEY",
437
+ "ZAI_API_KEY",
438
+ "ZAI_CODING_CN_API_KEY",
439
+ "MINIMAX_API_KEY",
440
+ "MINIMAX_CN_API_KEY",
441
+ "XIAOMI_API_KEY",
442
+ "XIAOMI_TOKEN_PLAN_CN_API_KEY",
443
+ "XIAOMI_TOKEN_PLAN_AMS_API_KEY",
444
+ "XIAOMI_TOKEN_PLAN_SGP_API_KEY",
445
+ "ANT_LING_API_KEY",
446
+ "HF_TOKEN",
447
+ "FIREWORKS_API_KEY",
448
+ "TOGETHER_API_KEY",
449
+ "BASETEN_API_KEY",
450
+ "COPILOT_GITHUB_TOKEN"
451
+ ];
452
+ /**
453
+ * `alineo init` / `alineo_init` — starts OpenSandbox + alineod locally via Docker and writes
454
+ * `alineo.config.json`. Shared verbatim by `alineo-cli` (`packages/cli/src/commands/init.ts`,
455
+ * which logs to stdout) and `alineo-mcp` (`packages/mcp/src/init.ts`, which collects a log array
456
+ * instead — an MCP stdio server's stdout is the JSON-RPC channel, so tool handlers must never
457
+ * `console.log`) via the injectable `log` callback, so the two can never drift apart the way two
458
+ * hand-copied files did before.
459
+ */
460
+ const OPENSANDBOX_CONTAINER_NAME = "alineo-opensandbox";
461
+ const SERVER_URL = "http://127.0.0.1:8080";
462
+ const ALINEOD_CONTAINER_NAME = "alineo-alineod";
463
+ const ALINEOD_IMAGE = "ghcr.io/drejt/alineod:latest";
464
+ const ALINEOD_URL = "http://127.0.0.1:4600";
465
+ const isAlineodHealthy = (body) => body?.ok === true;
466
+ const HOST_DOCKER_INTERNAL_SERVER_URL = "http://host.docker.internal:8080";
467
+ /**
468
+ * `--network host` (which makes alineod see `127.0.0.1` exactly as the host does, matching
469
+ * OpenSandbox's configured `eip` — see `ensureAlineod`'s doc comment) only works out of the box
470
+ * on native Linux Docker. Docker Desktop for Windows/Mac ships it behind an opt-in "Enable host
471
+ * networking" setting nothing here can safely toggle (no stable, documented way to flip it and
472
+ * restart Docker Desktop from a CLI); without it, `--network host` containers report "running"
473
+ * but publish no ports the host can reach at all (see the `isReachable` probe below, which is
474
+ * exactly what catches this class of failure). Keying off `process.platform` instead of probing
475
+ * Docker's own networking capabilities is a heuristic, not a guarantee (e.g. Docker Desktop for
476
+ * Linux may behave like Windows/Mac here too) — but it matches how the overwhelming majority of
477
+ * each platform's users actually run Docker. `ensureAlineod` backs this guess with a live
478
+ * reachability probe and falls back to bridge networking on the spot if it's wrong, so a bad
479
+ * guess self-heals instead of leaving alineod permanently unreachable.
480
+ */
481
+ const usesHostNetworking = process.platform !== "win32" && process.platform !== "darwin";
482
+ async function runInit(log) {
483
+ log("Checking Docker...");
484
+ await checkDocker();
485
+ const openSandboxConfigChanged = await ensureServerConfig();
486
+ await ensureServerDataDir();
487
+ const state = await getContainerState(OPENSANDBOX_CONTAINER_NAME);
488
+ if (state === "running") if (openSandboxConfigChanged) {
489
+ log("OpenSandbox networking config changed — restarting to apply it...");
490
+ await restartContainer(OPENSANDBOX_CONTAINER_NAME);
491
+ log("Waiting for OpenSandbox to be ready...");
492
+ await pollHealth(`${SERVER_URL}/health`);
493
+ } else log(`OpenSandbox already running at ${SERVER_URL}`);
494
+ else if (state === "stopped") {
495
+ log("Restarting OpenSandbox container...");
496
+ await startContainer(OPENSANDBOX_CONTAINER_NAME);
497
+ log("Waiting for OpenSandbox to be ready...");
498
+ await pollHealth(`${SERVER_URL}/health`);
499
+ } else {
500
+ log("Starting OpenSandbox in Docker...");
501
+ await runContainer([
502
+ "-d",
503
+ "--name",
504
+ OPENSANDBOX_CONTAINER_NAME,
505
+ "-p",
506
+ "8080:8080",
507
+ "-v",
508
+ "/var/run/docker.sock:/var/run/docker.sock",
509
+ "-v",
510
+ `${serverConfigPath()}:/etc/opensandbox/config.toml:ro`,
511
+ "-v",
512
+ `${serverDataDir()}:/data`,
513
+ "-e",
514
+ "SANDBOX_CONFIG_PATH=/etc/opensandbox/config.toml",
515
+ "-e",
516
+ "OPENSANDBOX_INSECURE_SERVER=YES",
517
+ "opensandbox/server:latest"
518
+ ], "OpenSandbox container");
519
+ log("Waiting for OpenSandbox to be ready...");
520
+ await pollHealth(`${SERVER_URL}/health`);
521
+ }
522
+ await ensureAlineod(log, openSandboxConfigChanged);
523
+ await ensureProjectConfig(log);
524
+ log(`OpenSandbox running at ${SERVER_URL}, alineod running at ${ALINEOD_URL} — ready.`);
525
+ return {
526
+ serverUrl: SERVER_URL,
527
+ alineodUrl: ALINEOD_URL
528
+ };
529
+ }
530
+ /**
531
+ * alineod needs to reach OpenSandbox at the same address OpenSandbox's own configured `eip`
532
+ * uses — that's what it hands back in every sandbox proxy URL (`{eip}/sandboxes/{id}/proxy/{port}`,
533
+ * see `apps/alineod/README.md`'s "Networking caveat"), and alineod follows those literally.
534
+ *
535
+ * - **Linux**: `--network host` puts alineod's `127.0.0.1` in the same namespace as the host's,
536
+ * matching `eip` (`SERVER_URL`, `ensureServerConfig` below) exactly — same as a bare `bun run
537
+ * start` would see. No extra port publishing needed; alineod's own port is already the host's.
538
+ * - **Windows/Mac (Docker Desktop)**: `--network host` doesn't publish container ports to the
539
+ * host at all without a setting this can't safely flip (see `usesHostNetworking`'s doc
540
+ * comment) — every ALINEOD_URL health check would time out, exactly what motivated this split.
541
+ * Instead alineod stays on the default bridge network with an explicit `-p 4600:4600` (so the
542
+ * host can reach *it*) and reaches OpenSandbox via `host.docker.internal`, which Docker
543
+ * Desktop resolves to the host on every container regardless of network mode — no host
544
+ * networking feature required. `ensureServerConfig` sets OpenSandbox's `eip` to the same
545
+ * `host.docker.internal` address so alineod can also follow the proxy URLs it hands back.
546
+ * Trade-off: a host-based client talking to *this same* OpenSandbox instance directly (not
547
+ * through alineod) can no longer follow those proxy URLs either, since the host itself can't
548
+ * reliably resolve `host.docker.internal` back to itself (Windows routes it via the LAN
549
+ * interface, which most local networks don't hairpin NAT back to the same machine) — use `uvx
550
+ * opensandbox-server` instead for that case (see the root CLAUDE.md's "Local OpenSandbox
551
+ * setup").
552
+ */
553
+ async function ensureAlineod(log, openSandboxConfigChanged) {
554
+ const state = await getContainerState(ALINEOD_CONTAINER_NAME);
555
+ if (state !== "missing" && openSandboxConfigChanged) {
556
+ log("OpenSandbox networking config changed — recreating alineod to match...");
557
+ await removeContainer(ALINEOD_CONTAINER_NAME);
558
+ } else if (state === "running") {
559
+ if (await isReachable(`http://127.0.0.1:4600/health`, isAlineodHealthy)) {
560
+ log(`alineod already running at ${ALINEOD_URL}`);
561
+ return;
562
+ }
563
+ log("alineod is running but not reachable — recreating it...");
564
+ await removeContainer(ALINEOD_CONTAINER_NAME);
565
+ } else if (state === "stopped") {
566
+ log("Restarting alineod container...");
567
+ await startContainer(ALINEOD_CONTAINER_NAME);
568
+ log("Waiting for alineod to be ready...");
569
+ await pollHealth(`${ALINEOD_URL}/health`, 6e4, isAlineodHealthy);
570
+ return;
571
+ }
572
+ log(`Pulling ${ALINEOD_IMAGE}...`);
573
+ await pullImage(ALINEOD_IMAGE);
574
+ const foundModelKeys = PI_MODEL_API_KEY_ENV_VARS.filter((name) => process.env[name]);
575
+ const modelKeyArgs = foundModelKeys.flatMap((name) => ["-e", `${name}=${process.env[name]}`]);
576
+ if (foundModelKeys.length > 0) log(`Forwarding model key(s): ${foundModelKeys.join(", ")}`);
577
+ else log("No known model API key found in the environment — alineod will start, but agent specs referencing a provider key will fail until one is set (see any of the env vars in pi-model-keys.ts).");
578
+ log("Starting alineod in Docker...");
579
+ await startAlineodContainer(usesHostNetworking, modelKeyArgs);
580
+ log("Waiting for alineod to be ready...");
581
+ if (usesHostNetworking && !await isReachable(`http://127.0.0.1:4600/health`, isAlineodHealthy)) {
582
+ log("alineod isn't reachable over host networking on this Docker install — falling back to bridge networking + host.docker.internal...");
583
+ await removeContainer(ALINEOD_CONTAINER_NAME);
584
+ if (await ensureServerEip("http://host.docker.internal:8080")) {
585
+ log("OpenSandbox eip changed to match — restarting to apply it...");
586
+ await restartContainer(OPENSANDBOX_CONTAINER_NAME);
587
+ await pollHealth(`${SERVER_URL}/health`);
588
+ }
589
+ await startAlineodContainer(false, modelKeyArgs);
590
+ }
591
+ await pollHealth(`${ALINEOD_URL}/health`, 6e4, isAlineodHealthy);
592
+ }
593
+ function startAlineodContainer(useHostNetworking, modelKeyArgs) {
594
+ const networkArgs = useHostNetworking ? ["--network", "host"] : [
595
+ "-p",
596
+ "4600:4600",
597
+ "--add-host",
598
+ "host.docker.internal:host-gateway"
599
+ ];
600
+ const alineodServerUrl = useHostNetworking ? SERVER_URL : HOST_DOCKER_INTERNAL_SERVER_URL;
601
+ return runContainer([
602
+ "-d",
603
+ "--name",
604
+ ALINEOD_CONTAINER_NAME,
605
+ ...networkArgs,
606
+ "-e",
607
+ `ALINEO_SERVER_URL=${alineodServerUrl}`,
608
+ "-e",
609
+ "ALINEO_USE_SERVER_PROXY=true",
610
+ ...modelKeyArgs,
611
+ "-v",
612
+ "alineod-data:/data",
613
+ ALINEOD_IMAGE
614
+ ], "alineod container");
615
+ }
616
+ /** Ensures `server.toml`'s `eip` matches what this platform needs (see `ensureAlineod`'s doc
617
+ * comment) — returns whether it changed, so callers can restart whatever already-running
618
+ * containers depend on it. */
619
+ async function ensureServerConfig() {
620
+ const dir = serverConfigDir();
621
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true });
622
+ return ensureServerEip(usesHostNetworking ? SERVER_URL : HOST_DOCKER_INTERNAL_SERVER_URL);
623
+ }
624
+ /**
625
+ * Creates `server.toml` from the default template if it doesn't exist yet, or otherwise patches
626
+ * only its `eip = "..."` line in place — the rest of an existing file is left untouched, since
627
+ * its own header comments invite hand-editing it for `networkPolicy`/`credentialProxy`/egress
628
+ * tuning, and clobbering that on every `init` would silently discard it. Returns whether the eip
629
+ * actually changed.
630
+ */
631
+ async function ensureServerEip(eip) {
632
+ const path = serverConfigPath();
633
+ if (!existsSync(path)) {
634
+ await Bun.write(path, serverConfigContent(eip));
635
+ return true;
636
+ }
637
+ const existing = await Bun.file(path).text();
638
+ const eipLine = /^eip\s*=\s*"([^"]*)"/m;
639
+ if (existing.match(eipLine)?.[1] === eip) return false;
640
+ const updated = eipLine.test(existing) ? existing.replace(eipLine, `eip = "${eip}"`) : existing.replace(/^\[server\]/m, `[server]\neip = "${eip}"`);
641
+ await Bun.write(path, updated);
642
+ return true;
643
+ }
644
+ /**
645
+ * Host-side half of the `serverDataDir()` bind mount. `docker run -v` would auto-create
646
+ * a missing host path anyway, but doing it explicitly here matches `ensureServerConfig()`'s
647
+ * pattern and keeps directory creation in one place rather than relying on Docker's
648
+ * legacy-`-v`-specific behavior (unlike `--mount`, which requires the source to pre-exist).
649
+ */
650
+ async function ensureServerDataDir() {
651
+ const dir = serverDataDir();
652
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true });
653
+ }
654
+ async function ensureProjectConfig(log) {
655
+ if (!existsSync(configPath())) {
656
+ await writeConfig({
657
+ serverUrl: SERVER_URL,
658
+ useServerProxy: true,
659
+ apiKey: "",
660
+ adapterPath: "./.alineo/ledger.db",
661
+ agentsDir: "./agents",
662
+ defaults: { resources: {
663
+ cpu: "1000m",
664
+ memory: "1Gi"
665
+ } }
666
+ });
667
+ log("Created alineo.config.json");
668
+ }
669
+ }
670
+ //#endregion
671
+ //#region src/init.ts
672
+ /**
673
+ * `alineo_init` — starts OpenSandbox + alineod locally via Docker and writes
674
+ * `alineo.config.json`. Delegates to `@alineo-labs/cli-shared`'s `runInit`, which `alineo init`
675
+ * (`packages/cli/src/commands/init.ts`) also calls — this collects its log lines into an array
676
+ * instead of writing to stdout, since an MCP stdio server's stdout is the JSON-RPC channel, so
677
+ * tool handlers must never `console.log`.
678
+ */
679
+ async function init() {
680
+ const log = [];
681
+ const { serverUrl, alineodUrl } = await runInit((message) => log.push(message));
682
+ return {
683
+ log,
684
+ serverUrl,
685
+ alineodUrl
686
+ };
687
+ }
688
+ //#endregion
689
+ //#region src/specs.ts
690
+ /**
691
+ * Local agent-spec cache — mirrors `alineo add` / `list` / `remove`
692
+ * (`packages/cli/src/commands/{add,list,remove}.ts`), returning structured results instead of
693
+ * writing to stdout.
694
+ */
695
+ async function addSpec(url, name) {
696
+ return addSpecResolving(url, name, []);
697
+ }
698
+ /**
699
+ * `ancestry` is the chain of `registryDependencies` URLs currently being resolved (not every URL
700
+ * ever seen — a diamond dependency shared by two specs is fine to fetch twice). Checking it
701
+ * before doing any work catches a circular dependency (A→B→A, or a spec depending on itself)
702
+ * before it can stack-overflow or loop unbounded HTTP fetches.
703
+ */
704
+ async function addSpecResolving(url, name, ancestry) {
705
+ if (!url) throw new Error("A spec URL or local file path is required.");
706
+ if (ancestry.includes(url)) throw new Error(`Circular registryDependencies: ${[...ancestry, url].join(" -> ")}`);
707
+ const config = await readConfig();
708
+ const spec = await fetchSpec(url);
709
+ const resolvedDependencies = [];
710
+ for (const depUrl of spec.registryDependencies ?? []) {
711
+ await addSpecResolving(depUrl, void 0, [...ancestry, url]);
712
+ resolvedDependencies.push(depUrl);
713
+ }
714
+ const specName = name ?? spec.name;
715
+ const agentsDir = config.agentsDir;
716
+ if (!existsSync(agentsDir)) await mkdir(agentsDir, { recursive: true });
717
+ const dest = join(agentsDir, `${specName}.json`);
718
+ await Bun.write(dest, JSON.stringify(spec, null, 2) + "\n");
719
+ return {
720
+ name: specName,
721
+ path: dest,
722
+ resolvedDependencies
723
+ };
724
+ }
725
+ async function fetchSpec(url) {
726
+ if (url.startsWith("http://") || url.startsWith("https://")) {
727
+ const res = await fetch(url);
728
+ if (!res.ok) throw new Error(`Failed to fetch spec: ${res.status} ${res.statusText}`);
729
+ return validateAgentSpec(await res.json());
730
+ }
731
+ const file = Bun.file(url);
732
+ if (!await file.exists()) throw new Error(`File not found: ${url}`);
733
+ return validateAgentSpec(await file.json());
734
+ }
735
+ async function listSpecs() {
736
+ const dir = (await readConfig()).agentsDir;
737
+ if (!existsSync(dir)) return [];
738
+ const files = readdirSync(dir).filter((f) => f.endsWith(".json"));
739
+ const specs = [];
740
+ for (const file of files) try {
741
+ const spec = await Bun.file(join(dir, file)).json();
742
+ specs.push({
743
+ name: spec.name ?? file.replace(/\.json$/, ""),
744
+ cli: spec.cli ?? "?",
745
+ description: spec.description ?? spec.title ?? ""
746
+ });
747
+ } catch {
748
+ specs.push({
749
+ name: file.replace(/\.json$/, ""),
750
+ cli: "?",
751
+ description: "(unreadable)"
752
+ });
753
+ }
754
+ return specs;
755
+ }
756
+ async function removeSpec(name) {
757
+ if (!name) throw new Error("A spec name is required.");
758
+ const config = await readConfig();
759
+ const dest = join(config.agentsDir, `${name}.json`);
760
+ if (!existsSync(dest)) throw new Error(`No agent spec named '${name}' in '${config.agentsDir}'.`);
761
+ await unlink(dest);
762
+ }
763
+ //#endregion
764
+ //#region src/server.ts
765
+ /**
766
+ * Builds the MCP server: registers every tool once against a fresh `AlineodClient` +
767
+ * `McpServer` pair. Kept separate from `index.ts` (which owns the stdio transport) so tests can
768
+ * connect a server instance to an in-memory transport without spawning a process.
769
+ */
770
+ function ok(data) {
771
+ return { content: [{
772
+ type: "text",
773
+ text: typeof data === "string" ? data : JSON.stringify(data, null, 2)
774
+ }] };
775
+ }
776
+ function fail(err) {
777
+ return {
778
+ content: [{
779
+ type: "text",
780
+ text: err instanceof AlineodError ? `alineod error (${err.status || "network"}): ${err.message}` : err instanceof Error ? err.message : String(err)
781
+ }],
782
+ isError: true
783
+ };
784
+ }
785
+ /** Wraps a tool handler so a thrown error becomes an `isError` result, never an uncaught rejection. */
786
+ function safe(fn) {
787
+ return async (args) => {
788
+ try {
789
+ return await fn(args);
790
+ } catch (err) {
791
+ return fail(err);
792
+ }
793
+ };
794
+ }
795
+ const BudgetOverride = z.object({
796
+ spawnDepth: z.number().int().nonnegative().optional(),
797
+ maxAgents: z.number().int().nonnegative().optional()
798
+ }).describe("Overrides the spec's own spawnDepth / maxAgents (flag-beats-config).");
799
+ const AgentSpecInput = z.record(z.string(), z.unknown()).describe("An alineo AgentSpec object (validated server-side by alineod's own SDK call).");
800
+ function buildServer(clientOpts = {}) {
801
+ const client = new AlineodClient(clientOpts);
802
+ const server = new McpServer({
803
+ name: "alineo-mcp",
804
+ version: "0.1.0"
805
+ }, { instructions: "Orchestrate swarms of sandboxed coding agents via alineod, alineo's HTTP+SSE control daemon, plus local agent-spec management. Typical flow: alineo_init (once, to start OpenSandbox + alineod locally) → alineo_add_spec / alineo_list_specs to get an AgentSpec → alineod_create_run to start a swarm → alineod_spawn_agent to fan out children → alineod_prompt_agent / alineod_steer_agent to drive them → alineod_watch_events or alineod_get_run to observe progress → alineod_get_result to read a settled agent's output → alineod_stop_agent / alineod_delete_run to tear down. alineod must be reachable (default http://127.0.0.1:4600, override with ALINEOD_URL) for every alineod_* tool; alineo_init starts it." });
806
+ server.registerTool("alineod_create_run", {
807
+ title: "Create a swarm run",
808
+ description: "POST /runs — load the root agent from an AgentSpec, optionally drive one prompt on it. Returns immediately with state \"provisioning\"; poll alineod_get_run for the real state.",
809
+ inputSchema: z.object({
810
+ spec: AgentSpecInput,
811
+ prompt: z.string().optional().describe("If set, drive one turn on the root agent after load."),
812
+ budget: BudgetOverride.optional()
813
+ })
814
+ }, safe(async ({ spec, prompt, budget }) => ok(await client.createRun({
815
+ spec,
816
+ prompt,
817
+ budget
818
+ }))));
819
+ server.registerTool("alineod_get_run", {
820
+ title: "Get a run's spawn tree",
821
+ description: "GET /runs/:runId — the flat list of every agent in the run, with parent pointers and current state.",
822
+ inputSchema: z.object({ runId: z.string().min(1) })
823
+ }, safe(async ({ runId }) => ok(await client.getRun(runId))));
824
+ server.registerTool("alineod_delete_run", {
825
+ title: "Tear down a run",
826
+ description: "DELETE /runs/:runId — abort and close every live agent in the run. The ledger is kept.",
827
+ inputSchema: z.object({ runId: z.string().min(1) })
828
+ }, safe(async ({ runId }) => {
829
+ await client.deleteRun(runId);
830
+ return ok(`Run ${runId} torn down (every live agent aborted and closed).`);
831
+ }));
832
+ server.registerTool("alineod_watch_events", {
833
+ title: "Watch a run's live events",
834
+ description: "GET /runs/:runId/events (SSE) — collects lifecycle events (agent_spawned, agent_state_changed, agent_ended, handle_settled, budget_denied, …) and forwarded harness events (text, tool_start, tool_end, …) for a bounded window, since this is a request/response tool call rather than a live stream. Pass sinceEventId (the last event's `id`) to resume from where you left off without missing anything persisted.",
835
+ inputSchema: z.object({
836
+ runId: z.string().min(1),
837
+ sinceEventId: z.number().int().nonnegative().optional().describe("Resume after this ledger seq (Last-Event-ID)."),
838
+ maxWaitSeconds: z.number().int().min(1).max(120).optional().describe("Default 20, capped at 120."),
839
+ maxEvents: z.number().int().min(1).max(500).optional().describe("Default 50.")
840
+ })
841
+ }, safe(async ({ runId, sinceEventId, maxWaitSeconds, maxEvents }) => ok(await client.watchEvents(runId, {
842
+ sinceEventId,
843
+ maxWaitMs: maxWaitSeconds !== void 0 ? maxWaitSeconds * 1e3 : void 0,
844
+ maxEvents
845
+ }))));
846
+ server.registerTool("alineod_spawn_agent", {
847
+ title: "Spawn a child agent",
848
+ description: "POST /runs/:runId/agents — fork a new child under a live parent. Set waitFor to hold the spawn until other agents' results settle (their output is written into the child's sandbox before it starts).",
849
+ inputSchema: z.object({
850
+ runId: z.string().min(1),
851
+ spec: AgentSpecInput,
852
+ parentAgentId: z.string().min(1),
853
+ waitFor: z.array(z.string()).optional().describe("Agent IDs whose handles must settle before this spawn proceeds."),
854
+ prompt: z.string().optional(),
855
+ budget: BudgetOverride.optional(),
856
+ idempotencyKey: z.string().optional().describe("A retried call with the same key returns the original spawn.")
857
+ })
858
+ }, safe(async ({ runId, spec, parentAgentId, waitFor, prompt, budget, idempotencyKey }) => ok(await client.spawnAgent(runId, {
859
+ spec,
860
+ parentAgentId,
861
+ waitFor,
862
+ prompt,
863
+ budget,
864
+ idempotencyKey
865
+ }))));
866
+ server.registerTool("alineod_get_agent", {
867
+ title: "Inspect an agent",
868
+ description: "GET /agents/:agentId — the agent's current view plus session stats (token usage, cost, message counts) when live and not paused.",
869
+ inputSchema: z.object({ agentId: z.string().min(1) })
870
+ }, safe(async ({ agentId }) => ok(await client.getAgent(agentId))));
871
+ server.registerTool("alineod_prompt_agent", {
872
+ title: "Prompt an agent",
873
+ description: "POST /agents/:agentId/prompt — drive one turn. Returns immediately (202); poll alineod_get_result or alineod_watch_events for the reply.",
874
+ inputSchema: z.object({
875
+ agentId: z.string().min(1),
876
+ text: z.string().min(1)
877
+ })
878
+ }, safe(async ({ agentId, text }) => {
879
+ await client.promptAgent(agentId, text);
880
+ return ok(`Prompt accepted for agent ${agentId}.`);
881
+ }));
882
+ server.registerTool("alineod_steer_agent", {
883
+ title: "Steer an agent's current turn",
884
+ description: "POST /agents/:agentId/steer — inject a message into the agent's in-flight turn (lands at the next turn boundary). The named agent only, never a subtree.",
885
+ inputSchema: z.object({
886
+ agentId: z.string().min(1),
887
+ message: z.string().min(1)
888
+ })
889
+ }, safe(async ({ agentId, message }) => {
890
+ await client.steerAgent(agentId, message);
891
+ return ok(`Steer message accepted for agent ${agentId}.`);
892
+ }));
893
+ server.registerTool("alineod_pause_agent", {
894
+ title: "Pause an agent",
895
+ description: "POST /agents/:agentId/pause — freeze the agent's sandbox container.",
896
+ inputSchema: z.object({ agentId: z.string().min(1) })
897
+ }, safe(async ({ agentId }) => {
898
+ await client.pauseAgent(agentId);
899
+ return ok(`Agent ${agentId} pausing.`);
900
+ }));
901
+ server.registerTool("alineod_resume_agent", {
902
+ title: "Resume a paused agent",
903
+ description: "POST /agents/:agentId/resume — thaw a paused sandbox container.",
904
+ inputSchema: z.object({ agentId: z.string().min(1) })
905
+ }, safe(async ({ agentId }) => {
906
+ await client.resumeAgent(agentId);
907
+ return ok(`Agent ${agentId} resuming.`);
908
+ }));
909
+ server.registerTool("alineod_stop_agent", {
910
+ title: "Stop an agent",
911
+ description: "POST /agents/:agentId/stop — abort and close one agent. mode defaults to \"abort\" (\"drain\" currently behaves the same).",
912
+ inputSchema: z.object({
913
+ agentId: z.string().min(1),
914
+ mode: z.enum(["abort", "drain"]).optional()
915
+ })
916
+ }, safe(async ({ agentId, mode }) => {
917
+ await client.stopAgent(agentId, mode);
918
+ return ok(`Agent ${agentId} stopping (mode: ${mode ?? "abort"}).`);
919
+ }));
920
+ server.registerTool("alineod_get_result", {
921
+ title: "Get an agent's result",
922
+ description: "GET /agents/:agentId/result — resolve a settled agent's output. Pass waitSeconds to long-poll (server-held) until it settles or the timeout elapses, instead of polling yourself.",
923
+ inputSchema: z.object({
924
+ agentId: z.string().min(1),
925
+ waitSeconds: z.number().int().min(0).max(240).optional().describe("Server-side long-poll bound, capped at 240.")
926
+ })
927
+ }, safe(async ({ agentId, waitSeconds }) => ok(await client.getResult(agentId, waitSeconds))));
928
+ server.registerTool("alineo_init", {
929
+ title: "Start OpenSandbox + alineod locally",
930
+ description: "Starts OpenSandbox and alineod in Docker (pulling images if needed) and writes alineo.config.json in the current directory if missing. Run this once before any alineod_* tool if alineod isn't already running. Requires Docker.",
931
+ inputSchema: z.object({})
932
+ }, safe(async () => ok(await init())));
933
+ server.registerTool("alineo_add_spec", {
934
+ title: "Add an agent spec",
935
+ description: "Fetches an AgentSpec from a URL or local file path, validates it, and saves it to the local agent-spec cache (recursively resolving registryDependencies). The saved spec's object is what alineod_create_run / alineod_spawn_agent expect as `spec`.",
936
+ inputSchema: z.object({
937
+ url: z.string().min(1).describe("An https:// URL or a local file path to an AgentSpec JSON file."),
938
+ name: z.string().optional().describe("Override the spec's own name for the saved filename.")
939
+ })
940
+ }, safe(async ({ url, name }) => ok(await addSpec(url, name))));
941
+ server.registerTool("alineo_list_specs", {
942
+ title: "List saved agent specs",
943
+ description: "Lists every AgentSpec saved locally via alineo_add_spec.",
944
+ inputSchema: z.object({})
945
+ }, safe(async () => ok(await listSpecs())));
946
+ server.registerTool("alineo_remove_spec", {
947
+ title: "Remove a saved agent spec",
948
+ description: "Deletes a locally saved AgentSpec by name.",
949
+ inputSchema: z.object({ name: z.string().min(1) })
950
+ }, safe(async ({ name }) => {
951
+ await removeSpec(name);
952
+ return ok(`Removed agent spec '${name}'.`);
953
+ }));
954
+ return server;
955
+ }
956
+ //#endregion
957
+ //#region src/index.ts
958
+ /**
959
+ * Entry point: serves the MCP server built in server.ts over stdio, the transport an MCP
960
+ * client (Claude Code, Claude Desktop, Cursor, …) launches this process with. stdout is the
961
+ * JSON-RPC channel here — nothing in this package may `console.log`; use console.error (stderr)
962
+ * for anything diagnostic.
963
+ */
964
+ serveStdio(() => buildServer(), { onerror: (err) => {
965
+ console.error(`[alineo-mcp] ${err.message}`);
966
+ } });
967
+ //#endregion
968
+ export {};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "alineo-mcp",
3
+ "version": "0.2.0",
4
+ "description": "MCP server exposing alineod's swarm-control API (and local agent-spec management) as tools for MCP clients (Claude Code, Claude Desktop, Cursor, …).",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/DrejT/alineo.git",
9
+ "directory": "packages/mcp"
10
+ },
11
+ "bin": {
12
+ "alineo-mcp": "./dist/index.mjs"
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "type": "module",
18
+ "exports": {
19
+ ".": {
20
+ "import": "./dist/index.mjs"
21
+ }
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "provenance": true
26
+ },
27
+ "scripts": {
28
+ "build": "tsdown",
29
+ "dev": "bun run src/index.ts",
30
+ "test": "bun test",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "dependencies": {
34
+ "@modelcontextprotocol/server": "^2.0.0",
35
+ "alineo": "0.6.0",
36
+ "zod": "^4"
37
+ },
38
+ "devDependencies": {
39
+ "@alineo-labs/cli-shared": "0.0.1",
40
+ "@modelcontextprotocol/client": "^2.0.0",
41
+ "bun-types": "1.3.14",
42
+ "tsdown": "0.22.3",
43
+ "typescript": "6.0.3"
44
+ }
45
+ }