constructor-research-mcp 0.4.2 → 0.6.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.
package/INSTALL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Install the Constructor Research MCP
2
2
 
3
- The MCP lets Claude Code, Codex or OpenCode deploy apps to Constructor Research: constructor.app, or your organisation's Constructor, such as acme.constructor.app. It runs on your machine as a local MCP server, installed from npm, and works with your personal Constructor access key.
3
+ The MCP lets Claude Code, Codex, OpenCode, jcode, Cline, Cursor or Gemini CLI deploy apps to Constructor Research: constructor.app, or your organisation's Constructor, such as acme.constructor.app. It runs on your machine as a local MCP server, installed from npm, and works with your personal Constructor access key.
4
4
 
5
5
  ## What you need
6
6
 
@@ -8,7 +8,35 @@ The MCP lets Claude Code, Codex or OpenCode deploy apps to Constructor Research:
8
8
  - a personal access key (`rk-…`) for your Constructor
9
9
  - macOS, Windows or Linux
10
10
 
11
- ## 1. Add it to your tool, with your key
11
+ ## The quick way: one command
12
+
13
+ In a terminal (not inside an agent), run:
14
+
15
+ ```sh
16
+ npx -y constructor-research-mcp@latest install
17
+ ```
18
+
19
+ 1. It lists the coding agents it found. Keep them, or choose **Customize…** to add or remove some.
20
+ 2. **Install location**: **Project** (this folder only) or **Global** (every project). Cline has only a global setting.
21
+ 3. **Where do you have access to Constructor Research?** constructor.app, or your organisation's separate instance (type its address, e.g. `acme.constructor.app`).
22
+ 4. It shows the link where you create an access key. Paste the key; it is not shown, it is checked with Constructor and saved to `~/.config/constructor-research/access-key.json` (readable only by you).
23
+ 5. Confirm, and it adds the MCP to each agent. The entry runs `npx -y constructor-research-mcp@latest` and contains no key. A settings file it changes is copied to `<file>.constructor-backup` the first time. An older `constructor-research` entry, for example one with the key in its settings, is replaced.
24
+
25
+ Then restart the agents. Settings files with comments (JSONC) are left untouched; add the entry by hand as below.
26
+
27
+ | Agent | Global | Project |
28
+ | ----------- | ------------------------------------------------------------------------------ | ----------------------- |
29
+ | Claude Code | `~/.claude.json` (through `claude mcp add-json` when the CLI works) | `.mcp.json` |
30
+ | Codex | `~/.codex/config.toml` | `.codex/config.toml` |
31
+ | OpenCode | `~/.config/opencode/opencode.json` (1.x and 2.x layouts) | `opencode.json` |
32
+ | jcode | `~/.jcode/mcp.json` | `.jcode/mcp.json` |
33
+ | Cline | `~/.cline/data/settings/cline_mcp_settings.json` (VS Code 4.x, JetBrains, CLI) | none |
34
+ | Cursor | `~/.cursor/mcp.json` | `.cursor/mcp.json` |
35
+ | Gemini CLI | `~/.gemini/settings.json` | `.gemini/settings.json` |
36
+
37
+ For scripts: `install -y --agents=claude,codex --scope=global --constructor=https://acme.constructor.app --key-stdin` reads the key from stdin (or `CONSTRUCTOR_ACCESS_KEY`); the key is never accepted as an argument.
38
+
39
+ ## 1. By hand: add it to your tool, with your key
12
40
 
13
41
  The key is required: the MCP does nothing without it. The address is `https://constructor.app`; if your organisation has its own Constructor, use its address instead (e.g. `https://acme.constructor.app`). Replace `rk-your-key` with your key.
14
42
 
package/README.md CHANGED
@@ -1,12 +1,26 @@
1
1
  # Constructor Research MCP
2
2
 
3
+ > **0.6:** a registry `image` the project does not have is added to it as an external image, with no desk and no build; Constructor refuses a bad one at once, with its reason.
4
+ >
5
+ > **0.5:** one command sets it up: `npx -y constructor-research-mcp@latest install` finds your coding agents, saves your access key and adds the MCP to each of them.
6
+ >
3
7
  > **0.4:** works with Constructor's public API and a personal access key (`rk-…`); browser sign-in is gone. On a Constructor without the public API yet, pin the previous version: `constructor-research-mcp@0.3.3`.
4
8
 
