constructor-research-mcp 0.4.0-beta.2 → 0.4.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
@@ -8,24 +8,32 @@ 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
11
+ ## 1. Add it to your tool, with your key
12
+
13
+ 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.
12
14
 
13
15
  **Claude Code**: run once:
14
16
 
15
17
  ```sh
16
- claude mcp add --scope user constructor-research -- npx -y constructor-research-mcp@beta
18
+ claude mcp add --scope user constructor-research \
19
+ -e CONSTRUCTOR_BASE_URL=https://constructor.app \
20
+ -e CONSTRUCTOR_ACCESS_KEY=rk-your-key \
21
+ -- npx -y constructor-research-mcp@latest
17
22
  ```
18
23
 
19
24
  On Windows (not WSL), use this instead:
20
25
 
21
26
  ```bat
22
- claude mcp add --scope user constructor-research -- cmd /c npx -y constructor-research-mcp@beta
27
+ claude mcp add --scope user constructor-research -e CONSTRUCTOR_BASE_URL=https://constructor.app -e CONSTRUCTOR_ACCESS_KEY=rk-your-key -- cmd /c npx -y constructor-research-mcp@latest
23
28
  ```
24
29
 
25
30
  **Codex**: run once:
26
31
 
27
32
  ```sh
28
- codex mcp add constructor-research -- npx -y constructor-research-mcp@beta
33
+ codex mcp add constructor-research \
34
+ --env CONSTRUCTOR_BASE_URL=https://constructor.app \
35
+ --env CONSTRUCTOR_ACCESS_KEY=rk-your-key \
36
+ -- npx -y constructor-research-mcp@latest
29
37
  ```
30
38
 
31
39
  The first start downloads the package and can exceed Codex's 10-second start limit. If Codex reports a timeout, restart it once, or add `startup_timeout_sec = 60` under `[mcp_servers.constructor-research]` in `~/.codex/config.toml`. The full entry, if you prefer to write it by hand:
@@ -33,24 +41,16 @@ The first start downloads the package and can exceed Codex's 10-second start lim
33
41
  ```toml
34
42
  [mcp_servers.constructor-research]
35
43
  command = "npx"
36
- args = ["-y", "constructor-research-mcp@beta"]
44
+ args = ["-y", "constructor-research-mcp@latest"]
37
45
  startup_timeout_sec = 60
38
46
  tool_timeout_sec = 30
39
- ```
40
-
41
- **OpenCode**: run once; it adds the entry to your OpenCode config and keeps what is already there. Check your version with `opencode --version`. OpenCode 2.x:
42
-
43
- ```sh
44
- opencode mcp add --global constructor-research -- npx -y constructor-research-mcp@beta
45
- ```
46
47
 
47
- Without `--global`, OpenCode 2.x adds it to the current folder's project config instead. OpenCode 1.x has no `--global` and writes to your user config when run outside a project:
48
-
49
- ```sh
50
- opencode mcp add constructor-research -- npx -y constructor-research-mcp@beta
48
+ [mcp_servers.constructor-research.env]
49
+ CONSTRUCTOR_BASE_URL = "https://constructor.app"
50
+ CONSTRUCTOR_ACCESS_KEY = "rk-your-key"
51
51
  ```
52
52
 
53
- Or add it by hand to `~/.config/opencode/opencode.json` (or a project's `opencode.json`). This is the 1.x layout; in 2.x the entry goes one level deeper, under `mcp.servers`, as in [examples/opencode-v2.json](examples/opencode-v2.json):
53
+ **OpenCode**: add the entry to `~/.config/opencode/opencode.json` (or a project's `opencode.json`), keeping what is already there. Check your version with `opencode --version`. OpenCode 1.x:
54
54
 
55
55
  ```json
56
56
  {
@@ -58,29 +58,33 @@ Or add it by hand to `~/.config/opencode/opencode.json` (or a project's `opencod
58
58
  "mcp": {
59
59
  "constructor-research": {
60
60
  "type": "local",
61
- "command": ["npx", "-y", "constructor-research-mcp@beta"]
61
+ "command": ["npx", "-y", "constructor-research-mcp@latest"],
62
+ "environment": {
63
+ "CONSTRUCTOR_BASE_URL": "https://constructor.app",
64
+ "CONSTRUCTOR_ACCESS_KEY": "rk-your-key"
65
+ }
62
66
  }
63
67
  }
64
68
  }
65
69
  ```
66
70
 
67
- Do not put the key in these settings unless you have to; the next step saves it where every tool finds it.
71
+ In 2.x the entry goes one level deeper, under `mcp.servers`, as in [examples/opencode-v2.json](examples/opencode-v2.json), with the same `environment`.
72
+
73
+ Then restart the tool, or run `/mcp` in Claude Code, so it starts the MCP. The first start downloads it and can take a minute.
68
74
 
69
- ## 2. Save your access key
75
+ ## 2. Or keep the key out of the tool's settings
70
76
 
71
- In a terminal, run this with your Constructor's address and paste the key when asked (it is not shown):
77
+ Step 1 stores the key in the tool's settings file (`~/.claude.json`, `~/.codex/config.toml`, `opencode.json`). To avoid that, add the MCP without the two variables (`claude mcp add --scope user constructor-research -- npx -y constructor-research-mcp@latest`, and the same for Codex and OpenCode) and save the key in a terminal; it asks for the key without showing it:
72
78
 
73
79
  ```sh
74
- npx -y -p constructor-research-mcp@beta constructor-research-set-key https://acme.constructor.app
80
+ npx -y -p constructor-research-mcp@latest constructor-research-set-key https://constructor.app
75
81
  ```
76
82
 
77
- It checks the key with Constructor and saves it, with that address, to `~/.config/constructor-research/access-key.json` (readable only by you). Claude Code, Codex and OpenCode all use this one key, and the MCP works with that Constructor. To switch Constructor or replace a revoked key, run it again. Never paste the key into the chat.
78
-
79
- Then restart the tool, or run `/mcp` in Claude Code, so it starts the MCP. The first start downloads it and can take a minute.
83
+ It checks the key with Constructor and saves it, with that address, to `~/.config/constructor-research/access-key.json` (readable only by you). Claude Code, Codex, OpenCode and the wait hooks all use this one file, and a new key needs no restart. To switch Constructor or replace a revoked key, run it again. A key set in the tool's settings wins over the file. Never paste the key into the chat.
80
84
 
81
85
  ## 3. Optional: get told when a deployment finishes
82
86
 
83
- Builds can take many minutes. These add-ons wake the agent when a deployment it started finishes:
87
+ Builds can take many minutes. These add-ons wake the agent when a deployment it started finishes. They do not see the MCP settings: with the key in step 1, also save it with `set-key` (step 2), or give the hooks the same two variables.
84
88
 
85
89
  - Claude Code: merge [examples/claude-hooks.json](examples/claude-hooks.json) into `~/.claude/settings.json`.
86
90
  - Codex: copy [examples/codex-hooks.json](examples/codex-hooks.json) to `~/.codex/hooks.json`, then trust it in `/hooks`.
@@ -88,7 +92,7 @@ Builds can take many minutes. These add-ons wake the agent when a deployment it
88
92
 
89
93
  ## Update
90
94
 
91
- Restart the tool (or `/mcp` in Claude Code): `@beta` fetches the newest beta on start. Your key is kept.
95
+ Restart the tool (or `/mcp` in Claude Code): `@latest` fetches the newest version on start. Your key is kept.
92
96
 
93
97
  ## Troubleshooting
94
98
 
@@ -105,7 +109,7 @@ which npx
105
109
  **Check the MCP on its own.** Run the MCP Inspector, then turn on the server's toggle and open Tools:
106
110
 
107
111
  ```sh
108
- npx @modelcontextprotocol/inspector@2.11.0 -- npx -y constructor-research-mcp@beta
112
+ npx @modelcontextprotocol/inspector@2.11.0 -- npx -y constructor-research-mcp@latest
109
113
  ```
110
114
 
111
115
  ## Uninstall
package/README.md CHANGED
@@ -1,54 +1,52 @@
1
1
  # Constructor Research MCP
2
2
 
3
- > **Beta (0.4.0-beta):** works only with Constructor's public API and a personal access key (`rk-…`); there is no browser sign-in. The public API is not yet on every Constructor. Install with `@beta`; `@latest` is still 0.3.x with browser sign-in.
3
+ > **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
4
 
5
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.
6
6
 
7
7
  ## Install
8
8
 
9
- You need Node.js 22+. Then add the MCP to your tool.
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`).
10
10
 
