constructor-research-mcp 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/INSTALL.md CHANGED
@@ -82,13 +82,16 @@ npx -y -p constructor-research-mcp@latest constructor-research-set-key https://c
82
82
 
83
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.
84
84
 
85
- ## 3. Optional: get told when a deployment finishes
85
+ ## 3. Recommended: wait for builds
86
86
 
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.
87
+ Builds take minutes, and some agents (Codex in particular) end their turn before a build finishes, so the user has to ask again. The wait hook keeps the agent on it until the deployment ends. One command adds it, leaving your other settings and hooks as they are:
88
88
 
89
- - Claude Code: merge [examples/claude-hooks.json](examples/claude-hooks.json) into `~/.claude/settings.json`.
90
- - Codex: copy [examples/codex-hooks.json](examples/codex-hooks.json) to `~/.codex/hooks.json`, then trust it in `/hooks`.
91
- - OpenCode: copy [examples/opencode-plugin.js](examples/opencode-plugin.js) to `~/.config/opencode/plugins/`.
89
+ ```sh
90
+ npx -y -p constructor-research-mcp@latest constructor-research-wait --install codex # ~/.codex/hooks.json
91
+ npx -y -p constructor-research-mcp@latest constructor-research-wait --install claude-code # ~/.claude/settings.json
92
+ ```
93
+
94
+ Restart the tool; in Codex, trust the new hook in `/hooks`. The hook only watches the deployments the MCP runs, so it works with the key in the MCP settings too. By hand: merge [examples/codex-hooks.json](examples/codex-hooks.json) or [examples/claude-hooks.json](examples/claude-hooks.json). OpenCode: copy [examples/opencode-plugin.js](examples/opencode-plugin.js) to `~/.config/opencode/plugins/`.
92
95
 
93
96
  ## Update
94
97
 
package/README.md CHANGED
@@ -177,9 +177,9 @@ Private DNS works between containers; browser JavaScript needs a public backend
177
177
 
178
178
  ### Image reuse and limits
179
179
 
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.
180
+ Replace a service's `build` with `"image_id":"IMAGE_ID"` to skip building, or with `"image":"registry/repo:tag"` to run a registry image unchanged, such as `jgraph/drawio:latest` from Docker Hub. Which of `build`, `image` and `image_id` fits is the agent's choice; the tool descriptions say what each one does. `list_images` returns compact records with `source` (`desk_build` or `external`), `reference` and `build_status` (`not_started`, `snapshot_creation`, `in_progress`, `done` or `error`); `detailed:true` returns full records.
181
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.
182
+ With `image`, the MCP first looks for it in the project (by `reference` or name). External images there (`source: external`) are pulled, not built, so they are used whatever their build status, unless it is `error`. An image the project does not have is built on the desk from a one-line `FROM <image>` Dockerfile that the MCP writes to `.constructor/images/<name>/`, because the public API cannot add an external image yet.
183
183
 
184
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**.
185
185
  - Each service can have multiple ports (1–65535), with at most **one public port**. That port must match where the container listens.
@@ -57,7 +57,7 @@ export declare class DeploymentEngine {
57
57
  * when there is none and `create` is given, otherwise the user chooses.
58
58
  */
59
59
  deskFor(project: string, create?: string): Promise<string>;
60
- /** Turn each service's `image` (reference or name) into the project's image_id. */
60
+ /** Turn each service's `image` into the project's image_id when the project has it (by reference or name); others are left as `image`. */
61
61
  resolveImages(project: string, services: any[]): Promise<any[]>;
62
62
  listImages(raw: unknown): Promise<{
63
63
  results: any[];
@@ -400,7 +400,7 @@ export class DeploymentEngine {
400
400
  });
401
401
  return d.id;
402
402
  }