5
- Local stdio MCP for Codex CLI, Claude Code and OpenCode. Submit the whole application once; the MCP builds images, connects services, configures them and starts them. The agent supplies missing configuration and reports the result.
9
+ Local stdio MCP for Codex CLI, Claude Code, OpenCode, jcode, Cline, Cursor and Gemini CLI. Submit the whole application once; the MCP builds images, connects services, configures them and starts them. The agent supplies missing configuration and reports the result.
6
10
 
7
11
  ## Install
8
12
 
9
- You need Node.js 22+ and your personal access key (`rk-…`); the MCP does not work without it. Add the MCP with the key; the address is `https://constructor.app` unless your organisation has its own Constructor (e.g. `https://acme.constructor.app`).
13
+ You need Node.js 22+ and your personal access key (`rk-…`); the MCP does not work without it. In a terminal, run:
14
+
15
+ ```sh
16
+ npx -y constructor-research-mcp@latest install
17
+ ```
18
+
19
+ It finds the coding agents on your machine (Claude Code, Codex, OpenCode, jcode, Cline, Cursor, Gemini CLI), asks which of them to set up and whether for this project or globally, and where you use Constructor Research (constructor.app or your organisation's instance). It then links to the page where you create an access key, takes the key hidden, checks it with Constructor and saves it to the key file below. Each agent gets an entry that runs `npx -y constructor-research-mcp@latest` and holds no key. Every settings file it changes is first copied to `<file>.constructor-backup`; `--verbose` shows the files and entries, `--dry-run` changes nothing, `--help` lists the options for scripted installs. Then restart the agents.
20
+
21
+ ### By hand
22
+
23
+ Add the MCP with the key; the address is `https://constructor.app` unless your organisation has its own Constructor (e.g. `https://acme.constructor.app`).
10
24
 
11
25
  **Claude Code**
12
26
 
@@ -179,7 +193,7 @@ Private DNS works between containers; browser JavaScript needs a public backend
179
193
 
180
194
  Replace a service's `build` with `"image_id":"IMAGE_ID"` to skip building, or with `"image":"registry/repo:tag"` to run a registry image unchanged, such as `jgraph/drawio:latest` from Docker Hub. Which of `build`, `image` and `image_id` fits is the agent's choice; the tool descriptions say what each one does. `list_images` returns compact records with `source` (`desk_build` or `external`), `reference` and `build_status` (`not_started`, `snapshot_creation`, `in_progress`, `done` or `error`); `detailed:true` returns full records.
181
195
 
182
- With `image`, the MCP first looks for it in the project (by `reference` or name). External images there (`source: external`) are pulled, not built, so they are used whatever their build status, unless it is `error`. An image the project does not have is built on the desk from a one-line `FROM <image>` Dockerfile that the MCP writes to `.constructor/images/<name>/`, because the public API cannot add an external image yet.
196
+ With `image`, the MCP first looks for it in the project (by `reference` or name). External images there (`source: external`) are pulled, not built, so they are used whatever their build status, unless it is `error`. An image the project does not have is added to the project as an external image (`POST /projects/{id}/images/external`): no desk, no upload, no build. Constructor reads the image manifest at once and refuses a missing tag, a private image, an image without a `linux/amd64` variant or a malformed reference; the MCP then returns `image_refused` with Constructor's reason and creates nothing else. Docker Hub references are sent in the short form (`docker.io/library/nginx:1.27` becomes `nginx:1.27`), which Constructor requires for now. A reference without a tag means `latest`, which moves: the result then carries `image_warnings`. On a Constructor without this endpoint, the MCP falls back to building the image on the desk from a one-line `FROM <image>` Dockerfile in `.constructor/images/<name>/`.
183
197
 
184
198
  - Build storage is omitted by default, using the API's documented **50 GB** default. Explicit `ephemeral_build_disk_size_gb` overrides must be **10–1000 GB**.
185
199
  - Each service can have multiple ports (1–65535), with at most **one public port**. That port must match where the container listens.
@@ -0,0 +1,72 @@
1
+ export declare const SERVER = "constructor-research";
2
+ export declare const PACKAGE_SPEC = "constructor-research-mcp@latest";
3
+ export type Scope = "project" | "global";
4
+ export type Kind = "claude" | "codex" | "opencode" | "cline" | "jcode" | "mcpServers";
5
+ export interface Spec {
6
+ command: string;
7
+ args: string[];
8
+ }
9
+ type Env = NodeJS.ProcessEnv;
10
+ /** The command every agent runs. On Windows npx is a .cmd script, which agents start through cmd. */
11
+ export declare function mcpCommand(platform?: NodeJS.Platform): Spec;
12
+ export interface Agent {
13
+ id: string;
14
+ label: string;
15
+ hint?: string;
16
+ kind: Kind;
17
+ /** The agent has no project-level MCP settings. */
18
+ globalOnly?: boolean;
19
+ /** Folders whose presence means the agent is installed (`also`: older locations). */
20
+ dirs(home: string, cwd: string, env: Env): Dirs;
21
+ file(scope: Scope, home: string, cwd: string, env: Env): string;
22
+ }
23
+ interface Dirs {
24
+ global?: string;
25
+ project?: string;
26
+ also?: string[];
27
+ }
28
+ export declare const AGENTS: Agent[];
29
+ export interface Detection {
30
+ agent: Agent;
31
+ scope: Scope;
32
+ path: string;
33
+ }
34
+ /** Every agent settings folder under the project or the home folder, project first. */
35
+ export declare function detect(home?: string, cwd?: string, env?: NodeJS.ProcessEnv): Detection[];
36
+ export type Status = "added" | "updated" | "already" | "skipped" | "failed";
37
+ export interface Result {
38
+ status: Status;
39
+ note?: string;
40
+ }
41
+ export declare const succeeded: (r: Result) => boolean;
42
+ /** The entry as each agent expects it. */
43
+ export declare function entryFor(kind: Kind, spec: Spec, opencodeV2?: boolean): object;
44
+ /** Codex: the first npx start downloads the package and can exceed Codex's 10 s start limit. */
45
+ export declare const tomlBlock: ({ command, args }: Spec) => string;
46
+ /** What will be written, for --verbose. */
47
+ export declare function describe(kind: Kind, spec: Spec, opencodeV2?: boolean): string[];
48
+ /** Merge the entry into a JSON settings file; files that are not plain JSON are left untouched. */
49
+ export declare function mergeJson(path: string, kind: Kind, spec: Spec, scope: Scope, opencodeMajor?: number): Result;
50
+ /**
51
+ * Codex: replace our [mcp_servers.constructor-research] table and its sub-tables (such as an
52
+ * older .env table carrying the key) with the new entry; every other line stays as it was. The
53
+ * result is parsed and compared with the original: unless only our entry changed, nothing is
54
+ * written.
55
+ */
56
+ export declare function writeToml(path: string, spec: Spec, scope: Scope): Result;
57
+ /**
58
+ * Whether Claude Code's CLI can add the entry. Without it the setup edits ~/.claude.json
59
+ * directly, which a running Claude Code may overwrite: the user should quit it first.
60
+ */
61
+ export declare const claudeCliWorks: (env?: Env) => boolean;
62
+ export interface ApplyOptions {
63
+ cwd: string;
64
+ home: string;
65
+ /** The environment for the settings locations and the agents' own CLIs. */
66
+ env: Env;
67
+ /** Let the agents' CLIs write or check the entry where they can. */
68
+ useClis?: boolean;
69
+ }
70
+ /** Writes the entry for one agent; never throws. */
71
+ export declare function applyEntry(agent: Agent, scope: Scope, spec: Spec, o: ApplyOptions): Result;
72
+ export {};
package/dist/agents.js ADDED
@@ -0,0 +1,483 @@
1
+ // Coding agents the setup command knows: how each is detected, where its MCP settings live, and
2
+ // how the constructor-research entry is written. The entry never carries the access key: the MCP
3
+ // reads the key and its Constructor from the key file.
4
+ //
5
+ // Locations checked against each agent's docs or source (Nov 2026): Claude Code, Codex, OpenCode
6
+ // 1.x/2.x, jcode 0.99 (crates/jcode-base/src/mcp/protocol.rs), Cline 4.x / CLI 3.x
7
+ // (sdk/packages/shared/src/storage/paths.ts), Cursor, Gemini CLI.
8
+ import { spawnSync } from "node:child_process";
9
+ import { randomBytes } from "node:crypto";
10
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { basename, dirname, join } from "node:path";
13
+ import { isDeepStrictEqual } from "node:util";
14
+ import { parse as parseToml } from "smol-toml";
15
+ export const SERVER = "constructor-research";
16
+ export const PACKAGE_SPEC = "constructor-research-mcp@latest";
17
+ /** The command every agent runs. On Windows npx is a .cmd script, which agents start through cmd. */
18
+ export function mcpCommand(platform = process.platform) {
19
+ return platform === "win32"
20
+ ? { command: "cmd", args: ["/c", "npx", "-y", PACKAGE_SPEC] }
21
+ : { command: "npx", args: ["-y", PACKAGE_SPEC] };
22
+ }
23
+ const set = (v) => v?.trim() || undefined;
24
+ const claudeDir = (home, env) => set(env.CLAUDE_CONFIG_DIR) ?? join(home, ".claude");
25
+ const codexDir = (home, env) => set(env.CODEX_HOME) ?? join(home, ".codex");
26
+ const opencodeDir = (home, env) => set(env.OPENCODE_CONFIG_DIR) ??
27
+ join(set(env.XDG_CONFIG_HOME) ?? join(home, ".config"), "opencode");
28
+ const jcodeDir = (home, env) => set(env.JCODE_HOME) ?? join(home, ".jcode");
29
+ // Cline 4.x (VS Code), JetBrains and the Cline CLI share one file under ~/.cline.
30
+ const clineDir = (home, env) => set(env.CLINE_DIR) ?? join(home, ".cline");
31
+ const clineFile = (home, env) => set(env.CLINE_MCP_SETTINGS_PATH) ??
32
+ join(set(env.CLINE_DATA_DIR) ?? join(clineDir(home, env), "data"), "settings", "cline_mcp_settings.json");
33
+ // Before 4.x Cline kept its settings in VS Code's extension storage; 4.x moves them to ~/.cline.
34
+ const clineLegacyDir = (home, env) => {
35
+ const storage = join("Code", "User", "globalStorage", "saoudrizwan.claude-dev");
36
+ if (process.platform === "darwin")
37
+ return join(home, "Library", "Application Support", storage);
38
+ if (process.platform === "win32")
39
+ return join(set(env.APPDATA) ?? join(home, "AppData", "Roaming"), storage);
40
+ return join(home, ".config", storage);
41
+ };
42
+ export const AGENTS = [
43
+ {
44
+ id: "claude",
45
+ label: "Claude Code",
46
+ kind: "claude",
47
+ dirs: (home, cwd, env) => ({
48
+ global: claudeDir(home, env),
49
+ project: join(cwd, ".claude"),
50
+ }),
51
+ // With CLAUDE_CONFIG_DIR set, Claude Code keeps .claude.json inside that folder.
52
+ file: (scope, home, cwd, env) => scope === "project"
53
+ ? join(cwd, ".mcp.json")
54
+ : set(env.CLAUDE_CONFIG_DIR)
55
+ ? join(env.CLAUDE_CONFIG_DIR.trim(), ".claude.json")
56
+ : join(home, ".claude.json"),
57
+ },
58
+ {
59
+ id: "codex",
60
+ label: "Codex",
61
+ kind: "codex",
62
+ dirs: (home, cwd, env) => ({
63
+ global: codexDir(home, env),
64
+ project: join(cwd, ".codex"),
65
+ }),
66
+ file: (scope, home, cwd, env) => scope === "project"
67
+ ? join(cwd, ".codex", "config.toml")
68
+ : join(codexDir(home, env), "config.toml"),
69
+ },
70
+ {
71
+ id: "opencode",
72
+ label: "OpenCode",
73
+ kind: "opencode",
74
+ dirs: (home, cwd, env) => ({
75
+ global: opencodeDir(home, env),
76
+ project: join(cwd, ".opencode"),
77
+ }),
78
+ file: (scope, home, cwd, env) => scope === "project"
79
+ ? join(cwd, "opencode.json")
80
+ : join(opencodeDir(home, env), "opencode.json"),
81
+ },
82
+ {
83
+ id: "jcode",
84
+ label: "jcode",
85
+ kind: "jcode",
86
+ dirs: (home, cwd, env) => ({
87
+ global: jcodeDir(home, env),
88
+ project: join(cwd, ".jcode"),
89
+ }),
90
+ file: (scope, home, cwd, env) => scope === "project"
91
+ ? join(cwd, ".jcode", "mcp.json")
92
+ : join(jcodeDir(home, env), "mcp.json"),
93
+ },
94
+ {
95
+ id: "cline",
96
+ label: "Cline",
97
+ hint: "VS Code, JetBrains, CLI",
98
+ kind: "cline",
99
+ globalOnly: true,
100
+ dirs: (home, _cwd, env) => ({
101
+ global: clineDir(home, env),
102
+ also: [clineLegacyDir(home, env)],
103
+ }),
104
+ file: (_scope, home, _cwd, env) => clineFile(home, env),
105
+ },
106
+ {
107
+ id: "cursor",
108
+ label: "Cursor",
109
+ kind: "mcpServers",
110
+ dirs: (home, cwd) => ({
111
+ global: join(home, ".cursor"),
112
+ project: join(cwd, ".cursor"),
113
+ }),
114
+ file: (scope, home, cwd) => join(scope === "project" ? cwd : home, ".cursor", "mcp.json"),
115
+ },
116
+ {
117
+ id: "gemini",
118
+ label: "Gemini CLI",
119
+ kind: "mcpServers",
120
+ dirs: (home, cwd) => ({
121
+ global: join(home, ".gemini"),
122
+ project: join(cwd, ".gemini"),
123
+ }),
124
+ file: (scope, home, cwd) => join(scope === "project" ? cwd : home, ".gemini", "settings.json"),
125
+ },
126
+ ];
127
+ const isDir = (p) => {
128
+ try {
129
+ return statSync(p).isDirectory();
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ };
135
+ /** Every agent settings folder under the project or the home folder, project first. */
136
+ export function detect(home = homedir(), cwd = process.cwd(), env = process.env) {
137
+ const found = [];
138
+ for (const agent of AGENTS) {
139
+ const d = agent.dirs(home, cwd, env);
140
+ if (d.project && d.project !== d.global && isDir(d.project))
141
+ found.push({ agent, scope: "project", path: d.project });
142
+ const g = [d.global, ...(d.also ?? [])].find((p) => p && isDir(p));
143
+ if (g)
144
+ found.push({ agent, scope: "global", path: g });
145
+ }
146
+ return found;
147
+ }
148
+ export const succeeded = (r) => r.status === "added" || r.status === "updated" || r.status === "already";
149
+ /** The entry as each agent expects it. */
150
+ export function entryFor(kind, spec, opencodeV2 = false) {
151
+ const { command, args } = spec;
152
+ switch (kind) {
153
+ case "claude":
154
+ return { type: "stdio", command, args, env: {} };
155
+ case "opencode":
156
+ return opencodeV2
157
+ ? { type: "local", command: [command, ...args] }
158
+ : { type: "local", command: [command, ...args], enabled: true };
159
+ case "cline":
160
+ return { type: "stdio", command, args, disabled: false };
161
+ default:
162
+ return { command, args };
163
+ }
164
+ }
165
+ const tomlString = (s) => JSON.stringify(s);
166
+ /** Codex: the first npx start downloads the package and can exceed Codex's 10 s start limit. */
167
+ export const tomlBlock = ({ command, args }) => `[mcp_servers.${SERVER}]\ncommand = ${tomlString(command)}\nargs = [${args.map(tomlString).join(", ")}]\nstartup_timeout_sec = 60\n`;
168
+ /** What will be written, for --verbose. */
169
+ export function describe(kind, spec, opencodeV2 = false) {
170
+ if (kind === "codex")
171
+ return tomlBlock(spec).trimEnd().split("\n");
172
+ const entry = { [SERVER]: entryFor(kind, spec, opencodeV2) };
173
+ const body = kind === "opencode"
174
+ ? { mcp: opencodeV2 ? { servers: entry } : entry }
175
+ : { mcpServers: entry };
176
+ return JSON.stringify(body, null, 2).split("\n");
177
+ }
178
+ /** A symlinked settings file (dotfiles) is written through, not replaced by a plain file. */
179
+ function target(file) {
180
+ try {
181
+ return realpathSync(file);
182
+ }
183
+ catch {
184
+ return file;
185
+ }
186
+ }
187
+ /** Access keys as they appear in settings; a backup never keeps one. */
188
+ const KEY_PATTERN = /rk-[A-Za-z0-9_\-.~+/=]{8,}/g;
189
+ /**
190
+ * The file as it was before this setup first changed it, kept once (later runs keep the
191
+ * original), readable only by the user, with any access key in it replaced: older setups put
192
+ * the key into the agent's settings, and a backup in a project folder could end up in git.
193
+ */
194
+ function backupOnce(file) {
195
+ if (!existsSync(file))
196
+ return undefined;
197
+ const backup = `${file}.constructor-backup`;
198
+ if (!existsSync(backup))
199
+ writeFileSync(backup, readFileSync(file, "utf8").replace(KEY_PATTERN, "rk-REMOVED"), { mode: 0o600, flag: "wx" });
200
+ return basename(backup);
201
+ }
202
+ /** Replace the file in one step, keeping its permissions; new files: 600 global, 644 project. */
203
+ function writeAtomic(file, text, scope) {
204
+ mkdirSync(dirname(file), { recursive: true });
205
+ let mode = scope === "global" ? 0o600 : 0o644;
206
+ try {
207
+ mode = statSync(file).mode & 0o777;
208
+ }
209
+ catch { }
210
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
211
+ writeFileSync(tmp, text, { mode, flag: "wx" });
212
+ try {
213
+ renameSync(tmp, file);
214
+ }
215
+ catch (err) {
216
+ rmSync(tmp, { force: true });
217
+ throw err;
218
+ }
219
+ }
220
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
221
+ /** Merge the entry into a JSON settings file; files that are not plain JSON are left untouched. */
222
+ export function mergeJson(path, kind, spec, scope, opencodeMajor) {
223
+ const file = target(path);
224
+ let data = {};
225
+ if (existsSync(file)) {
226
+ let parsed;
227
+ try {
228
+ const text = readFileSync(file, "utf8");
229
+ parsed = text.trim() ? JSON.parse(text) : {};
230
+ }
231
+ catch {
232
+ return {
233
+ status: "skipped",
234
+ note: `${file} is not plain JSON (comments?); left untouched`,
235
+ };
236
+ }
237
+ if (!isObject(parsed))
238
+ return {
239
+ status: "skipped",
240
+ note: `${file} is not a JSON object; left untouched`,
241
+ };
242
+ data = parsed;
243
+ }
244
+ let holder;
245
+ let v2 = false;
246
+ if (kind === "opencode") {
247
+ if (data.mcp !== undefined && !isObject(data.mcp))
248
+ return {
249
+ status: "skipped",
250
+ note: `"mcp" in ${file} is not an object; left untouched`,
251
+ };
252
+ data.mcp ??= {};
253
+ // OpenCode 2.x keeps servers one level deeper, under mcp.servers. A 1.x server that
254
+ // happens to be called "servers" has a type or command of its own.
255
+ const nested = data.mcp.servers;
256
+ v2 =
257
+ (isObject(nested) && !("type" in nested) && !("command" in nested)) ||
258
+ (opencodeMajor ?? 1) >= 2;
259
+ if (v2)
260
+ data.mcp.servers ??= {};
261
+ holder = v2 ? data.mcp.servers : data.mcp;
262
+ if (!isObject(holder))
263
+ return {
264
+ status: "skipped",
265
+ note: `"mcp.servers" in ${file} is not an object; left untouched`,
266
+ };
267
+ }
268
+ else {
269
+ // jcode reads "mcpServers" or its older "servers", never both: keep whichever is there.
270
+ const key = kind === "jcode" &&
271
+ data.servers !== undefined &&
272
+ data.mcpServers === undefined
273
+ ? "servers"
274
+ : "mcpServers";
275
+ if (data[key] !== undefined && !isObject(data[key]))
276
+ return {
277
+ status: "skipped",
278
+ note: `"${key}" in ${file} is not an object; left untouched`,
279
+ };
280
+ holder = data[key] ??= {};
281
+ }
282
+ const next = entryFor(kind, spec, v2);
283
+ if (JSON.stringify(holder[SERVER]) === JSON.stringify(next))
284
+ return { status: "already" };
285
+ const had = SERVER in holder;
286
+ holder[SERVER] = next;
287
+ if (kind === "opencode")
288
+ data.$schema ??= "https://opencode.ai/config.json";
289
+ const backup = backupOnce(file);
290
+ writeAtomic(file, JSON.stringify(data, null, 2) + "\n", scope);
291
+ return {
292
+ status: had ? "updated" : "added",
293
+ note: backup ? `backup ${backup}` : undefined,
294
+ };
295
+ }
296
+ // A TOML table header line: [a.b] or [[a.b]], keys bare or quoted, optionally a comment after.
297
+ const KEY = String.raw `(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
298
+ const TOML_HEADER = new RegExp(String.raw `^\s*\[\[?\s*${KEY}(?:\s*\.\s*${KEY})*\s*\]\]?\s*(?:#.*)?$`);
299
+ const OUR_HEADER = new RegExp(String.raw `^\s*\[\s*mcp_servers\s*\.\s*(?:${SERVER}|"${SERVER}"|'${SERVER}')\s*[\].]`);
300
+ /** Plain objects (the parser's have no prototype), so values compare by content alone. */
301
+ const plain = (v) => JSON.parse(JSON.stringify(v));
302
+ /** The parsed settings without our entry, to compare everything else before and after. */
303
+ function withoutOurs(data) {
304
+ data = plain(data);
305
+ if (isObject(data.mcp_servers)) {
306
+ delete data.mcp_servers[SERVER];
307
+ if (!Object.keys(data.mcp_servers).length)
308
+ delete data.mcp_servers;
309
+ }
310
+ return data;
311
+ }
312
+ /**
313
+ * Codex: replace our [mcp_servers.constructor-research] table and its sub-tables (such as an
314
+ * older .env table carrying the key) with the new entry; every other line stays as it was. The
315
+ * result is parsed and compared with the original: unless only our entry changed, nothing is
316
+ * written.
317
+ */
318
+ export function writeToml(path, spec, scope) {
319
+ const file = target(path);
320
+ const old = existsSync(file) ? readFileSync(file, "utf8") : "";
321
+ const untouched = (why) => ({
322
+ status: "skipped",
323
+ note: `${file} ${why}; left untouched`,
324
+ });
325
+ try {
326
+ parseToml(old);
327
+ }
328
+ catch {
329
+ return untouched("is not valid TOML");
330
+ }
331
+ const kept = [];
332
+ const ours = [];
333
+ let inOurs = false;
334
+ for (const line of old.split("\n")) {
335
+ if (TOML_HEADER.test(line))
336
+ inOurs = OUR_HEADER.test(line);
337
+ (inOurs ? ours : kept).push(line);
338
+ }
339
+ const block = tomlBlock(spec);
340
+ if (ours.join("\n").trim() === block.trim())
341
+ return { status: "already" };
342
+ const body = kept.join("\n").replace(/\s+$/, "");
343
+ const text = (body ? body + "\n\n" : "") + block;
344
+ let after;
345
+ try {
346
+ after = parseToml(text);
347
+ }
348
+ catch {
349
+ return untouched("could not be edited safely");
350
+ }
351
+ const entry = after.mcp_servers?.[SERVER];
352
+ if (!isDeepStrictEqual(plain(entry), { ...spec, startup_timeout_sec: 60 }) ||
353
+ !isDeepStrictEqual(withoutOurs(parseToml(old)), withoutOurs(after)))
354
+ return untouched(`sets ${SERVER} in a form this setup does not edit`);
355
+ const backup = backupOnce(file);
356
+ writeAtomic(file, text, scope);
357
+ return {
358
+ status: ours.length ? "updated" : "added",
359
+ note: backup ? `backup ${backup}` : undefined,
360
+ };
361
+ }
362
+ /** Runs another tool's CLI without a shell, bounded in time. */
363
+ function run(bin, args, opts = {}) {
364
+ return spawnSync(bin, args, {
365
+ cwd: opts.cwd,
366
+ env: opts.env ?? process.env,
367
+ encoding: "utf8",
368
+ timeout: opts.timeout ?? 15000,
369
+ windowsHide: true,
370
+ });
371
+ }
372
+ const available = (bin, env) => run(bin, ["--version"], { env, timeout: 10000 }).status === 0;
373
+ /**
374
+ * Whether Claude Code's CLI can add the entry. Without it the setup edits ~/.claude.json
375
+ * directly, which a running Claude Code may overwrite: the user should quit it first.
376
+ */
377
+ export const claudeCliWorks = (env = process.env) => available("claude", env);
378
+ /** Claude Code's own CLI, so a running Claude Code does not overwrite the change. */
379
+ function viaClaude(scope, spec, cwd, env) {
380
+ const s = scope === "global" ? "user" : "project";
381
+ const add = run("claude", [
382
+ "mcp",
383
+ "add-json",
384
+ "--scope",
385
+ s,
386
+ SERVER,
387
+ JSON.stringify(entryFor("claude", spec)),
388
+ ], { cwd, env });
389
+ if (add.status !== 0) {
390
+ // Only when it is already there: replace it (an older entry may carry the key in env).
391
+ if (!/already exists/i.test(`${add.stdout}${add.stderr}`))
392
+ return undefined;
393
+ run("claude", ["mcp", "remove", SERVER, "--scope", s], { cwd, env });
394
+ const again = run("claude", [
395
+ "mcp",
396
+ "add-json",
397
+ "--scope",
398
+ s,
399
+ SERVER,
400
+ JSON.stringify(entryFor("claude", spec)),
401
+ ], { cwd, env });
402
+ if (again.status !== 0)
403
+ return undefined;
404
+ }
405
+ const get = run("claude", ["mcp", "get", SERVER], { cwd, env });
406
+ return get.status === 0 && get.stdout.includes(SERVER)
407
+ ? { status: "added", note: "via claude mcp add-json" }
408
+ : undefined;
409
+ }
410
+ /** OpenCode's major version, when its CLI answers. */
411
+ function opencodeMajor(env) {
412
+ const r = run("opencode", ["--version"], { env, timeout: 10000 });
413
+ const m = r.status === 0 ? /(\d+)\.\d+/.exec(r.stdout) : null;
414
+ return m ? Number(m[1]) : undefined;
415
+ }
416
+ /** jcode imports Codex's MCP servers once, and only while ~/.jcode/mcp.json does not exist. */
417
+ function jcodeImportNote(file, scope, home) {
418
+ if (scope !== "global" || existsSync(file))
419
+ return undefined;
420
+ try {
421
+ const codex = readFileSync(join(home, ".codex", "config.toml"), "utf8");
422
+ const others = [
423
+ ...codex.matchAll(/^\s*\[mcp_servers\.["']?([^\].'"]+)["']?\]/gm),
424
+ ].filter((m) => m[1] !== SERVER);
425
+ return others.length
426
+ ? "new file, so jcode no longer imports your other Codex MCP servers by itself"
427
+ : undefined;
428
+ }
429
+ catch {
430
+ return undefined;
431
+ }
432
+ }
433
+ const withNote = (r, note) => note ? { ...r, note: [r.note, note].filter(Boolean).join("; ") } : r;
434
+ /** Writes the entry for one agent; never throws. */
435
+ export function applyEntry(agent, scope, spec, o) {
436
+ const file = agent.file(scope, o.home, o.cwd, o.env);
437
+ const clis = o.useClis !== false;
438
+ try {
439
+ switch (agent.kind) {
440
+ case "claude": {
441
+ if (clis && available("claude", o.env)) {
442
+ const r = viaClaude(scope, spec, o.cwd, o.env);
443
+ if (r)
444
+ return r;
445
+ }
446
+ return mergeJson(file, "claude", spec, scope);
447
+ }
448
+ case "codex": {
449
+ const r = writeToml(file, spec, scope);
450
+ if (!succeeded(r) ||
451
+ scope !== "global" ||
452
+ !clis ||
453
+ !available("codex", o.env))
454
+ return r;
455
+ const get = run("codex", ["mcp", "get", SERVER], { env: o.env });
456
+ return withNote(r, get.status === 0 && get.stdout.includes(SERVER)
457
+ ? "codex mcp get sees it"
458
+ : "written, but codex mcp get does not list it");
459
+ }
460
+ case "opencode":
461
+ return mergeJson(file, "opencode", spec, scope, clis ? opencodeMajor(o.env) : undefined);
462
+ case "jcode": {
463
+ const note = jcodeImportNote(file, scope, o.home);
464
+ const r = mergeJson(file, "jcode", spec, scope);
465
+ if (!succeeded(r) || !clis || !available("jcode", o.env))
466
+ return withNote(r, note);
467
+ const test = run("jcode", ["mcp", "test", SERVER], {
468
+ cwd: o.cwd,
469
+ env: o.env,
470
+ timeout: 30000,
471
+ });
472
+ return withNote(withNote(r, test.status === 0
473
+ ? "jcode mcp test connected"
474
+ : "written, but jcode mcp test failed"), note);
475
+ }
476
+ default:
477
+ return mergeJson(file, agent.kind, spec, scope);
478
+ }
479
+ }
480
+ catch (err) {
481
+ return { status: "failed", note: String(err?.message ?? err) };
482
+ }
483
+ }
package/dist/api.d.ts CHANGED
@@ -8,6 +8,8 @@ export declare class ToolError extends Error {
8
8
  constructor(code: string, message: string, status?: number | undefined, apiCode?: number | undefined,
9
9
  /** Extra fields returned to the agent next to status and message. */
10
10
  details?: Record<string, unknown> | undefined);
11
+ /** Constructor's own reason (detail.info.details); never put into messages by default. */
12
+ reason?: string;
11
13
  }
12
14
  export declare const segment: (s: string) => string;
13
15
  /** A key as Constructor shows it, with or without the "Bearer " the header adds. */