11
11
  **Claude Code**
12
12
 
13
13
  ```sh
14
- claude mcp add --scope user constructor-research -- npx -y constructor-research-mcp@beta
14
+ claude mcp add --scope user constructor-research \
15
+ -e CONSTRUCTOR_BASE_URL=https://constructor.app \
16
+ -e CONSTRUCTOR_ACCESS_KEY=rk-your-key \
17
+ -- npx -y constructor-research-mcp@latest
15
18
  ```
16
19
 
17
20
  **Codex**
18
21
 
19
22
  ```sh
20
- codex mcp add constructor-research -- npx -y constructor-research-mcp@beta
23
+ codex mcp add constructor-research \
24
+ --env CONSTRUCTOR_BASE_URL=https://constructor.app \
25
+ --env CONSTRUCTOR_ACCESS_KEY=rk-your-key \
26
+ -- npx -y constructor-research-mcp@latest
21
27
  ```
22
28
 
23
- **OpenCode 2.x**
29
+ **OpenCode**: add the entry to `~/.config/opencode/opencode.json` (layouts for 1.x and 2.x in [INSTALL.md](INSTALL.md)).
24
30
 
25
- ```sh
26
- opencode mcp add --global constructor-research -- npx -y constructor-research-mcp@beta
27
- ```
28
-
29
- **OpenCode 1.x** (no `--global` there):
31
+ Then restart the tool and ask the agent anything about Constructor. Windows notes, the optional wake-up hooks and troubleshooting are in [INSTALL.md](INSTALL.md). Restarting the tool picks up a new version.
30
32
 
31
- ```sh
32
- opencode mcp add constructor-research -- npx -y constructor-research-mcp@beta
33
- ```
34
-
35
- Then save your personal access key (see below), restart the tool and ask the agent anything about Constructor. Windows notes, the optional wake-up hooks and troubleshooting are in [INSTALL.md](INSTALL.md). Restarting the tool picks up a new version.
33
+ The key then sits in the tool's settings file (`~/.claude.json`, `~/.codex/config.toml`, `opencode.json`). To keep it out of there, add the MCP without the two variables and save the key with `set-key` (below).
36
34
 
37
35
  ## Access key and connection
38
36
 
39
- The MCP uses only a personal access key (`rk-…`) from Constructor's public API; there is no browser sign-in. Every request carries it as `X-Research-AccessKey: Bearer rk-…`, to the account API (`/api/platform-account/v1`), the desk storage (WebDAV) and the logs alike. The key never goes through the chat: the user saves it in a terminal, where it is read hidden, checked against Constructor and saved:
37
+ The MCP uses only a personal access key (`rk-…`) from Constructor's public API; there is no browser sign-in. Every request carries it as `X-Research-AccessKey: Bearer rk-…`, to the account API (`/api/platform-account/v1`), the desk storage (WebDAV) and the logs alike. The key never goes through the chat. It comes from the MCP settings (`CONSTRUCTOR_ACCESS_KEY`, with `CONSTRUCTOR_BASE_URL`, as in Install), or from a key file the user saves in a terminal, where the key is read hidden, checked against Constructor and saved:
40
38
 
41
39
  ```sh
42
- npx -y -p constructor-research-mcp@beta constructor-research-set-key https://acme.constructor.app
40
+ npx -y -p constructor-research-mcp@latest constructor-research-set-key https://acme.constructor.app
43
41
  ```
44
42
 
45
43
  It goes to `~/.config/constructor-research/access-key.json` (mode 600) together with the Constructor it belongs to, and the MCP works with that Constructor. All harnesses (Claude Code, Codex, OpenCode) and the wait command share this one file. Every request rereads it, so a new key needs no restart. A key is never sent to a Constructor other than the one it was saved for.
46
44
 
47
- Instead of the file, `CONSTRUCTOR_ACCESS_KEY` (with `CONSTRUCTOR_BASE_URL`) can be set in the MCP settings; it takes precedence. The wait hooks do not see the MCP settings, so with this option they need the same variables in their own environment.
45
+ `CONSTRUCTOR_ACCESS_KEY` in the MCP settings takes precedence over the file. The wait hooks do not see the MCP settings: with the key there, give the hooks the same two variables in their own environment, or save the key with `set-key` as well.
48
46
 
49
47
  Without a key, or when Constructor rejects it (401: revoked, expired or for another Constructor), tools return `needs_key` with the command above; a deployment pauses as `needs_key` and resumes on the next check once a valid key is saved. A desk link from another Constructor returns `wrong_environment`.
50
48
 
51
- Deployment must be switched on for the project. If it is off and the key may not switch it on (403), the operation fails at stage `prepare` with a message asking the user to switch it on in Constructor.
49
+ Deployment must be switched on for the project. When it is off, the MCP switches it on (`POST /projects/{id}/deployment`), which only the project owner may do. For anyone else (error 40005), the operation fails at stage `prepare` with a message asking the project owner to switch it on in Constructor.
52
50
 
53
51
  | Variable | Default |
54
52
  | ----------------------------------- | ----------------------------------------------------------------------------------------------- |
@@ -104,6 +102,12 @@ https://constructor.app/research/projects/<project_id>/desks/<desk_id>/viewer/fi
104
102
 
105
103
  Every tool accepts it as `desk_url`, in place of `project_id`/`desk_id`. Anything after `/desks/<desk_id>` is ignored. The link's host must be the Constructor the key belongs to; a link from another one returns `wrong_environment` (see the access key above). Explicit IDs, if also sent, must agree with the link. In `deploy_app`/`update_app`, builds without their own `desk_id` use the link's desk; `start_app`/`stop_app` and `get_deployment` take only the project from it.
106
104
 
105
+ Given only `project_id`, the MCP finds the desk itself:
106
+
107
+ - one desk in the project: it is used;
108
+ - no desk: `deploy_app`/`update_app` create one (`<application>-source`) for the sources; the file tools return an error;
109
+ - several desks: nothing is changed and the tool returns `desk_choice_required` with each desk's `name`, `id` and `desk_url`. The agent asks the user which one and repeats the call with that link or ID.
110
+
107
111
  ## Normal deployment flow
108
112
 
109
113
  1. Inspect with `get_deployment`: no arguments returns the map of all deployments (every deployment-enabled project → applications → services with names, native statuses, public URLs and ports; other projects are listed by name only); `desk_url` or `project_id` returns that project's disks, images, hardware and apps; add `application_id` for service details.
@@ -173,7 +177,9 @@ Private DNS works between containers; browser JavaScript needs a public backend
173
177
 
174
178
  ### Image reuse and limits
175
179
 
176
- Replace a service's `build` with `"image_id":"IMAGE_ID"` to skip building. `list_images` returns compact records with `not_started`, `snapshot_creation`, `in_progress`, `done` or `error`; `detailed:true` returns full records.
180
+ Replace a service's `build` with `"image_id":"IMAGE_ID"` to skip building, or with `"image":"registry/repo:tag"` to name an image already in the project by its reference or name. `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
+
182
+ External images (`source: external`) are pulled, not built, so they are accepted whatever their build status, unless it is `error`. They are added to the project in Constructor: the public API has no endpoint to add one, so `image` only finds images that are already there and lists the project's external images when nothing matches.
177
183
 