403
- /** Turn each service's `image` (reference or name) into the project's image_id. */
403
+ /** Turn each service's `image` into the project's image_id when the project has it (by reference or name); others are left as `image`. */
404
404
  async resolveImages(project, services) {
405
405
  if (!services?.some((s) => s.image))
406
406
  return services;
@@ -414,10 +414,9 @@ export class DeploymentEngine {
414
414
  ? (hits.find((x) => x.reference === want) ??
415
415
  bad(`Image "${want}" for ${s.name} matches several images: ${hits.map((x) => x.id).join(", ")}. Pass image_id.`))
416
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
- }
417
+ // Not in the project: the caller builds it from a one-line FROM Dockerfile.
418
+ if (!im)
419
+ return s;
421
420
  const { image: _i, ...rest } = s;
422
421
  return { ...rest, image_id: im.id };
423
422
  });
@@ -568,6 +567,8 @@ export class DeploymentEngine {
568
567
  const images = op.project_id ? await this.images(op.project_id) : [];
569
568
  if (op.project_id)
570
569
  input.services = await this.resolveImages(op.project_id, input.services);
570
+ if (input.services.some((s) => s.image))
571
+ bad("In a resume, image must name an image already in the project; for a new registry image, send a new deploy_app or update_app.");
571
572
  for (const override of input.services) {
572
573
  const at = next.findIndex((s) => s.name === override.name);
573
574
  if (at < 0)
@@ -1293,7 +1294,7 @@ export class DeploymentEngine {
1293
1294
  ? `${this.api.keyHelp("Constructor rejected the access key, or none is set.")} Then call get_deployment with this deployment_id.`
1294
1295
  : op.status === "needs_upload"
1295
1296
  ? "Upload files with sync_files, then call get_deployment with files_uploaded=true."
1296
- : "Execution continues automatically in the MCP. Keep calling get_deployment with wait_seconds=20 until it is finished, then tell the user the result; do not orchestrate individual steps.",
1297
+ : "Execution continues automatically in the MCP. Keep calling get_deployment with wait_seconds=45 until it is finished, then tell the user the result; do not orchestrate individual steps.",
1297
1298
  };
1298
1299
  if (cache) {
1299
1300
  op.result = result;
package/dist/runtime.js CHANGED
@@ -220,7 +220,7 @@ export class DeploymentRuntime {
220
220
  ? "Inspect the uncertain mutation in Constructor before submitting a new operation."
221
221
  : terminal.has(op.status)
222
222
  ? undefined
223
- : `Not finished yet; builds often take several minutes. Do not end your turn or answer the user until execution is finished: they asked for the result (the public_url, or what failed). Finish any other work of this request, then wait with the shell command \`${waitCommand(this.engine.api.config, [op.id])}\`; it prints the outcome when the deployment finishes. Run it in the foreground, or in the background only if your client wakes you when a background command ends. Without a shell, keep calling get_deployment with wait_seconds=20 until execution is finished.`,
223
+ : `NOT FINISHED: do not answer the user yet. Run now, in the foreground: \`${waitCommand(this.engine.api.config, [op.id])}\`. It returns when the deployment ends and prints the public URL or what failed. No shell: call get_deployment with this deployment_id and wait_seconds=45 again, until it is finished.`,
224
224
  };
225
225
  }
226
226
  async wait(id, milliseconds) {
package/dist/schemas.js CHANGED
@@ -49,6 +49,13 @@ const wait = z
49
49
  .max(20)
50
50
  .default(20)
51
51
  .describe("Wait up to this many seconds for completion; execution continues in the MCP after the response.");
52
+ /** get_deployment only: longer, so fewer calls; stays under the 60 s tool timeout of Codex. */
53
+ const longWait = z
54
+ .number()
55
+ .min(0)
56
+ .max(50)
57
+ .default(45)
58
+ .describe("Wait up to this many seconds (max 50) for the deployment to finish; it continues in the MCP after the response.");
52
59
  const requestId = z
53
60
  .string()
54
61
  .min(1)
@@ -107,9 +114,10 @@ export const serviceInput = z
107
114
  image: z
108
115
  .string()
109
116
  .min(1)
110
- .max(512)
117
+ .max(256)
118
+ .regex(/^[a-z0-9][a-z0-9._\/:@-]*$/i, "image is a registry reference such as jgraph/drawio:latest or ghcr.io/org/app:1.2.")
111
119
  .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."),
120
+ .describe("A registry image reference (docker.io/jgraph/drawio:latest, ghcr.io/org/app:1.2) or the name of an image already in the project; the alternative to build and image_id. If the project has it (an external image added in Constructor, or an earlier build), it is used as is. Otherwise the MCP builds it on the desk from a one-line FROM <image> Dockerfile, so the image runs unchanged; to add files or change it, use build with your own Dockerfile. The service's ports must match the port the image listens on."),
113
121
  build: build.optional(),
114
122
  hardware: z
115
123
  .strictObject({
@@ -176,7 +184,7 @@ export const getInput = z
176
184
  application_id: id.optional(),
177
185
  files_uploaded: z.boolean().optional(),
178
186
  resume: z.boolean().default(true),
179
- wait_seconds: wait,
187
+ wait_seconds: longWait,
180
188
  })
181
189
  .refine((x) => !x.application_id || !!x.project_id || !!x.desk_url, "application_id requires desk_url or project_id.")
182
190
  .refine((x) => x.resume || x.files_uploaded === undefined, "files_uploaded cannot be set in observation mode.");
package/dist/server.js CHANGED
@@ -7,7 +7,9 @@ import { StateStore } from "./store.js";
7
7
  import { DeploymentEngine } from "./deployment.js";
8
8
  import { DeploymentRuntime } from "./runtime.js";
9
9
  import { FileManager, dockerignore } from "./files.js";
10
- import { basename } from "node:path";
10
+ import { basename, join } from "node:path";
11
+ import { mkdir, writeFile } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
11
13
  import { LogFollower } from "./logs.js";
12
14
  const RULES = "Dockerfile rules: one Dockerfile per service named Dockerfile or <name>.dockerfile; docker-compose is not supported. The Dockerfile must build everything itself; no separate setup script the user runs before the build. The app listens on 0.0.0.0 on a fixed port; only one port per service can be public. Services reach each other through internal references (bare host:port by default, http:// only when scheme is set), never localhost; do not bake compose-style fallback hosts (http://db:5432) into ENV. Files uploaded to a desk lose the executable bit: RUN chmod 0755 any entrypoint script you COPY. In nginx configs use only the IPv4 listen line. A volume belongs to one service; services cannot share a volume. Volume data survives restarts and image changes but is wiped if the service is deleted or the volume is removed or changed. The build context is the folder containing the Dockerfile, exactly like a local docker build in that folder. Test the image locally (docker build/run) before uploading.";
13
15
  import { located, resolveDeskUrl } from "./location.js";
@@ -41,13 +43,38 @@ async function main() {
41
43
  const checked = (fn, single = false) => async (a) => {
42
44
  const begun = Date.now();
43
45
  if (!single && a.project_id && a.services) {
44
- // External images by reference or name; builds without a desk go to the project's desk.
46
+ // Images the project has by reference or name; builds without a desk go to the project's desk.
45
47
  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);
48
+ if (services.some((x) => x.image || (x.build && !x.build.desk_id))) {
49
+ const here = config.localDesk;
50
+ const desk = here && a.project_id === here.projectId
51
+ ? here.deskId
52
+ : await engine.deskFor(a.project_id, `${a.application_name ?? "application"}-source`);
53
+ services = await Promise.all(services.map(async (x) => {
54
+ if (x.build && !x.build.desk_id)
55
+ return { ...x, build: { ...x.build, desk_id: desk } };
56
+ if (!x.image)
57
+ return x;
58
+ // A registry image the project does not have: build it from a one-line Dockerfile.
59
+ if (!/^[a-z0-9][a-z0-9._/:@-]*$/i.test(x.image))
60
+ throw new ToolError("invalid_input", `Service ${x.name}: invalid image reference.`);
61
+ const slug = x.image
62
+ .toLowerCase()
63
+ .replace(/[^a-z0-9]+/g, "-")
64
+ .replace(/^-|-$/g, "")
65
+ .slice(0, 80);
66
+ const remote = `.constructor/images/${slug}`;
67
+ const dir = here && desk === here.deskId
68
+ ? join(here.root, remote)
69
+ : join(tmpdir(), "constructor-research-images", slug);
70
+ await mkdir(dir, { recursive: true });
71
+ await writeFile(join(dir, "Dockerfile"), `FROM ${x.image}\n`);
72
+ const { image: _i, ...rest } = x;
73
+ return {
74
+ ...rest,
75
+ build: { desk_id: desk, local_path: dir, remote_path: remote },
76
+ };
77
+ }));
51
78
  }
52
79
  a = { ...a, services };
53
80
  }
@@ -167,7 +194,7 @@ async function main() {
167
194
  ? 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) + " ")
168
195
  : text;
169
196
  const server = new McpServer({ name: "constructor-research", version: VERSION }, {
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.`),
197
+ 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. A service can also take image: a registry reference (repo:tag) that runs unchanged. The MCP uses the copy in the project when there is one (list_images shows source and reference), otherwise builds it from FROM <image>. 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, run the wait command that next_action names (with a shell), or call get_deployment(wait_seconds=45) again until it is finished; never perform the deployment steps yourself. Never end the turn while a deployment the user asked for is still running. 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.`),
171
198
  });
172
199
  const register = (name, description, schema, fn, readOnly = false, budget = 20000, scope) => {
173
200
  const here = config.localDesk && DESK_DEFAULT.has(name) ? config.localDesk : undefined;
@@ -213,7 +240,7 @@ async function main() {
213
240
  type: "text",
214
241
  text: result.text ??
215
242
  (result.status
216
- ? `${result.status}${result.deployment_id ? ` (${result.deployment_id})` : ""}${result.message ? `: ${result.message}` : ""}`
243
+ ? `${result.status}${result.deployment_id ? ` (${result.deployment_id})` : ""}${result.message ? `: ${result.message}` : ""}${result.execution === "background" && result.next_action ? `\n${result.next_action}` : ""}`
217
244
  : `Discovery result: ${result.total !== undefined ? result.total + " images" : Object.keys(result).join(", ")}. See structuredContent for details.`),
218
245
  },
219
246
  ],
@@ -262,7 +289,7 @@ async function main() {
262
289
  register("update_app", "Update/add selected services in one request; preserve omitted settings. MCP handles builds, links and restarts in the background. Environment variables merge; supplied port/volume lists replace their lists. Resume a failed update using deployment_id and service overrides. The Dockerfile rules in deploy_app apply.", updateInput, checked((a) => runtime.update(a)), false, 60000, "deploy");
263
290
  register("start_app", "Start all or selected services as one operation. MCP handles all requests. Waits up to wait_seconds (default 20); remaining execution continues in the background. Started does not mean ready.", lifecycleInput, (a) => runtime.lifecycle("start", a), false, 20000, "project");
264
291
  register("stop_app", "Stop all or selected services as one operation. MCP handles all requests. Waits up to wait_seconds (default 20). Stopped means stop requests accepted, not verified teardown.", lifecycleInput, (a) => runtime.lifecycle("stop", a), false, 20000, "project");
265
- register("get_deployment", "With deployment_id, observe/wait for background execution; the MCP owns execution. Each call waits up to wait_seconds (max 20); to wait longer, call again, as often as needed (a loop of get_deployment calls is fine), until execution is finished; do not answer the user while it is still in the background. Services carry status_changes and restarts_seen when the MCP saw the status change or a new container start. After sync_files (or manual upload) set files_uploaded=true; after a new key is saved, checking the job resumes it. With no arguments, returns the map of all deployments: every deployment-enabled project with its applications and services (names, native statuses, public URLs, ports). With desk_url or project_id, returns that project's desks, images, hardware and applications; add application_id for one application. resume=false observes only. Never returns environment-variable values.", getInput, (a) => runtime.get(a), false, 20000, "deploy");
292
+ register("get_deployment", "With deployment_id, observe/wait for background execution; the MCP owns execution. Each call waits up to wait_seconds (default 45, max 50); to wait longer, call again, as often as needed (a loop of get_deployment calls is fine), until execution is finished; do not answer the user while it is still in the background. Services carry status_changes and restarts_seen when the MCP saw the status change or a new container start. After sync_files (or manual upload) set files_uploaded=true; after a new key is saved, checking the job resumes it. With no arguments, returns the map of all deployments: every deployment-enabled project with its applications and services (names, native statuses, public URLs, ports). With desk_url or project_id, returns that project's desks, images, hardware and applications; add application_id for one application. resume=false observes only. Never returns environment-variable values.", getInput, (a) => runtime.get(a), false, 55000, "deploy");
266
293
  register("get_logs", "Last lines (default 20, up to 50) of a build or service log: why a build or start failed, how far a long build got, what a starting service prints. Constructor serves logs only live: a build log while the build runs, a service log for its current container while it runs (both replayed from the start, then streamed). The MCP follows the builds and services it starts or shows and keeps their last 50 lines, so they stay readable after the build ends or the container restarts; anything else can be read only while it runs. When a new container starts, the lines of the one before stay, above a '--- new container' marker, and restarts_seen counts them: that answers whether a service keeps restarting and why. An empty service log on a running service usually means a crash loop.", logsInput, async (a) => {
267
294
  const i = logsInput.parse(a);
268
295
  let targets = [];
package/dist/wait.d.ts CHANGED
@@ -24,3 +24,38 @@ export declare function active(store: StateStore): Promise<string[]>;
24
24
  export declare function waitFor(runtime: DeploymentRuntime, ids: string[], { maxMs, staleMs, pollMs }: WaitOptions): Promise<WaitResult>;
25
25
  /** One line per deployment, for an agent to read. */
26
26
  export declare function summary({ results, running }: WaitResult): string;
27
+ declare const HOOKS: {
28
+ readonly codex: {
29
+ readonly file: () => string;
30
+ readonly event: "Stop";
31
+ readonly entry: {
32
+ readonly hooks: readonly [{
33
+ readonly type: "command";
34
+ readonly command: "npx -y -p constructor-research-mcp@latest constructor-research-wait --hook codex";
35
+ readonly timeout: 600;
36
+ readonly statusMessage: "Waiting for Constructor deployments";
37
+ }];
38
+ };
39
+ readonly next: "Restart Codex and trust the new hook in /hooks.";
40
+ };
41
+ readonly "claude-code": {
42
+ readonly file: () => string;
43
+ readonly event: "PostToolUse";
44
+ readonly entry: {
45
+ readonly matcher: "mcp__constructor-research__(deploy_app|update_app|build_image|start_app|stop_app|get_deployment)";
46
+ readonly hooks: readonly [{
47
+ readonly type: "command";
48
+ readonly command: "npx -y -p constructor-research-mcp@latest constructor-research-wait --hook claude-code";
49
+ readonly asyncRewake: true;
50
+ }];
51
+ };
52
+ readonly next: "Restart Claude Code.";
53
+ };
54
+ };
55
+ /** Add the wait hook to the client's settings once; other settings and hooks stay as they are. */
56
+ export declare function installHook(client: keyof typeof HOOKS, file?: string): Promise<{
57
+ path: string;
58
+ added: boolean;
59
+ next: "Restart Claude Code." | "Restart Codex and trust the new hook in /hooks.";
60
+ }>;
61
+ export {};
package/dist/wait.js CHANGED
@@ -7,7 +7,9 @@
7
7
  */
8
8
  import { setTimeout as delay } from "node:timers/promises";
9
9
  import { readFile, unlink, writeFile } from "node:fs/promises";
10
- import { join } from "node:path";
10
+ import { dirname, join } from "node:path";
11
+ import { homedir } from "node:os";
12
+ import { mkdir } from "node:fs/promises";
11
13
  import { realpathSync } from "node:fs";
12
14
  import { fileURLToPath } from "node:url";
13
15
  import { configFromEnv } from "./config.js";
@@ -129,7 +131,63 @@ async function claim(dir, id) {
129
131
  }
130
132
  return () => unlink(file).catch(() => { });
131
133
  }
134
+ /** The hook entry each client needs, as in examples/ (claude-hooks.json, codex-hooks.json). */
135
+ const HOOK = "npx -y -p constructor-research-mcp@latest constructor-research-wait";
136
+ const HOOKS = {
137
+ codex: {
138
+ file: () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json"),
139
+ event: "Stop",
140
+ entry: {
141
+ hooks: [
142
+ {
143
+ type: "command",
144
+ command: `${HOOK} --hook codex`,
145
+ timeout: 600,
146
+ statusMessage: "Waiting for Constructor deployments",
147
+ },
148
+ ],
149
+ },
150
+ next: "Restart Codex and trust the new hook in /hooks.",
151
+ },
152
+ "claude-code": {
153
+ file: () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "settings.json"),
154
+ event: "PostToolUse",
155
+ entry: {
156
+ matcher: "mcp__constructor-research__(deploy_app|update_app|build_image|start_app|stop_app|get_deployment)",
157
+ hooks: [
158
+ {
159
+ type: "command",
160
+ command: `${HOOK} --hook claude-code`,
161
+ asyncRewake: true,
162
+ },
163
+ ],
164
+ },
165
+ next: "Restart Claude Code.",
166
+ },
167
+ };
168
+ /** Add the wait hook to the client's settings once; other settings and hooks stay as they are. */
169
+ export async function installHook(client, file) {
170
+ const h = HOOKS[client];
171
+ const path = file ?? h.file();
172
+ let settings = {};
173
+ try {
174
+ settings = JSON.parse(await readFile(path, "utf8"));
175
+ }
176
+ catch (err) {
177
+ if (err?.code !== "ENOENT")
178
+ throw new Error(`${path} is not valid JSON; nothing was changed.`);
179
+ }
180
+ settings.hooks ??= {};
181
+ const list = (settings.hooks[h.event] ??= []);
182
+ if (JSON.stringify(list).includes("constructor-research-wait"))
183
+ return { path, added: false, next: h.next };
184
+ list.push(h.entry);
185
+ await mkdir(dirname(path), { recursive: true });
186
+ await writeFile(path, JSON.stringify(settings, null, 2) + "\n");
187
+ return { path, added: true, next: h.next };
188
+ }
132
189
  const USAGE = `Usage: constructor-research-wait [deployment_id ...] [--max-minutes N] [--hook claude-code|codex|opencode]
190
+ constructor-research-wait --install codex|claude-code
133
191
 
134
192
  Waits until the deployments finish (all in-progress ones when no ID is given) and prints one line each.
135
193
  Exit codes: 0 finished, 2 needs the user (failed, key, upload, confirmation), 3 still running at the
@@ -137,13 +195,30 @@ time limit, 4 nothing to wait for, 1 usage error.
137
195
 
138
196
  --hook claude-code PostToolUse hook with asyncRewake: waits for the deployment in the tool result and
139
197
  wakes Claude with the outcome (exit 2). opencode: the same, for the plugin.
140
- --hook codex Stop hook: waits for in-progress deployments, then continues the turn with the outcome.`;
198
+ --hook codex Stop hook: waits for in-progress deployments, then continues the turn with the outcome.
199
+ --install CLIENT Add that hook to ~/.codex/hooks.json or ~/.claude/settings.json (once; nothing else changes).`;
141
200
  async function main(argv) {
142
201
  const ids = [];
143
202
  let hook;
144
203
  let minutes;
145
204
  for (let i = 0; i < argv.length; i++) {
146
205
  const a = argv[i];
206
+ if (a === "--install") {
207
+ const client = argv[++i];
208
+ if (client !== "codex" && client !== "claude-code") {
209
+ console.error(USAGE);
210
+ return EXIT.error;
211
+ }
212
+ try {
213
+ const r = await installHook(client);
214
+ console.log(`${r.added ? "Added the wait hook to" : "The wait hook is already in"} ${r.path}. ${r.next} The hook reads the access key from the key file (constructor-research-set-key), not from the MCP settings.`);
215
+ return EXIT.done;
216
+ }
217
+ catch (err) {
218
+ console.error(err?.message ?? String(err));
219
+ return EXIT.error;
220
+ }
221
+ }
147
222
  if (a === "--hook")
148
223
  hook = argv[++i];
149
224
  else if (a === "--max-minutes")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructor-research-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "description": "Local deployment MCP for Constructor Research",
6
6
  "license": "MIT",