constructor-research-mcp 0.4.2 → 0.5.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,24 @@
1
1
  # Constructor Research MCP
2
2
 
3
+ > **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.
4
+ >
3
5
  > **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
6
 
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.
7
+ 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
8
 
7
9
  ## Install
8
10
 
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`).
11
+ You need Node.js 22+ and your personal access key (`rk-…`); the MCP does not work without it. In a terminal, run:
12
+
13
+ ```sh
14
+ npx -y constructor-research-mcp@latest install
15
+ ```
16
+
17
+ 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.
18
+
19
+ ### By hand
20
+
21
+ 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
22
 
11
23
  **Claude Code**
12
24
 
@@ -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
+ }
@@ -0,0 +1,3 @@
1
+ /** The access key as a short hint: rk-…abcd. */
2
+ export declare const mask: (key: string) => string;
3
+ export declare function runInstall(argv: string[]): Promise<number>;
@@ -0,0 +1,432 @@
1
+ // `constructor-research-mcp install`: find the coding agents on this machine, let the user pick
2
+ // them and project or global, get and check the access key, save it to the key file, and add the
3
+ // MCP to each agent. The key is never an argument and never part of an agent's settings.
4
+ import * as p from "@clack/prompts";
5
+ import { mkdirSync, mkdtempSync } from "node:fs";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { join, sep } from "node:path";
8
+ import { styleText } from "node:util";
9
+ import { AGENTS, PACKAGE_SPEC, SERVER, applyEntry, claudeCliWorks, describe, detect, mcpCommand, succeeded, } from "./agents.js";
10
+ import { cleanKey } from "./api.js";
11
+ import { DEFAULT_BASE_URL, configFromEnv, originOf } from "./config.js";
12
+ import { checkKey, readKeyFile, saveKeyFile } from "./key.js";
13
+ const bold = (s) => styleText("bold", s);
14
+ const dim = (s) => styleText("dim", s);
15
+ const accent = (s) => styleText("cyan", s);
16
+ const USAGE = `Constructor Research MCP setup
17
+
18
+ npx -y ${PACKAGE_SPEC} install [options]
19
+
20
+ -y, --yes no questions: detected agents, the level they were found at
21
+ --agents=a,b ${AGENTS.map((a) => a.id).join(", ")}
22
+ --scope=project|global where the MCP entry goes
23
+ --constructor=<link> the Constructor you use (default ${DEFAULT_BASE_URL})
24
+ --key-stdin with -y: read the access key from stdin (or set CONSTRUCTOR_ACCESS_KEY)
25
+ --dry-run change nothing
26
+ --verbose show each agent's file and the exact entry
27
+ --demo try it in a throw-away home folder with fake agents (no key check)
28
+
29
+ The access key is never accepted as an argument.`;
30
+ /** The access key as a short hint: rk-…abcd. */
31
+ export const mask = (key) => `${key.slice(0, 3)}…${key.slice(-4)}`;
32
+ /** Access keys start with rk-; printable ASCII only (cleanKey). */
33
+ const accessKey = (raw) => {
34
+ const key = cleanKey(raw);
35
+ return key?.startsWith("rk-") ? key : undefined;
36
+ };
37
+ /** Accepts acme.constructor.app as well as https://acme.constructor.app. */
38
+ const linkOrigin = (raw) => originOf(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw.trim()) ? raw : `https://${raw.trim()}`);
39
+ async function readStdin() {
40
+ let text = "";
41
+ for await (const chunk of process.stdin)
42
+ text += chunk;
43
+ return text;
44
+ }
45
+ /** Clack draws checkboxes as squares; the agent list shows them as circles (○ / ●). */
46
+ const circles = new Proxy(process.stdout, {
47
+ get(target, key) {
48
+ if (key === "write")
49
+ return (chunk, ...rest) => target.write(typeof chunk === "string"
50
+ ? chunk.replaceAll("◻", "○").replaceAll("◼", "●")
51
+ : chunk, ...rest);
52
+ const value = Reflect.get(target, key, target);
53
+ return typeof value === "function" ? value.bind(target) : value;
54
+ },
55
+ });
56
+ export async function runInstall(argv) {
57
+ const flag = (n) => argv.includes(n);
58
+ const value = (n) => argv.find((a) => a.startsWith(`${n}=`))?.slice(n.length + 1);
59
+ const known = /^(-y|--yes|--key-stdin|--dry-run|--verbose|--demo|-h|--help|--(agents|harnesses|scope|constructor)=.*)$/;
60
+ const unknown = argv.filter((a) => !known.test(a));
61
+ if (flag("-h") || flag("--help") || unknown.length) {
62
+ if (unknown.length)
63
+ console.error(`Unknown option: ${unknown.join(" ")}\n`);
64
+ (unknown.length ? console.error : console.log)(USAGE);
65
+ return unknown.length ? 2 : 0;
66
+ }
67
+ const yes = flag("-y") || flag("--yes");
68
+ const dry = flag("--dry-run");
69
+ const verbose = flag("--verbose");
70
+ const demo = flag("--demo");
71
+ if (flag("--key-stdin") && process.stdin.isTTY) {
72
+ console.error("--key-stdin reads a piped key, e.g. from a password manager.");
73
+ return 2;
74
+ }
75
+ if (flag("--key-stdin") && !yes) {
76
+ console.error("--key-stdin needs -y: the questions read from the same input.");
77
+ return 2;
78
+ }
79
+ if (!yes && !(process.stdin.isTTY && process.stdout.isTTY)) {
80
+ console.error("Run this in a terminal, or pass -y with --agents, --scope and the key on stdin.");
81
+ return 2;
82
+ }
83
+ // One environment for the settings locations, the key file and the agents' own CLIs.
84
+ const env = { ...process.env };
85
+ let home = homedir();
86
+ let cwd = process.cwd();
87
+ if (demo) {
88
+ home = mkdtempSync(join(tmpdir(), "constructor-research-demo-"));
89
+ cwd = join(home, "my-project");
90
+ for (const d of [
91
+ ".claude",
92
+ ".codex",
93
+ join(".config", "opencode"),
94
+ ".jcode",
95
+ ".cline",
96
+ ".cursor",
97
+ "my-project",
98
+ ])
99
+ mkdirSync(join(home, d), { recursive: true });
100
+ // Nothing outside the demo folder: every location override points into it or is cleared.
101
+ for (const v of [
102
+ "OPENCODE_CONFIG_DIR",
103
+ "CLINE_DIR",
104
+ "CLINE_DATA_DIR",
105
+ "CLINE_MCP_SETTINGS_PATH",
106
+ "APPDATA",
107
+ ])
108
+ delete env[v];
109
+ Object.assign(env, {
110
+ HOME: home,
111
+ USERPROFILE: home,
112
+ CLAUDE_CONFIG_DIR: join(home, ".claude"),
113
+ CODEX_HOME: join(home, ".codex"),
114
+ XDG_CONFIG_HOME: join(home, ".config"),
115
+ JCODE_HOME: join(home, ".jcode"),
116
+ CONSTRUCTOR_KEY_FILE: join(home, ".config", "constructor-research", "access-key.json"),
117
+ });
118
+ }
119
+ const config = configFromEnv({ ...env, CONSTRUCTOR_BASE_URL: undefined });
120
+ const show = (path) => path === cwd || path.startsWith(cwd + sep)
121
+ ? "." + path.slice(cwd.length)
122
+ : path.startsWith(home + sep)
123
+ ? "~" + path.slice(home.length)
124
+ : path;
125
+ const ask = async (prompt) => {
126
+ const answer = await prompt;
127
+ if (p.isCancel(answer)) {
128
+ p.cancel("Cancelled. Nothing more was changed.");
129
+ process.exit(1);
130
+ }
131
+ return answer;
132
+ };
133
+ // ---- 1. which agents ---------------------------------------------------------------------
134
+ console.log("");
135
+ p.intro(`${bold(accent("Constructor Research MCP"))} ${dim("setup")}${demo ? dim(` (demo in ${home})`) : ""}`);
136
+ const found = detect(home, cwd, env);
137
+ if (found.length) {
138
+ const width = Math.max(...found.map((d) => d.agent.label.length));
139
+ p.note(found
140
+ .map((d) => `${bold(d.agent.label.padEnd(width))} ${dim(show(d.path))}`)
141
+ .join("\n"), "Detected coding agents");
142
+ }
143
+ else
144
+ p.log.warn("No coding agents found in this folder or your home folder.");
145
+ const detectedIds = [...new Set(found.map((d) => d.agent.id))];
146
+ let chosen;
147
+ const listed = value("--agents") ?? value("--harnesses");
148
+ if (listed) {
149
+ chosen = [
150
+ ...new Set(listed
151
+ .split(",")
152
+ .map((s) => s.trim())
153
+ .filter(Boolean)),
154
+ ];
155
+ const bad = chosen.filter((id) => !AGENTS.some((a) => a.id === id));
156
+ if (bad.length) {
157
+ p.log.error(`Unknown agent: ${bad.join(", ")}. Known: ${AGENTS.map((a) => a.id).join(", ")}`);
158
+ return 2;
159
+ }
160
+ }
161
+ else if (yes)
162
+ chosen = detectedIds;
163
+ else {
164
+ const mode = detectedIds.length
165
+ ? await ask(p.select({
166
+ message: "Install for detected agents only, or add more?",
167
+ options: [
168
+ {
169
+ value: "detected",
170
+ label: "Detected only",
171
+ hint: detectedIds.join(", "),
172
+ },
173
+ { value: "custom", label: "Customize…" },
174
+ ],
175
+ }))
176
+ : "custom";
177
+ chosen =
178
+ mode === "detected"
179
+ ? detectedIds
180
+ : await ask(p.autocompleteMultiselect({
181
+ message: "Select coding agents",
182
+ options: AGENTS.map((a) => ({
183
+ value: a.id,
184
+ label: a.label,
185
+ hint: a.hint,
186
+ })),
187
+ initialValues: detectedIds,
188
+ required: true,
189
+ maxItems: AGENTS.length,
190
+ output: circles,
191
+ }));
192
+ }
193
+ if (!chosen.length) {
194
+ p.log.error("No coding agent selected or found. Name them with --agents=…");
195
+ return 1;
196
+ }
197
+ // ---- 2. project or global ------------------------------------------------------------------
198
+ let scope = value("--scope");
199
+ if (scope && scope !== "project" && scope !== "global") {
200
+ p.log.error("--scope is project or global");
201
+ return 2;
202
+ }
203
+ if (!scope) {
204
+ const fallback = found.some((d) => chosen.includes(d.agent.id) && d.scope === "project")
205
+ ? "project"
206
+ : "global";
207
+ scope = yes
208
+ ? fallback
209
+ : await ask(p.select({
210
+ message: "Install location",
211
+ initialValue: fallback,
212
+ options: [
213
+ {
214
+ value: "project",
215
+ label: "Project",
216
+ hint: show(cwd) === "." ? cwd : show(cwd),
217
+ },
218
+ { value: "global", label: "Global", hint: "~" },
219
+ ],
220
+ }));
221
+ }
222
+ // ---- 3. which Constructor ------------------------------------------------------------------
223
+ let saved;
224
+ try {
225
+ saved = await readKeyFile(config.keyFile);
226
+ }
227
+ catch {
228
+ saved = undefined; // A broken key file is replaced by the new key.
229
+ }
230
+ let base;
231
+ try {
232
+ const given = value("--constructor");
233
+ if (given)
234
+ base = linkOrigin(given);
235
+ else if (yes)
236
+ base = saved?.url ?? DEFAULT_BASE_URL;
237
+ else {
238
+ const savedOrg = saved && saved.url !== DEFAULT_BASE_URL ? saved.url : "";
239
+ const where = await ask(p.select({
240
+ message: `Where do you have access to ${bold("Constructor Research")}?`,
241
+ initialValue: savedOrg ? "org" : "public",
242
+ options: [
243
+ { value: "public", label: "constructor.app" },
244
+ {
245
+ value: "org",
246
+ label: "My organisation's separate instance",
247
+ hint: "e.g. acme.constructor.app",
248
+ },
249
+ ],
250
+ }));
251
+ base =
252
+ where === "public"
253
+ ? DEFAULT_BASE_URL
254
+ : linkOrigin(await ask(p.text({
255
+ message: "Your organisation's instance address",
256
+ placeholder: "acme.constructor.app",
257
+ initialValue: savedOrg.replace(/^https:\/\//, ""),
258
+ validate: (v) => {
259
+ if (!v?.trim())
260
+ return "Enter the address you open Constructor at";
261
+ try {
262
+ linkOrigin(v);
263
+ }
264
+ catch {
265
+ return "Enter an address like acme.constructor.app";
266
+ }
267
+ },
268
+ })));
269
+ // A typo in the address would send the new key to someone else's server.
270
+ const host = new URL(base).hostname;
271
+ if (host !== "constructor.app" &&
272
+ !host.endsWith(".constructor.app") &&
273
+ !(await ask(p.confirm({
274
+ message: `${bold(host)} is not a constructor.app address. Send your key there to check it?`,
275
+ initialValue: false,
276
+ })))) {
277
+ p.cancel("Nothing was sent. Run this again with the right address.");
278
+ return 1;
279
+ }
280
+ }
281
+ }
282
+ catch (err) {
283
+ p.log.error(err?.message ?? String(err));
284
+ return 2;
285
+ }
286
+ // ---- 4. the access key ---------------------------------------------------------------------
287
+ let keySaved = false;
288
+ let keyProblem = "";
289
+ const check = async (key) => {
290
+ if (demo)
291
+ return "ok";
292
+ const s = p.spinner();
293
+ s.start(`Checking the key with ${base.replace(/^https:\/\//, "")}`);
294
+ const { result } = await checkKey(base, config.apiPath, key);
295
+ if (result === "ok")
296
+ s.stop("Key accepted");
297
+ else if (result === "rejected")
298
+ s.error(`${base} rejected this key`);
299
+ else
300
+ s.error(result === "unreachable"
301
+ ? `Could not reach ${base} (VPN?)`
302
+ : `${base} answered without the public API`);
303
+ return result;
304
+ };
305
+ let key;
306
+ if (yes) {
307
+ const raw = flag("--key-stdin")
308
+ ? await readStdin()
309
+ : env.CONSTRUCTOR_ACCESS_KEY;
310
+ if (raw !== undefined) {
311
+ key = accessKey(raw);
312
+ if (!key)
313
+ keyProblem = "that is not an access key (it starts with rk-)";
314
+ else if ((await check(key)) !== "ok") {
315
+ keyProblem = "the key was not accepted, so it was not saved";
316
+ key = undefined;
317
+ }
318
+ }
319
+ else if (!(saved && saved.url === base))
320
+ keyProblem = "no key given (CONSTRUCTOR_ACCESS_KEY or --key-stdin)";
321
+ }
322
+ else {
323
+ const keep = saved?.url === base &&
324
+ !(await ask(p.confirm({
325
+ message: `A key for ${base} is already saved (${mask(saved.key)}). Replace it?`,
326
+ initialValue: false,
327
+ })));
328
+ if (!keep) {
329
+ p.note(`1. Open ${accent(`${base}/research/api-keys`)}\n2. Create an access key and copy it (${dim("rk-…")})\n3. Paste it below. It is not shown, and no agent's settings will contain it`, "Get your access key");
330
+ for (let attempt = 0; attempt < 3 && !key; attempt++) {
331
+ const candidate = accessKey(await ask(p.password({
332
+ message: "Paste the access key",
333
+ mask: "•",
334
+ validate: (v) => accessKey(v)
335
+ ? undefined
336
+ : "That is not an access key (it starts with rk-)",
337
+ })));
338
+ const result = await check(candidate);
339
+ if (result === "ok")
340
+ key = candidate;
341
+ else if (result !== "rejected") {
342
+ if (await ask(p.confirm({
343
+ message: "Save the key without checking it?",
344
+ initialValue: false,
345
+ })))
346
+ key = candidate;
347
+ break;
348
+ }
349
+ }
350
+ if (!key)
351
+ keyProblem = "no accepted key, nothing saved";
352
+ }
353
+ }
354
+ if (key) {
355
+ if (dry)
356
+ p.log.info(`Dry run: key ${mask(key)} not saved.`);
357
+ else {
358
+ await saveKeyFile(config.keyFile, base, key);
359
+ keySaved = true;
360
+ p.log.success(`Key saved to ${bold(show(config.keyFile))} ${dim("(readable only by you)")}`);
361
+ }
362
+ }
363
+ else if (keyProblem)
364
+ p.log.warn(`Key: ${keyProblem}.`);
365
+ // ---- 5. the MCP entry in each agent ----------------------------------------------------------
366
+ const spec = mcpCommand();
367
+ const targets = chosen.map((id) => {
368
+ const agent = AGENTS.find((a) => a.id === id);
369
+ const level = agent.globalOnly ? "global" : scope;
370
+ return { agent, level };
371
+ });
372
+ const names = (list) => list
373
+ .map((t) => `${t.agent.label}${t.level !== scope ? dim(` (${t.level})`) : ""}`)
374
+ .join(", ");
375
+ if (verbose) {
376
+ const lines = [];
377
+ for (const { agent, level } of targets) {
378
+ lines.push(`${bold(agent.label)} ${dim(`· ${level}`)}`);
379
+ lines.push(` ${dim("file")} ${show(agent.file(level, home, cwd, env))}`);
380
+ describe(agent.kind, spec).forEach((l, i) => lines.push(` ${dim(i ? " " : "add ")} ${l}`));
381
+ lines.push("");
382
+ }
383
+ lines.pop();
384
+ p.note(lines.join("\n"), `MCP "${SERVER}": no key inside, it reads the saved key`);
385
+ }
386
+ const results = [];
387
+ // Without Claude Code's CLI its settings file is edited directly; an open Claude Code would
388
+ // overwrite that edit when it next saves.
389
+ if (!dry && !demo && chosen.includes("claude") && !claudeCliWorks(env))
390
+ p.log.warn(`Quit ${bold("Claude Code")} before you continue: its settings file is edited directly.`);
391
+ if (dry)
392
+ p.log.info(`Dry run: would add the MCP to ${names(targets)}.`);
393
+ else if (yes ||
394
+ (await ask(p.confirm({
395
+ message: `Add the MCP to ${names(targets)}${dim(` · ${scope}`)}?`,
396
+ initialValue: true,
397
+ })))) {
398
+ const s = p.spinner();
399
+ s.start("Adding");
400
+ for (const { agent, level } of targets)
401
+ results.push({
402
+ agent,
403
+ r: applyEntry(agent, level, spec, { cwd, home, env }),
404
+ });
405
+ const good = results.filter(({ r }) => succeeded(r));
406
+ s.stop(good.length
407
+ ? `Added to ${good.map(({ agent }) => agent.label).join(", ")}`
408
+ : "Nothing added");
409
+ for (const { agent, r } of results) {
410
+ if (!succeeded(r))
411
+ p.log.warn(`${agent.label}: ${r.status}${r.note ? dim(` · ${r.note}`) : ""}`);
412
+ else if (verbose)
413
+ p.log.info(`${agent.label}: ${r.status}${r.note ? dim(` · ${r.note}`) : ""}`);
414
+ else if (r.note?.includes("jcode no longer imports"))
415
+ p.log.info(`${agent.label}: ${dim(r.note.split("; ").pop())}`);
416
+ }
417
+ if (!verbose && good.length)
418
+ p.log.message(dim("Changed files were backed up first. --verbose shows files and entries."));
419
+ }
420
+ else
421
+ p.log.info("Nothing written to the agents' settings.");
422
+ const okNames = results
423
+ .filter(({ r }) => succeeded(r))
424
+ .map(({ agent }) => agent.label);
425
+ const failed = results.some(({ r }) => !succeeded(r)) || !!keyProblem;
426
+ p.outro(okNames.length
427
+ ? `${bold("Done.")} Restart ${okNames.join(", ")} and ask about Constructor.`
428
+ : keySaved
429
+ ? `${bold("Key saved.")} Add the MCP to an agent, then restart it.`
430
+ : `${bold("Nothing changed.")} Run this again when ready.`);
431
+ return failed ? 1 : 0;
432
+ }
package/dist/key.d.ts CHANGED
@@ -7,3 +7,9 @@ export interface SavedKey {
7
7
  export declare function readKeyFile(file: string): Promise<SavedKey | undefined>;
8
8
  /** Saves the key for one Constructor, mode 600, replacing the file in one step. */
9
9
  export declare function saveKeyFile(file: string, url: string, key: string): Promise<void>;
10
+ export type KeyCheck = "ok" | "rejected" | "no_api" | "unreachable";
11
+ /** Ask Constructor whether it accepts the key: 200 accepted, 401 rejected, else no public API. */
12
+ export declare function checkKey(url: string, apiPath: string, key: string, timeoutMs?: number): Promise<{
13
+ result: KeyCheck;
14
+ status?: number;
15
+ }>;
package/dist/key.js CHANGED
@@ -1,4 +1,5 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
3
  import { dirname } from "node:path";
3
4
  import { originOf } from "./config.js";
4
5
  /** The saved key, or undefined when none was saved. A broken file throws. */
@@ -27,9 +28,38 @@ export async function readKeyFile(file) {
27
28
  /** Saves the key for one Constructor, mode 600, replacing the file in one step. */
28
29
  export async function saveKeyFile(file, url, key) {
29
30
  await mkdir(dirname(file), { recursive: true, mode: 0o700 });
30
- const tmp = `${file}.${process.pid}.tmp`;
31
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
31
32
  await writeFile(tmp, JSON.stringify({ url: originOf(url), key }) + "\n", {
32
33
  mode: 0o600,
34
+ flag: "wx",
33
35
  });
34
- await rename(tmp, file);
36
+ try {
37
+ await rename(tmp, file);
38
+ }
39
+ catch (err) {
40
+ await rm(tmp, { force: true });
41
+ throw err;
42
+ }
43
+ }
44
+ /** Ask Constructor whether it accepts the key: 200 accepted, 401 rejected, else no public API. */
45
+ export async function checkKey(url, apiPath, key, timeoutMs = 15000) {
46
+ try {
47
+ const response = await fetch(`${url}${apiPath}/auth/session`, {
48
+ headers: {
49
+ "X-Research-AccessKey": `Bearer ${key}`,
50
+ Accept: "application/json",
51
+ },
52
+ redirect: "manual",
53
+ signal: AbortSignal.timeout(timeoutMs),
54
+ });
55
+ await response.body?.cancel();
56
+ const status = response.status;
57
+ return {
58
+ result: status === 200 ? "ok" : status === 401 ? "rejected" : "no_api",
59
+ status,
60
+ };
61
+ }
62
+ catch {
63
+ return { result: "unreachable" };
64
+ }
35
65
  }
package/dist/server.js CHANGED
@@ -350,7 +350,17 @@ async function main() {
350
350
  };
351
351
  await server.connect(new StdioServerTransport());
352
352
  }
353
- main().catch(() => {
354
- console.error("Constructor Research MCP could not start. Check environment configuration.");
355
- process.exitCode = 1;
356
- });
353
+ // `constructor-research-mcp install` (or setup) runs the interactive setup instead of the server.
354
+ if (["install", "setup"].includes(process.argv[2] ?? "")) {
355
+ import("./install.js")
356
+ .then(({ runInstall }) => runInstall(process.argv.slice(3)))
357
+ .then((code) => (process.exitCode = code), (err) => {
358
+ console.error(`Setup failed: ${err?.message ?? err}`);
359
+ process.exitCode = 1;
360
+ });
361
+ }
362
+ else
363
+ main().catch(() => {
364
+ console.error("Constructor Research MCP could not start. Check environment configuration.");
365
+ process.exitCode = 1;
366
+ });
package/dist/set-key.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // Usage: npx -y -p constructor-research-mcp constructor-research-set-key <Constructor link>
5
5
  import { configFromEnv, originOf } from "./config.js";
6
6
  import { cleanKey } from "./api.js";
7
- import { saveKeyFile } from "./key.js";
7
+ import { checkKey, saveKeyFile } from "./key.js";
8
8
  const USAGE = "Usage: npx -y -p constructor-research-mcp constructor-research-set-key <Constructor link, e.g. https://acme.constructor.app>\nThen paste the access key (rk-…) when asked, or pipe it in on stdin.";
9
9
  /** One line from the terminal without echoing it, or all of stdin when piped. */
10
10
  async function readSecret(prompt) {
@@ -72,28 +72,16 @@ async function main() {
72
72
  return 1;
73
73
  }
74
74
  // Check the key with Constructor before saving it.
75
- let status;
76
- try {
77
- const response = await fetch(`${url}${config.apiPath}/auth/session`, {
78
- headers: {
79
- "X-Research-AccessKey": `Bearer ${key}`,
80
- Accept: "application/json",
81
- },
82
- redirect: "manual",
83
- signal: AbortSignal.timeout(15000),
84
- });
85
- status = response.status;
86
- await response.body?.cancel();
87
- }
88
- catch {
75
+ const { result, status } = await checkKey(url, config.apiPath, key);
76
+ if (result === "unreachable") {
89
77
  console.error(`Could not reach ${url} (VPN?); nothing saved.`);
90
78
  return 1;
91
79
  }
92
- if (status === 401) {
80
+ if (result === "rejected") {
93
81
  console.error(`${url} rejected this key; nothing saved.`);
94
82
  return 1;
95
83
  }
96
- if (status !== 200) {
84
+ if (result !== "ok") {
97
85
  console.error(`${url} answered HTTP ${status}: it may not have the public API yet; nothing saved.`);
98
86
  return 1;
99
87
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructor-research-mcp",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Local deployment MCP for Constructor Research",
6
6
  "license": "MIT",
@@ -48,7 +48,9 @@
48
48
  "set-key": "node dist/set-key.js"
49
49
  },
50
50
  "dependencies": {
51
+ "@clack/prompts": "1.8.1",
51
52
  "@modelcontextprotocol/sdk": "1.32.2",
53
+ "smol-toml": "1.9.1",
52
54
  "zod": "4.6.7"
53
55
  },
54
56
  "devDependencies": {