178
184
  - 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**.
179
185
  - Each service can have multiple ports (1–65535), with at most **one public port**. That port must match where the container listens.
@@ -255,7 +261,7 @@ Constructor serves logs only live, as a stream: a build log while the build runs
255
261
  Builds can run for many minutes. The MCP keeps executing in the background, but an agent that has ended its turn is not told when they finish. `dist/wait.js` (bin `constructor-research-wait`) blocks until the given deployments, or all in-progress ones when no ID is given, finish, and prints one line each: status, message, services with public URLs, next step. Exit codes: `0` finished, `2` needs the user (failed, key, upload, volume confirmation), `3` still running at `--max-minutes` (default 60), `4` nothing in progress.
256
262
 
257
263
  ```sh
258
- npx -y -p constructor-research-mcp@beta constructor-research-wait <deployment_id>
264
+ npx -y -p constructor-research-mcp@latest constructor-research-wait <deployment_id>
259
265
  ```
260
266
 
261
267
  It watches the checkpoints the MCP writes. For deployments named by ID, if no process has advanced one for a minute (the MCP was closed), it continues it itself, exactly as the MCP would on restart. Without IDs it only watches, since those deployments may belong to other sessions. While a deployment runs, `next_action` gives the agent the exact command, including the MCP's non-default `CONSTRUCTOR_*` settings; the wait command needs the same settings as the MCP.
package/dist/api.d.ts CHANGED
@@ -3,7 +3,11 @@ export declare class ToolError extends Error {
3
3
  code: string;
4
4
  status?: number | undefined;
5
5
  apiCode?: number | undefined;
6
- constructor(code: string, message: string, status?: number | undefined, apiCode?: number | undefined);
6
+ /** Extra fields returned to the agent next to status and message. */
7
+ details?: Record<string, unknown> | undefined;
8
+ constructor(code: string, message: string, status?: number | undefined, apiCode?: number | undefined,
9
+ /** Extra fields returned to the agent next to status and message. */
10
+ details?: Record<string, unknown> | undefined);
7
11
  }
8
12
  export declare const segment: (s: string) => string;
9
13
  /** A key as Constructor shows it, with or without the "Bearer " the header adds. */
package/dist/api.js CHANGED
@@ -6,11 +6,15 @@ export class ToolError extends Error {
6
6
  code;
7
7
  status;
8
8
  apiCode;
9
- constructor(code, message, status, apiCode) {
9
+ details;
10
+ constructor(code, message, status, apiCode,
11
+ /** Extra fields returned to the agent next to status and message. */
12
+ details) {
10
13
  super(message);
11
14
  this.code = code;
12
15
  this.status = status;
13
16
  this.apiCode = apiCode;
17
+ this.details = details;
14
18
  }
15
19
  }
16
20
  export const segment = (s) => encodeURIComponent(s);
@@ -50,6 +50,15 @@ export declare class DeploymentEngine {
50
50
  * and wait; it takes about 30-40 s.
51
51
  */
52
52
  filesDesk(project: string, id: string): Promise<any>;
53
+ /** An image a service can run: built here, or external (pulled, never built). */
54
+ static usable(im: any): boolean;
55
+ /**
56
+ * The desk to use when the call names only the project: the only desk, a new one
57
+ * when there is none and `create` is given, otherwise the user chooses.
58
+ */
59
+ deskFor(project: string, create?: string): Promise<string>;
60
+ /** Turn each service's `image` (reference or name) into the project's image_id. */
61
+ resolveImages(project: string, services: any[]): Promise<any[]>;
53
62
  listImages(raw: unknown): Promise<{
54
63
  results: any[];
55
64
  total: number;
@@ -370,6 +370,58 @@ export class DeploymentEngine {
370
370
  return d;
371
371
  throw new ToolError("not_ready", `The desk's file storage was stopped (desk not used recently), so the MCP started it, as opening the desk in the browser does. It is still ${status ?? "starting"}; this takes about 30-40 s. Nothing was changed. Repeat the same call in a moment.`);
372
372
  }
373
+ /** An image a service can run: built here, or external (pulled, never built). */
374
+ static usable(im) {
375
+ return im?.source === "external"
376
+ ? im.build_status !== "error"
377
+ : im?.build_status === "done";
378
+ }
379
+ /**
380
+ * The desk to use when the call names only the project: the only desk, a new one
381
+ * when there is none and `create` is given, otherwise the user chooses.
382
+ */
383
+ async deskFor(project, create) {
384
+ await this.project(project);
385
+ const desks = await this.rows(this.root(project) + "/desks");
386
+ if (desks.length === 1)
387
+ return desks[0].id;
388
+ if (desks.length > 1)
389
+ throw new ToolError("desk_choice_required", `Project ${project} has ${desks.length} desks: ${desks.map((d) => `${d.name} (${d.id})`).join(", ")}. Nothing was changed. Ask the user which desk to use (name or link), then repeat the call with desk_url, or desk_id (build.desk_id for a service).`, undefined, undefined, {
390
+ desks: desks.map((d) => ({
391
+ id: d.id,
392
+ name: d.name,
393
+ desk_url: this.deskLink(project, d.id),
394
+ })),
395
+ });
396
+ if (!create)
397
+ bad(`Project ${project} has no desk. Ask the user to create one in Constructor, or deploy a local folder (deploy_app creates a desk for it).`);
398
+ const d = await this.api.request("POST", this.root(project) + "/desks", {
399
+ name: create,
400
+ });
401
+ return d.id;
402
+ }
403
+ /** Turn each service's `image` (reference or name) into the project's image_id. */
404
+ async resolveImages(project, services) {
405
+ if (!services?.some((s) => s.image))
406
+ return services;
407
+ const images = await this.images(project);
408
+ return services.map((s) => {
409
+ if (!s.image)
410
+ return s;
411
+ const want = s.image.trim();
412
+ const hits = images.filter((im) => im.reference === want || im.name === want || im.id === want);
413
+ const im = hits.length > 1
414
+ ? (hits.find((x) => x.reference === want) ??
415
+ bad(`Image "${want}" for ${s.name} matches several images: ${hits.map((x) => x.id).join(", ")}. Pass image_id.`))
416
+ : hits[0];
417
+ if (!im) {
418
+ const ext = images.filter((x) => x.source === "external");
419
+ bad(`Image "${want}" for ${s.name} is not in this project. ${ext.length ? `External images here: ${ext.map((x) => `${x.reference ?? x.name} (${x.id})`).join(", ")}.` : "The project has no external images."} An external image is added in Constructor first; the API cannot add one.`);
420
+ }
421
+ const { image: _i, ...rest } = s;
422
+ return { ...rest, image_id: im.id };
423
+ });
424
+ }
373
425
  async listImages(raw) {
374
426
  const input = listInput.parse(raw);
375
427
  await this.project(input.project_id);
@@ -387,6 +439,8 @@ export class DeploymentEngine {
387
439
  dockerfile: x.dockerfile,
388
440
  tag: x.tag,
389
441
  build_status: x.build_status,
442
+ source: x.source,
443
+ reference: x.reference,
390
444
  })),
391
445
  total: results.length,
392
446
  };
@@ -512,12 +566,14 @@ export class DeploymentEngine {
512
566
  input.services.length)
513
567
  bad("Service overrides must be unique.");
514
568
  const images = op.project_id ? await this.images(op.project_id) : [];
569
+ if (op.project_id)
570
+ input.services = await this.resolveImages(op.project_id, input.services);
515
571
  for (const override of input.services) {
516
572
  const at = next.findIndex((s) => s.name === override.name);
517
573
  if (at < 0)
518
574
  bad("Resume overrides can only change services already in this deployment.");
519
575
  if (override.image_id &&
520
- !images.some((im) => im.id === override.image_id && im.build_status === "done"))
576
+ !images.some((im) => im.id === override.image_id && DeploymentEngine.usable(im)))
521
577
  bad("Replacement image is not successfully built in this project.");
522
578
  const saved = next[at];
523
579
  next[at] = {
@@ -785,13 +841,15 @@ export class DeploymentEngine {
785
841
  /** Switches on deployment; when the key may not, the operation stops with what to do instead. */
786
842
  async enableDeployment(op, project) {
787
843
  try {
788
- await this.mutate(op, "PATCH", this.root(project), { deployment_enabled: true }, () => {
844
+ await this.mutate(op, "POST", this.root(project) + "/deployment", { enabled: true }, () => {
789
845
  op.status = "preparing";
790
846
  });
791
847
  }
792
848
  catch (err) {
793
- if (err instanceof ToolError && err.status === 403)
794
- throw new ToolError("deployment_disabled", "Deployment is switched off for this project, and the access key may not switch it on. Ask the user to switch on deployment for the project in Constructor, then repeat the same call.", 403, err.apiCode);
849
+ // Only the project owner may switch it on (421, error 40005); older servers answer 403.
850
+ if (err instanceof ToolError &&
851
+ (err.apiCode === 40005 || err.status === 403))
852
+ throw new ToolError("deployment_disabled", "Deployment is switched off for this project, and only the project owner can switch it on. Ask the project owner to switch on deployment for the project in Constructor, then repeat the same call.", err.status, err.apiCode);
795
853
  throw err;
796
854
  }
797
855
  }
@@ -933,8 +991,8 @@ export class DeploymentEngine {
933
991
  bad(`New service ${s.name} requires image_id or build.`);
934
992
  if (s.image_id) {
935
993
  const im = images.find((x) => x.id === s.image_id);
936
- if (!im || im.build_status !== "done")
937
- bad(`Image for ${s.name} is missing or not successfully built in this project.`);
994
+ if (!DeploymentEngine.usable(im))
995
+ bad(`Image for ${s.name} is missing, or not successfully built, in this project.`);
938
996
  }
939
997
  const hw = hardwareFor(s, old);
940
998
  if (!hw || !hardware.some((h) => h.id === hw && !h.removed))
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  /** Where a tool acts: a desk (project + desk), a project only, or a deployment-shaped input whose schema already allows a missing project_id. */
3
3
  export type Scope = "desk" | "project" | "deploy";
4
4
  /** Tool-facing schema: the engine schema plus desk_url, with the IDs it supplies made optional. */
5
- export declare function located(schema: z.ZodObject<any>, scope: Exclude<Scope, "deploy">,
5
+ export declare function located(schema: z.ZodObject<any>, _scope: Exclude<Scope, "deploy">,
6
6
  /** Inside a desk the IDs default to it, so neither a link nor IDs are required. */
7
7
  implied?: boolean): z.ZodObject<{
8
8
  [x: string]: any;
package/dist/location.js CHANGED
@@ -2,7 +2,7 @@ import { ToolError } from "./api.js";
2
2
  import { VERSION } from "./config.js";
3
3
  import { id, deskUrl } from "./schemas.js";
4
4
  /** Tool-facing schema: the engine schema plus desk_url, with the IDs it supplies made optional. */
5
- export function located(schema, scope,
5
+ export function located(schema, _scope,
6
6
  /** Inside a desk the IDs default to it, so neither a link nor IDs are required. */
7
7
  implied = false) {
8
8
  const extended = schema.extend({
@@ -19,12 +19,8 @@ implied = false) {
19
19
  desk_url: deskUrl.optional(),
20
20
  })
21
21
  .refine((x) => !!x.desk_url ||
22
- (!!x.project_id &&
23
- (scope !== "desk" ||
24
- !!x.desk_id ||
25
- schema.shape.desk_id.safeParse(undefined).success)), scope === "desk"
26
- ? "Provide desk_url (the desk link from the browser) or project_id and desk_id."
27
- : "Provide desk_url (the desk link from the browser) or project_id.");
22
+ // Without desk_id the MCP picks the project's only desk, or asks which one.
23
+ !!x.project_id, "Provide desk_url (the desk link from the browser) or project_id.");
28
24
  }
29
25
  function bad(code, message) {
30
26
  throw new ToolError(code, message);
package/dist/schemas.d.ts CHANGED
@@ -18,6 +18,7 @@ export declare const serviceInput: z.ZodObject<{
18
18
  name: z.ZodString;
19
19
  service_id: z.ZodOptional<z.ZodString>;
20
20
  image_id: z.ZodOptional<z.ZodString>;
21
+ image: z.ZodOptional<z.ZodString>;
21
22
  build: z.ZodOptional<z.ZodObject<{
22
23
  desk_id: z.ZodOptional<z.ZodString>;
23
24
  dockerfile: z.ZodOptional<z.ZodString>;
@@ -66,6 +67,7 @@ export declare const deployInput: z.ZodObject<{
66
67
  name: z.ZodString;
67
68
  service_id: z.ZodOptional<z.ZodString>;
68
69
  image_id: z.ZodOptional<z.ZodString>;
70
+ image: z.ZodOptional<z.ZodString>;
69
71
  build: z.ZodOptional<z.ZodObject<{
70
72
  desk_id: z.ZodOptional<z.ZodString>;
71
73
  dockerfile: z.ZodOptional<z.ZodString>;
@@ -120,6 +122,7 @@ export declare const updateInput: z.ZodObject<{
120
122
  name: z.ZodString;
121
123
  service_id: z.ZodOptional<z.ZodString>;
122
124
  image_id: z.ZodOptional<z.ZodString>;
125
+ image: z.ZodOptional<z.ZodString>;
123
126
  build: z.ZodOptional<z.ZodObject<{
124
127
  desk_id: z.ZodOptional<z.ZodString>;
125
128
  dockerfile: z.ZodOptional<z.ZodString>;
package/dist/schemas.js CHANGED
@@ -104,6 +104,12 @@ export const serviceInput = z
104
104
  name: serviceName,
105
105
  service_id: id.optional(),
106
106
  image_id: id.optional(),
107
+ image: z
108
+ .string()
109
+ .min(1)
110
+ .max(512)
111
+ .optional()
112
+ .describe("An image already in the project, by its reference (registry/repo:tag, for an external image) or its name, as list_images shows them. The MCP turns it into image_id. External images are added in Constructor; the API cannot add them."),
107
113
  build: build.optional(),
108
114
  hardware: z
109
115
  .strictObject({
@@ -121,11 +127,11 @@ export const serviceInput = z
121
127
  .describe("Plain strings, or {service, port[, scheme]} to point at another service of the same app; never localhost."),
122
128
  depends_on: z.array(serviceName).optional(),
123
129
  })
124
- .refine((s) => !(s.image_id && s.build), "Choose image_id or build, not both.");
130
+ .refine((s) => [s.image_id, s.image, s.build].filter(Boolean).length <= 1, "Choose one of image_id, image or build.");
125
131
  export const deskUrl = z
126
132
  .string()
127
133
  .max(2048)
128
- .describe("Link to the Constructor desk the user copied from the browser, e.g. https://constructor.app/research/projects/<project>/desks/<desk>/viewer/file. Supplies project_id and desk_id; ask the user for it instead of choosing a project or desk yourself.");
134
+ .describe("Link to the Constructor desk the user copied from the browser, e.g. https://constructor.app/research/projects/<project>/desks/<desk>/viewer/file. Supplies project_id and desk_id. With project_id alone the MCP uses the project's only desk; when the project has several, it asks for this link or desk_id.");
129
135
  const deploymentShape = {
130
136
  project_id: id.optional(),
131
137
  desk_url: deskUrl
package/dist/server.js CHANGED
@@ -40,6 +40,17 @@ async function main() {
40
40
  /** Verify Dockerfiles on their disks before any build; surface lint warnings to the agent. */
41
41
  const checked = (fn, single = false) => async (a) => {
42
42
  const begun = Date.now();
43
+ if (!single && a.project_id && a.services) {
44
+ // External images by reference or name; builds without a desk go to the project's desk.
45
+ let services = await engine.resolveImages(a.project_id, a.services);
46
+ if (services.some((x) => x.build && !x.build.desk_id)) {
47
+ const desk = await engine.deskFor(a.project_id, `${a.application_name ?? "application"}-source`);
48
+ services = services.map((x) => x.build && !x.build.desk_id
49
+ ? { ...x, build: { ...x.build, desk_id: desk } }
50
+ : x);
51
+ }
52
+ a = { ...a, services };
53
+ }
43
54
  if (!single && a.services?.some((x) => x.build?.local_path)) {
44
55
  // Upload local sources first, once per (disk, local folder, disk folder).
45
56
  const done = new Set();
@@ -156,7 +167,7 @@ async function main() {
156
167
  ? text.replace(/Where to act: ask the user for the Constructor desk link.*?if the user has not said where to deploy or where files live, ask\. /, deskInstructions(config.localDesk) + " ")
157
168
  : text;
158
169
  const server = new McpServer({ name: "constructor-research", version: VERSION }, {
159
- instructions: withDesk(`Access: the MCP works with one Constructor and the user's personal access key for it, set up outside the chat. When a tool returns needs_key, pass its instructions on to the user; never ask for the key in the chat. Where to act: ask the user for the Constructor desk link (they open the desk in the browser and copy the address; it contains /projects/<project>/desks/<desk>) and pass it as desk_url. Do not pick a project or desk yourself; if the user has not said where to deploy or where files live, ask. Ask the user only before replacing, renaming or deleting files on a disk, once per request for the whole list (the tools return confirm_required); creating folders and uploading new files need no question. ${RULES} For a local app, pass build.local_path (the folder with the Dockerfile) and deploy_app uploads it first. Hardware: leave it out; the default is used. Set hardware minimums only when the app cannot run without a GPU or a lot of RAM. Use deploy_app/update_app once for the WHOLE application. The MCP builds, resolves service URLs, configures and starts services in the background. IDs are automatic. To wait, call get_deployment(wait_seconds=20) again as often as needed (a loop of such calls is fine); never perform the deployment steps yourself. When the user asks to deploy or build, wait until the deployment is finished before answering, then give the public URL or what failed. On failure, tell the user the failed stage/service; failure.log_tail and get_logs show the last build or service log lines. Do not use browser or debugging tools. For source files: sync_files to the desk before building (the MCP checks each Dockerfile on the disk and reports warnings); after a needs_upload pause, sync and call get_deployment with files_uploaded=true. Started is not readiness.`),
170
+ instructions: withDesk(`Access: the MCP works with one Constructor and the user's personal access key for it, set up outside the chat. When a tool returns needs_key, pass its instructions on to the user; never ask for the key in the chat. Where to act: ask the user for the Constructor desk link (they open the desk in the browser and copy the address; it contains /projects/<project>/desks/<desk>) and pass it as desk_url. Do not pick a project yourself; if the user has not said where to deploy or where files live, ask. Given a project only (project_id), the MCP uses its only desk, or creates one for a deploy when there is none; when the project has several desks it returns desk_choice_required with their names and links: ask the user which one. Ask the user only before replacing, renaming or deleting files on a disk, once per request for the whole list (the tools return confirm_required); creating folders and uploading new files need no question. ${RULES} For a local app, pass build.local_path (the folder with the Dockerfile) and deploy_app uploads it first. To run an image that is already in the project, such as an external image (registry/repo:tag added in Constructor), pass image with its reference or name, or image_id; list_images shows source and reference. Hardware: leave it out; the default is used. Set hardware minimums only when the app cannot run without a GPU or a lot of RAM. Use deploy_app/update_app once for the WHOLE application. The MCP builds, resolves service URLs, configures and starts services in the background. IDs are automatic. To wait, call get_deployment(wait_seconds=20) again as often as needed (a loop of such calls is fine); never perform the deployment steps yourself. When the user asks to deploy or build, wait until the deployment is finished before answering, then give the public URL or what failed. On failure, tell the user the failed stage/service; failure.log_tail and get_logs show the last build or service log lines. Do not use browser or debugging tools. For source files: sync_files to the desk before building (the MCP checks each Dockerfile on the disk and reports warnings); after a needs_upload pause, sync and call get_deployment with files_uploaded=true. Started is not readiness.`),
160
171
  });
161
172
  const register = (name, description, schema, fn, readOnly = false, budget = 20000, scope) => {
162
173
  const here = config.localDesk && DESK_DEFAULT.has(name) ? config.localDesk : undefined;
@@ -174,20 +185,28 @@ async function main() {
174
185
  }, async (args) => {
175
186
  try {
176
187
  await api.refresh();
177
- const result = await api.withBudget(budget, () => fn(scope
178
- ? resolveDeskUrl(
179
- // Inside a desk, a call that names no other desk acts on it.
180
- here &&
181
- !args?.desk_url &&
182
- (!args?.project_id ||
183
- args.project_id === here.projectId) &&
184
- (!args?.desk_id || args.desk_id === here.deskId)
185
- ? {
186
- ...args,
187
- desk_url: `${config.baseUrl}/research/projects/${here.projectId}/desks/${here.deskId}`,
188
- }
189
- : args, config.baseUrl, scope, config.baseUrlFixed)
190
- : args));
188
+ const result = await api.withBudget(budget, async () => {
189
+ const at = scope
190
+ ? resolveDeskUrl(
191
+ // Inside a desk, a call that names no other desk acts on it.
192
+ here &&
193
+ !args?.desk_url &&
194
+ (!args?.project_id || args.project_id === here.projectId) &&
195
+ (!args?.desk_id || args.desk_id === here.deskId)
196
+ ? {
197
+ ...args,
198
+ desk_url: `${config.baseUrl}/research/projects/${here.projectId}/desks/${here.deskId}`,
199
+ }
200
+ : args, config.baseUrl, scope, config.baseUrlFixed)
201
+ : args;
202
+ // A desk tool given only the project acts on its only desk, or asks which one.
203
+ if (scope === "desk" &&
204
+ name !== "list_images" &&
205
+ at?.project_id &&
206
+ !at.desk_id)
207
+ at.desk_id = await engine.deskFor(at.project_id);
208
+ return fn(at);
209
+ });
191
210
  return {
192
211
  content: [
193
212
  {
@@ -216,6 +235,7 @@ async function main() {
216
235
  message: err.message,
217
236
  http_status: err.status,
218
237
  api_error_code: err.apiCode,
238
+ ...err.details,
219
239
  }
220
240
  : {
221
241
  status: "internal_error",
@@ -6,7 +6,7 @@
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
- "command": "npx -y -p constructor-research-mcp@beta constructor-research-wait --hook claude-code",
9
+ "command": "npx -y -p constructor-research-mcp@latest constructor-research-wait --hook claude-code",
10
10
  "asyncRewake": true
11
11
  }
12
12
  ]
@@ -2,7 +2,7 @@
2
2
  "mcpServers": {
3
3
  "constructor-research": {
4
4
  "command": "npx",
5
- "args": ["-y", "constructor-research-mcp@beta"]
5
+ "args": ["-y", "constructor-research-mcp@latest"]
6
6
  }
7
7
  }
8
8
  }
@@ -5,7 +5,7 @@
5
5
  "hooks": [
6
6
  {
7
7
  "type": "command",
8
- "command": "npx -y -p constructor-research-mcp@beta constructor-research-wait --hook codex",
8
+ "command": "npx -y -p constructor-research-mcp@latest constructor-research-wait --hook codex",
9
9
  "timeout": 600,
10
10
  "statusMessage": "Waiting for Constructor deployments"
11
11
  }
@@ -1,6 +1,6 @@
1
1
  [mcp_servers.constructor-research]
2
2
  command = "npx"
3
- args = ["-y", "constructor-research-mcp@beta"]
3
+ args = ["-y", "constructor-research-mcp@latest"]
4
4
  # The first start downloads the package.
5
5
  startup_timeout_sec = 60
6
6
  tool_timeout_sec = 30
@@ -5,7 +5,7 @@ import { spawn } from "node:child_process";
5
5
  const WAIT = [
6
6
  "-y",
7
7
  "-p",
8
- "constructor-research-mcp@beta",
8
+ "constructor-research-mcp@latest",
9
9
  "constructor-research-wait",
10
10
  ];
11
11
  // Any CONSTRUCTOR_* settings your MCP entry sets besides the defaults.
@@ -4,7 +4,7 @@
4
4
  "servers": {
5
5
  "constructor-research": {
6
6
  "type": "local",
7
- "command": ["npx", "-y", "constructor-research-mcp@beta"]
7
+ "command": ["npx", "-y", "constructor-research-mcp@latest"]
8
8
  }
9
9
  }
10
10
  }
@@ -3,7 +3,7 @@
3
3
  "mcp": {
4
4
  "constructor-research": {
5
5
  "type": "local",
6
- "command": ["npx", "-y", "constructor-research-mcp@beta"]
6
+ "command": ["npx", "-y", "constructor-research-mcp@latest"]
7
7
  }
8
8
  }
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructor-research-mcp",
3
- "version": "0.4.0-beta.2",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Local deployment MCP for Constructor Research",
6
6
  "license": "MIT",
@@ -56,8 +56,5 @@
56
56
  "prettier": "3.9.10",
57
57
  "tsx": "4.23.15",
58
58
  "typescript": "7.0.2"
59
- },
60
- "publishConfig": {
61
- "tag": "beta"
62
59
  }
63
60
  }
package/dist/login.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/dist/login.js DELETED
@@ -1,25 +0,0 @@
1
- #!/usr/bin/env node
2
- // Sign in from a terminal; the MCP's sign_in tool does the same from an agent session.
3
- // Usage: npx -y -p constructor-research-mcp constructor-research-login [--url <any link to your Constructor>] --for claude-code|codex|opencode (or --to <session file>)
4
- import { configFromEnv, HARNESSES, originOf, sessionArgs } from "./config.js";
5
- import { signIn } from "./signin.js";
6
- const config = configFromEnv();
7
- const args = process.argv.slice(2);
8
- const at = args.indexOf("--url");
9
- const url = at >= 0 ? args.splice(at, 2)[1] : undefined;
10
- const { file } = sessionArgs(args, config);
11
- if (!file || (at >= 0 && !url)) {
12
- console.error(`Usage: npx -y -p constructor-research-mcp constructor-research-login [--url <any link to your Constructor>] --for ${HARNESSES.join("|")} (or --to <session file>)`);
13
- process.exit(2);
14
- }
15
- if (url) {
16
- const host = originOf(url);
17
- if (config.baseUrlFixed && host !== config.baseUrl) {
18
- console.error(`CONSTRUCTOR_BASE_URL fixes the MCP to ${config.baseUrl}.`);
19
- process.exit(2);
20
- }
21
- config.baseUrl = host;
22
- }
23
- const result = await signIn(config, file, () => console.log(`A Chrome window opened at ${config.baseUrl}. Sign in there; it closes by itself afterwards.`));
24
- (result.status === "signed_in" ? console.log : console.error)(result.message);
25
- process.exit(result.status === "signed_in" ? 0 : 1);
package/dist/session.d.ts DELETED
@@ -1,21 +0,0 @@
1
- /** The cookies the MCP keeps: the access token for requests, the refresh token to renew it. */
2
- export declare const SESSION_COOKIES: readonly ["ap_access_token", "ap_id_token", "ap_refresh_token"];
3
- /** Claims of a JWT, or undefined when it is not one. */
4
- export declare function claims(jwt?: string): Record<string, any> | undefined;
5
- /** Session cookies found in a Cookie header, a cURL, a Set-Cookie list or a bare JWT. */
6
- export declare function sessionCookies(text: string): Map<string, string>;
7
- /** The session saved in a cookie file; only its cookie line is read. */
8
- export declare function readSession(file: string): Promise<Map<string, string>>;
9
- /**
10
- * The Constructor (an origin) a saved session belongs to: its host line, written at sign-in,
11
- * or else the issuer of its access token. Undefined when nothing is saved.
12
- */
13
- export declare function sessionHost(file: string): Promise<string | undefined>;
14
- /**
15
- * Replaces the cookie line of a file with these cookies, keeping its other lines, and with
16
- * `host` its host line. Written to a temporary file and renamed, mode 600, so a reader never
17
- * sees half a token and a crash never loses the session.
18
- */
19
- export declare function saveSession(file: string, cookies: Map<string, string>, host?: string): Promise<void>;
20
- /** New session cookies from a response's Set-Cookie headers. */
21
- export declare function setCookies(response: Response): Map<string, string>;
package/dist/session.js DELETED
@@ -1,108 +0,0 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { dirname } from "node:path";
3
- import { randomUUID } from "node:crypto";
4
- /** The cookies the MCP keeps: the access token for requests, the refresh token to renew it. */
5
- export const SESSION_COOKIES = [
6
- "ap_access_token",
7
- "ap_id_token",
8
- "ap_refresh_token",
9
- ];
10
- /** Claims of a JWT, or undefined when it is not one. */
11
- export function claims(jwt) {
12
- try {
13
- return JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString());
14
- }
15
- catch {
16
- return undefined;
17
- }
18
- }
19
- /** Session cookies found in a Cookie header, a cURL, a Set-Cookie list or a bare JWT. */
20
- export function sessionCookies(text) {
21
- const found = new Map();
22
- for (const name of SESSION_COOKIES) {
23
- const value = [
24
- ...text.matchAll(new RegExp(`(?:^|[\\s;'"])${name}=([\\w.~+/=-]+)`, "g")),
25
- ].at(-1)?.[1];
26
- if (value)
27
- found.set(name, value);
28
- }
29
- const bare = /^\s*(ey[\w-]+\.[\w-]+\.[\w-]+)\s*$/.exec(text)?.[1];
30
- if (bare && !found.size)
31
- found.set("ap_access_token", bare);
32
- return found;
33
- }
34
- /** Index of the line holding the tokens in a cookie file, or -1. */
35
- const cookieLine = (lines) => lines.findIndex((l) => /^\s*(Cookie:\s*)?(ey[\w-]+\.|.*\bap_(access|refresh)_token=)/.test(l));
36
- /** The session saved in a cookie file; only its cookie line is read. */
37
- export async function readSession(file) {
38
- const lines = (await readFile(file, "utf8")).split(/\r?\n/);
39
- const line = lines[cookieLine(lines)] ?? "";
40
- if (/[\x00-\x1f]/.test(line))
41
- return new Map();
42
- return sessionCookies(line.trim().replace(/^Cookie:\s*/i, ""));
43
- }
44
- /** The line naming the Constructor the session belongs to. */
45
- const HOST = /^host=(\S+)\s*$/;
46
- /**
47
- * The Constructor (an origin) a saved session belongs to: its host line, written at sign-in,
48
- * or else the issuer of its access token. Undefined when nothing is saved.
49
- */
50
- export async function sessionHost(file) {
51
- let lines;
52
- try {
53
- lines = (await readFile(file, "utf8")).split(/\r?\n/);
54
- }
55
- catch {
56
- return undefined;
57
- }
58
- const named = lines.map((l) => HOST.exec(l)?.[1]).find(Boolean);
59
- const line = lines[cookieLine(lines)] ?? "";
60
- const issuer = claims(sessionCookies(line.replace(/^\s*Cookie:\s*/i, "")).get("ap_access_token"))?.iss;
61
- try {
62
- return new URL(named ?? issuer).origin;
63
- }
64
- catch {
65
- return undefined;
66
- }
67
- }
68
- /**
69
- * Replaces the cookie line of a file with these cookies, keeping its other lines, and with
70
- * `host` its host line. Written to a temporary file and renamed, mode 600, so a reader never
71
- * sees half a token and a crash never loses the session.
72
- */
73
- export async function saveSession(file, cookies, host) {
74
- let lines = [];
75
- try {
76
- lines = (await readFile(file, "utf8")).split(/\r?\n/);
77
- }
78
- catch (e) {
79
- if (e.code !== "ENOENT")
80
- throw e;
81
- }
82
- const line = SESSION_COOKIES.filter((n) => cookies.get(n))
83
- .map((n) => `${n}=${cookies.get(n)}`)
84
- .join("; ");
85
- const i = cookieLine(lines);
86
- if (i >= 0)
87
- lines[i] = line;
88
- else
89
- lines.unshift(line);
90
- if (host) {
91
- lines = lines.filter((l) => !HOST.test(l));
92
- lines.splice(lines.indexOf(line) + 1, 0, `host=${host}`);
93
- }
94
- await mkdir(dirname(file), { recursive: true });
95
- const tmp = `${file}.${randomUUID()}.tmp`;
96
- await writeFile(tmp, lines.join("\n").replace(/\n*$/, "\n"), {
97
- mode: 0o600,
98
- flag: "wx",
99
- });
100
- await rename(tmp, file);
101
- }
102
- /** New session cookies from a response's Set-Cookie headers. */
103
- export function setCookies(response) {
104
- return sessionCookies(response.headers
105
- .getSetCookie()
106
- .map((c) => c.split(";")[0])
107
- .join("; "));
108
- }
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/dist/set-token.js DELETED
@@ -1,48 +0,0 @@
1
- #!/usr/bin/env node
2
- // Save the session from a copied cURL (or a bare token) for the MCP without printing it.
3
- // Usage: npx -y -p constructor-research-mcp constructor-research-set-token <file with a copied cURL, or a token> --for claude-code|codex|opencode
4
- // (or --to <session file>); the session belongs to the Constructor the cURL was sent to.
5
- import { readFileSync } from "node:fs";
6
- import { configFromEnv, HARNESSES, originOf, sessionArgs } from "./config.js";
7
- import { claims, saveSession, sessionCookies } from "./session.js";
8
- const { file: target, rest } = sessionArgs(process.argv.slice(2), configFromEnv());
9
- const source = rest[0];
10
- if (!source || !target) {
11
- console.error(`Usage: npx -y -p constructor-research-mcp constructor-research-set-token <file with a copied cURL> --for ${HARNESSES.join("|")} (or --to <session file>)`);
12
- process.exit(2);
13
- }
14
- const text = readFileSync(source, "utf8");
15
- const found = sessionCookies(text);
16
- const token = found.get("ap_access_token");
17
- if (!token) {
18
- console.error("No ap_access_token found in " + source + ".");
19
- process.exit(1);
20
- }
21
- const { exp, max_slt } = claims(token) ?? {};
22
- if (exp && exp * 1000 <= Date.now() && !found.has("ap_refresh_token")) {
23
- console.error("That token already expired at " +
24
- new Date(exp * 1000).toISOString() +
25
- "; copy a fresh one.");
26
- process.exit(1);
27
- }
28
- // The Constructor the cURL was sent to; a bare token names its own issuer.
29
- const sent = /\bcurl\s+(?:-\S+\s+)*['"]?(https?:\/\/[^\s'"]+)/.exec(text)?.[1];
30
- let host;
31
- try {
32
- host = sent ? originOf(sent) : undefined;
33
- }
34
- catch { }
35
- await saveSession(target, found, host);
36
- const time = (s) => new Date(s * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
37
- console.log("Saved to " +
38
- target +
39
- (host ? ` (for ${host})` : "") +
40
- (found.has("ap_refresh_token")
41
- ? `, with the refresh token: the MCP renews the session itself${max_slt ? " until " + time(max_slt) : ""}. The browser this cURL came from holds the same session, and a refresh token works once: whichever renews first logs the other out. The sign_in tool (or constructor-research-login) gives the MCP a session of its own.`
42
- : exp
43
- ? "; expires " +
44
- time(exp) +
45
- " (in " +
46
- Math.round((exp * 1000 - Date.now()) / 60000) +
47
- " min). Copy the cURL with the ap_refresh_token cookie, or use the sign_in tool, and the MCP renews it itself."
48
- : "."));
package/dist/signin.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { Config } from "./config.js";
2
- export type SignInResult = {
3
- status: "signed_in";
4
- message: string;
5
- session_file: string;
6
- host: string;
7
- until?: string;
8
- } | {
9
- status: "sign_in_failed";
10
- message: string;
11
- };
12
- /** A Chromium-based browser on macOS, Windows or Linux; CONSTRUCTOR_BROWSER overrides. */
13
- export declare function findBrowser(): string | undefined;
14
- /**
15
- * Opens the sign-in window, waits for the user to sign in (up to 15 min), saves the
16
- * session cookies to `file`, and closes the window at once. Never returns a token.
17
- * `opened` runs once the window is up.
18
- */
19
- export declare function signIn(config: Pick<Config, "baseUrl" | "apiPath" | "requestTimeoutMs">, file: string, opened?: () => void): Promise<SignInResult>;
package/dist/signin.js DELETED
@@ -1,209 +0,0 @@
1
- // Sign in to Constructor in a separate Chrome window and save the session.
2
- // The window uses a fresh temporary profile: a session nothing else holds, so the MCP can
3
- // renew it without logging out the user's own browser (a refresh token works only once).
4
- import { spawn } from "node:child_process";
5
- import { existsSync } from "node:fs";
6
- import { mkdtemp, readFile, rm } from "node:fs/promises";
7
- import { homedir, tmpdir } from "node:os";
8
- import { delimiter, join } from "node:path";
9
- import { setTimeout as delay } from "node:timers/promises";
10
- import { claims, saveSession, setCookies, SESSION_COOKIES } from "./session.js";
11
- const SIGN_IN_MINUTES = 15;
12
- /** A Chromium-based browser on macOS, Windows or Linux; CONSTRUCTOR_BROWSER overrides. */
13
- export function findBrowser() {
14
- if (process.env.CONSTRUCTOR_BROWSER)
15
- return existsSync(process.env.CONSTRUCTOR_BROWSER)
16
- ? process.env.CONSTRUCTOR_BROWSER
17
- : undefined;
18
- const env = process.env;
19
- const installed = process.platform === "win32"
20
- ? [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA]
21
- .filter((d) => !!d)
22
- .flatMap((d) => [
23
- join(d, "Google", "Chrome", "Application", "chrome.exe"),
24
- join(d, "Microsoft", "Edge", "Application", "msedge.exe"),
25
- join(d, "Chromium", "Application", "chrome.exe"),
26
- join(d, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
27
- ])
28
- : process.platform === "darwin"
29
- ? [
30
- "Google Chrome.app/Contents/MacOS/Google Chrome",
31
- "Chromium.app/Contents/MacOS/Chromium",
32
- "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
33
- "Brave Browser.app/Contents/MacOS/Brave Browser",
34
- ].flatMap((app) => [
35
- join("/Applications", app),
36
- join(homedir(), "Applications", app),
37
- ])
38
- : [];
39
- // Then the PATH, as Linux installs them (and any OS where the user put one there).
40
- const names = [
41
- "google-chrome",
42
- "google-chrome-stable",
43
- "chromium",
44
- "chromium-browser",
45
- "microsoft-edge",
46
- "brave-browser",
47
- "chrome",
48
- "msedge",
49
- ];
50
- const exts = process.platform === "win32"
51
- ? (env.PATHEXT ?? ".EXE").split(";").filter(Boolean)
52
- : [""];
53
- const onPath = (env.PATH ?? "")
54
- .split(delimiter)
55
- .filter(Boolean)
56
- .flatMap((dir) => names.flatMap((n) => exts.map((e) => join(dir, n + e.toLowerCase()))));
57
- return [...installed, ...onPath].find((c) => existsSync(c));
58
- }
59
- /** Minimal Chrome DevTools Protocol client over the browser's WebSocket. */
60
- async function devtools(url) {
61
- const ws = new WebSocket(url);
62
- await new Promise((ok, fail) => {
63
- ws.onopen = ok;
64
- ws.onerror = () => fail(new Error("Could not connect to the browser."));
65
- });
66
- let id = 0;
67
- const waiting = new Map();
68
- ws.onmessage = (e) => {
69
- const m = JSON.parse(String(e.data));
70
- waiting.get(m.id)?.(m);
71
- waiting.delete(m.id);
72
- };
73
- return {
74
- send(method, params = {}) {
75
- return new Promise((ok, fail) => {
76
- const n = ++id;
77
- waiting.set(n, (m) => m.error ? fail(new Error(m.error.message)) : ok(m.result));
78
- ws.send(JSON.stringify({ id: n, method, params }));
79
- });
80
- },
81
- close: () => ws.close(),
82
- };
83
- }
84
- /**
85
- * Opens the sign-in window, waits for the user to sign in (up to 15 min), saves the
86
- * session cookies to `file`, and closes the window at once. Never returns a token.
87
- * `opened` runs once the window is up.
88
- */
89
- export async function signIn(config, file, opened = () => { }) {
90
- const fallback = `save a session from a copied cURL instead: npx -y -p constructor-research-mcp constructor-research-set-token <file with the cURL> --to ${file}`;
91
- const headless = !!process.env.CONSTRUCTOR_LOGIN_HEADLESS;
92
- if (process.platform === "linux" &&
93
- !headless &&
94
- !process.env.DISPLAY &&
95
- !process.env.WAYLAND_DISPLAY)
96
- return {
97
- status: "sign_in_failed",
98
- message: `This machine has no screen to open a sign-in window on (no DISPLAY or WAYLAND_DISPLAY). Sign in where the MCP has a desktop, or ${fallback}.`,
99
- };
100
- const exe = findBrowser();
101
- if (!exe)
102
- return {
103
- status: "sign_in_failed",
104
- message: `No Chrome, Edge, Chromium or Brave found. Set CONSTRUCTOR_BROWSER in the MCP settings to the browser's executable, or ${fallback}.`,
105
- };
106
- const host = new URL(config.baseUrl).hostname;
107
- const profile = await mkdtemp(join(tmpdir(), "constructor-login-"));
108
- const chrome = spawn(exe, [
109
- `--user-data-dir=${profile}`,
110
- "--remote-debugging-port=0",
111
- "--remote-allow-origins=http://127.0.0.1",
112
- "--no-first-run",
113
- "--no-default-browser-check",
114
- "--disable-sync",
115
- // Tests run the browser without a window.
116
- ...(headless ? ["--headless=new"] : []),
117
- "--new-window",
118
- `${config.baseUrl}/research/`,
119
- ], { stdio: "ignore" });
120
- let exited = false;
121
- chrome.on("exit", () => (exited = true));
122
- chrome.on("error", () => (exited = true));
123
- const failed = (message) => ({
124
- status: "sign_in_failed",
125
- message,
126
- });
127
- try {
128
- let port, path;
129
- for (let i = 0; i < 300 && !port && !exited; i++) {
130
- try {
131
- [port, path] = (await readFile(join(profile, "DevToolsActivePort"), "utf8")).split("\n");
132
- }
133
- catch {
134
- await delay(100);
135
- }
136
- }
137
- if (!port)
138
- return failed(`The browser did not start (${exe}); ${fallback}.`);
139
- const cdp = await devtools(`ws://127.0.0.1:${port}${path}`);
140
- opened();
141
- const session = async () => {
142
- const { cookies } = await cdp.send("Storage.getCookies");
143
- return new Map(cookies
144
- .filter((c) => SESSION_COOKIES.includes(c.name) &&
145
- (c.domain.replace(/^\./, "") === host ||
146
- host.endsWith(c.domain.startsWith(".") ? c.domain : "." + c.domain)))
147
- .map((c) => [c.name, c.value]));
148
- };
149
- const deadline = Date.now() + SIGN_IN_MINUTES * 60000;
150
- let found;
151
- while (!exited && Date.now() < deadline) {
152
- const s = await session().catch(() => undefined);
153
- const exp = claims(s?.get("ap_access_token"))?.exp;
154
- if (s?.has("ap_refresh_token") && exp && exp * 1000 > Date.now()) {
155
- // The page may still be loading; read again once it settles, then close at once so
156
- // the window never renews this session itself.
157
- await delay(3000);
158
- found = (await session().catch(() => undefined)) ?? s;
159
- break;
160
- }
161
- await delay(1000);
162
- }
163
- await cdp.send("Browser.close").catch(() => { });
164
- cdp.close();
165
- if (!found)
166
- return failed(exited
167
- ? "The window was closed before sign-in finished; nothing was saved."
168
- : `No sign-in within ${SIGN_IN_MINUTES} min; nothing was saved.`);
169
- // Check the access token without sending the refresh token, so nothing is renewed.
170
- const response = await fetch(config.baseUrl + config.apiPath + "/auth/session", {
171
- headers: {
172
- Cookie: `ap_access_token=${found.get("ap_access_token")}`,
173
- Accept: "application/json",
174
- },
175
- redirect: "manual",
176
- signal: AbortSignal.timeout(config.requestTimeoutMs),
177
- }).catch(() => undefined);
178
- await response?.body?.cancel();
179
- if (response?.status === 401)
180
- return failed("Constructor rejected the new session; nothing was saved.");
181
- await saveSession(file, new Map([...found, ...(response ? setCookies(response) : [])]), config.baseUrl);
182
- const end = claims(found.get("ap_access_token"))?.max_slt;
183
- const until = end
184
- ? new Date(end * 1000).toISOString().slice(0, 16).replace("T", " ") +
185
- " UTC"
186
- : undefined;
187
- return {
188
- status: "signed_in",
189
- message: `Signed in to ${config.baseUrl}. Session saved to ${file}` +
190
- (until ? `; the MCP renews it automatically until ${until}.` : "."),
191
- session_file: file,
192
- host: config.baseUrl,
193
- until,
194
- };
195
- }
196
- catch (e) {
197
- return failed(`Sign-in failed: ${e?.message ?? e}. Nothing was saved.`);
198
- }
199
- finally {
200
- if (!exited) {
201
- chrome.kill();
202
- for (let i = 0; i < 50 && !exited; i++)
203
- await delay(100);
204
- if (!exited)
205
- chrome.kill("SIGKILL"); // TerminateProcess on Windows
206
- }
207
- await rm(profile, { recursive: true, force: true }).catch(() => { });
208
- }
209
- }