constructor-research-mcp 0.6.3 → 0.6.5

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
@@ -70,6 +70,8 @@ The first start downloads the package and can exceed Codex's 10-second start lim
70
70
  [mcp_servers.constructor-research]
71
71
  command = "npx"
72
72
  args = ["-y", "constructor-research-mcp@latest"]
73
+ # Inside a Constructor desk: pass the desk and its access key on (Codex passes only a few variables).
74
+ env_vars = ["ROLOS_PROJECT_ID", "ROLOS_DESK_ID", "ROLOS_API_SERVER", "RESEARCH_PROJECT_ID", "RESEARCH_DESK_ID", "RESEARCH_API_SERVER", "RESEARCH_ACCESS_KEY"]
73
75
  startup_timeout_sec = 60
74
76
  tool_timeout_sec = 30
75
77
 
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Constructor Research MCP
2
2
 
3
+ > **0.6.5:** inside a Constructor desk, the MCP uses the access key the desk provides (`RESEARCH_ACCESS_KEY`), so the user needs no key of their own (once Research sets it); the Codex entry passes the desk's variables on to the MCP.
4
+ >
5
+ > **0.6.4:** with no project or desk named (and not inside a desk), `deploy_app` creates a new project from a short `project_name` and deploys there.
6
+ >
3
7
  > **0.6.3:** `delete_resources` deletes applications, services and images, after the user approves the list.
4
8
  >
5
9
  > **0.6.2:** a ready-made image works on a project with deployment off (it is switched on first); logs keep 2000 lines per build or service for 14 days, services are followed for two hours, and `watched` says when.
@@ -62,23 +66,24 @@ npx -y -p constructor-research-mcp@latest constructor-research-set-key https://a
62
66
 
63
67
  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.
64
68
 
65
- `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.
69
+ `CONSTRUCTOR_ACCESS_KEY` in the MCP settings takes precedence over the file and over a desk's key. 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.
66
70
 
67
71
  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`.
68
72
 
69
73
  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.
70
74
 
71
- | Variable | Default |
72
- | ----------------------------------- | ----------------------------------------------------------------------------------------------- |
73
- | `CONSTRUCTOR_BASE_URL` | unset: the Constructor of the saved key, else `https://constructor.app`; set, it fixes the host |
74
- | `CONSTRUCTOR_API_PATH` | `/api/platform-account/v1` |
75
- | `CONSTRUCTOR_STORAGE_PATH` | `/api/platform-storage` |
76
- | `CONSTRUCTOR_ACCESS_KEY` | unset: the key file is used |
77
- | `CONSTRUCTOR_KEY_FILE` | `~/.config/constructor-research/access-key.json` |
78
- | `CONSTRUCTOR_DESK_ROOT` | `~/project` (inside a desk only) |
79
- | `CONSTRUCTOR_STATE_DIR` | `~/.local/state/constructor-research-mcp` |
80
- | `CONSTRUCTOR_UPLOAD_SETTLE_SECONDS` | `30` |
81
- | `CONSTRUCTOR_READINESS_SECONDS` | `60` |
75
+ | Variable | Default |
76
+ | ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
77
+ | `CONSTRUCTOR_BASE_URL` | unset: the Constructor of the saved key, else `https://constructor.app`; set, it fixes the host |
78
+ | `CONSTRUCTOR_API_PATH` | `/api/platform-account/v1` |
79
+ | `CONSTRUCTOR_STORAGE_PATH` | `/api/platform-storage` |
80
+ | `CONSTRUCTOR_ACCESS_KEY` | unset: the key file is used |
81
+ | `RESEARCH_ACCESS_KEY` | set by Constructor Research inside a desk: the desk's key, used when `CONSTRUCTOR_ACCESS_KEY` is unset |
82
+ | `CONSTRUCTOR_KEY_FILE` | `~/.config/constructor-research/access-key.json` |
83
+ | `CONSTRUCTOR_DESK_ROOT` | `~/project` (inside a desk only) |
84
+ | `CONSTRUCTOR_STATE_DIR` | `~/.local/state/constructor-research-mcp` |
85
+ | `CONSTRUCTOR_UPLOAD_SETTLE_SECONDS` | `30` |
86
+ | `CONSTRUCTOR_READINESS_SECONDS` | `60` |
82
87
 
83
88
  HTTPS is required except on localhost.
84
89
 
@@ -91,6 +96,10 @@ When the MCP runs in VS Code inside a Constructor Research desk, it finds that d
91
96
  - `build.dockerfile` is the path inside the project folder (`/backend/Dockerfile`), or `build.local_path` names a folder inside it; Dockerfiles are checked from the local files;
92
97
  - two addresses can lead to the user's Constructor: the one the user named (the saved key's, or `CONSTRUCTOR_BASE_URL`; without either, the desk's server) and the desk's server (`ROLOS_API_SERVER`), which may differ from it, e.g. `https://constructor.app` in a desk opened on `https://acme.constructor.app`. The MCP asks the desk's server once whether it accepts the key: if it does, requests go there, else to the user's address. Links shown to the user and key help keep the user's address, and desk links from either address are accepted. Setup (`install`, `constructor-research-set-key`) checks the key with both and saves it for the user's address when either accepts it.
93
98
 
99
+ - **the desk's access key:** Constructor Research sets `RESEARCH_ACCESS_KEY` in the desk, and the MCP uses it, so the user needs no key of their own and `install` asks for none. A key the user saved for this Constructor stays and takes over when Constructor rejects the desk's key. Once accepted, the desk's key is also saved to the key file, marked `"source": "desk"` (never over a key the user saved), so the wait command and hooks find it even where the agent's shell drops variables named `*KEY*` (Codex does).
100
+
101
+ Codex starts MCP servers with only a few variables (`HOME`, `PATH`, …). Its entry therefore lists the desk's variables in `env_vars` (names only, no values); `install` writes it. Claude Code passes its whole environment on. Agents that pass on neither (Cline) do not see the desk.
102
+
94
103
  `CONSTRUCTOR_LOCAL_DESK=0` turns this off.
95
104
 
96
105
  ## Fourteen tools
@@ -115,7 +124,7 @@ No special clone/new-instance workflow is implemented. The fourteen tools use th
115
124
 
116
125
  ## Where to act: the desk link
117
126
 
118
- The agent does not choose a project or desk. It asks the user for the desk link: open the desk in Constructor and copy the browser address, for example
127
+ The agent never picks an existing project itself. It uses the project or desk the user named (now or earlier in the conversation); inside a Constructor desk, that desk is the default. The desk link is the browser address of a desk, for example
119
128
 
120
129
  ```text
121
130
  https://constructor.app/research/projects/<project_id>/desks/<desk_id>/viewer/file
@@ -123,6 +132,14 @@ https://constructor.app/research/projects/<project_id>/desks/<desk_id>/viewer/fi
123
132
 
124
133
  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 (inside a desk, the desk's server too); 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.
125
134
 
135
+ **No target at all** (no `desk_url` or `project_id`, and not inside a desk): `deploy_app` returns `no_target`, telling the agent not to ask but to repeat the call with `project_name`, a short name (one to three words) taken from the app, and to tell the user. With `project_name` the MCP then:
136
+
137
+ - creates the project (`POST /projects`, description "Created by the Constructor Research MCP for <app>"); a name already taken gets a number (`todo 2`);
138
+ - waits until it is active and switches deployment on;
139
+ - deploys there as usual (sources go to the project's desk, registry images are added as external images), and the result message carries the project's link.
140
+
141
+ The same request again (same `project_name` and `application_name` within a day) reuses that project instead of creating another: `created-projects.json` in the state directory records each creation before and after the request, so even an interrupted one is adopted. `project_name` is ignored when a project or desk is given.
142
+
126
143
  Given only `project_id`, the MCP finds the desk itself:
127
144
 
128
145
  - one desk in the project: it is used;
@@ -211,7 +228,7 @@ With `image`, the MCP first looks for it in the project (by `reference` or name)
211
228
  ## Missing prerequisites
212
229
 
213
230
  - **No or rejected key:** `needs_key` with the command to save one (see Access key). Save a valid key, then check the same deployment again.
214
- - **No project/disk:** omit `project_id`, optionally supply `project_name`, and use build sources without disk IDs. MCP creates the project/disk and enables deployment tools.
231
+ - **No project/disk:** omit `project_id` and pass `project_name`; the MCP creates the project, switches deployment on and uses or creates its desk (see "Where to act").
215
232
  - **Files absent:** `needs_upload` lists disks and Dockerfile paths. Upload with `sync_files` (or manually), then call `get_deployment` with `deployment_id` and `files_uploaded:true`.
216
233
 
217
234
  Before any build, the MCP reads each Dockerfile from its disk. A missing one returns `dockerfile_missing` and nothing is created. When every build's Dockerfile is present, the upload pause is skipped. The MCP also returns `dockerfile_warnings` (in `message` too) for: a name other than `Dockerfile`/`<name>.dockerfile`, no `FROM`, no `EXPOSE` or a service port that is not exposed, `localhost`/`127.0.0.1` in `ENV`/`ARG`/`CMD`/`ENTRYPOINT`, a docker-compose file next to the Dockerfile, compose-style default hosts in `ENV` (`http://cerbos:3592`, `temporal:7233`), an `ENTRYPOINT`/`CMD` script copied from the build context with no `chmod` (files uploaded to a desk lose the executable bit, so such a container exits before printing anything), and `listen [::]` in an nginx `.conf`/`.template` the Dockerfile copies (nginx exits where the cluster has no IPv6). The same rules are in the tool descriptions, so agents see them before writing a Dockerfile. An existing project with a conflicting name requires an explicit ID; the MCP does not guess.
package/dist/agents.d.ts CHANGED
@@ -41,7 +41,11 @@ export interface Result {
41
41
  export declare const succeeded: (r: Result) => boolean;
42
42
  /** The entry as each agent expects it. */
43
43
  export declare function entryFor(kind: Kind, spec: Spec, opencodeV2?: boolean): object;
44
- /** Codex: the first npx start downloads the package and can exceed Codex's 10 s start limit. */
44
+ /**
45
+ * Codex: the first npx start downloads the package and can exceed Codex's 10 s start limit.
46
+ * Codex starts MCP servers with only a few variables (HOME, PATH, …); env_vars passes on the
47
+ * ones a Constructor desk sets, names only, so the MCP finds the desk and the desk's key.
48
+ */
45
49
  export declare const tomlBlock: ({ command, args }: Spec) => string;
46
50
  /** What will be written, for --verbose. */
47
51
  export declare function describe(kind: Kind, spec: Spec, opencodeV2?: boolean): string[];
package/dist/agents.js CHANGED
@@ -12,6 +12,7 @@ import { homedir } from "node:os";
12
12
  import { basename, dirname, join } from "node:path";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import { parse as parseToml } from "smol-toml";
15
+ import { DESK_ENV } from "./desk.js";
15
16
  export const SERVER = "constructor-research";
16
17
  export const PACKAGE_SPEC = "constructor-research-mcp@latest";
17
18
  /** The command every agent runs. On Windows npx is a .cmd script, which agents start through cmd. */
@@ -163,8 +164,12 @@ export function entryFor(kind, spec, opencodeV2 = false) {
163
164
  }
164
165
  }
165
166
  const tomlString = (s) => JSON.stringify(s);
166
- /** Codex: the first npx start downloads the package and can exceed Codex's 10 s start limit. */
167
- export const tomlBlock = ({ command, args }) => `[mcp_servers.${SERVER}]\ncommand = ${tomlString(command)}\nargs = [${args.map(tomlString).join(", ")}]\nstartup_timeout_sec = 60\n`;
167
+ /**
168
+ * Codex: the first npx start downloads the package and can exceed Codex's 10 s start limit.
169
+ * Codex starts MCP servers with only a few variables (HOME, PATH, …); env_vars passes on the
170
+ * ones a Constructor desk sets, names only, so the MCP finds the desk and the desk's key.
171
+ */
172
+ export const tomlBlock = ({ command, args }) => `[mcp_servers.${SERVER}]\ncommand = ${tomlString(command)}\nargs = [${args.map(tomlString).join(", ")}]\nenv_vars = [${DESK_ENV.map(tomlString).join(", ")}]\nstartup_timeout_sec = 60\n`;
168
173
  /** What will be written, for --verbose. */
169
174
  export function describe(kind, spec, opencodeV2 = false) {
170
175
  if (kind === "codex")
@@ -349,7 +354,11 @@ export function writeToml(path, spec, scope) {
349
354
  return untouched("could not be edited safely");
350
355
  }
351
356
  const entry = after.mcp_servers?.[SERVER];
352
- if (!isDeepStrictEqual(plain(entry), { ...spec, startup_timeout_sec: 60 }) ||
357
+ if (!isDeepStrictEqual(plain(entry), {
358
+ ...spec,
359
+ env_vars: DESK_ENV,
360
+ startup_timeout_sec: 60,
361
+ }) ||
353
362
  !isDeepStrictEqual(withoutOurs(parseToml(old)), withoutOurs(after)))
354
363
  return untouched(`sets ${SERVER} in a form this setup does not edit`);
355
364
  const backup = backupOnce(file);
package/dist/api.d.ts CHANGED
@@ -38,6 +38,18 @@ export declare class PlatformApi {
38
38
  * changes; an unreachable server is asked again after a minute.
39
39
  */
40
40
  origin(key: string): Promise<string>;
41
+ /** What Constructor said about the desk's key; see deskKey(). */
42
+ private deskCheck?;
43
+ /**
44
+ * Inside a Constructor desk, RESEARCH_ACCESS_KEY is the key the desk provides, so the user
45
+ * need not supply one. It is used first; a key the user saved for this Constructor takes over
46
+ * when Constructor rejects it. Once accepted it is saved to the key file (marked "desk") unless
47
+ * the user saved a key of their own there, so the wait command and hooks find it even when the
48
+ * agent's shell drops variables named *KEY*. Constructor is asked about the key once, and only
49
+ * when there is a choice or something to save.
50
+ */
51
+ private deskKey;
52
+ private checkDeskKey;
41
53
  /** The access-key header for a request, and the origin the request goes to. */
42
54
  private auth;
43
55
  private rejected;
package/dist/api.js CHANGED
@@ -2,7 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { createHash } from "node:crypto";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { DEFAULT_BASE_URL, VERSION } from "./config.js";
5
- import { readKeyFile, routeKey } from "./key.js";
5
+ import { readKeyFile, routeKey, saveKeyFile, } from "./key.js";
6
6
  export class ToolError extends Error {
7
7
  code;
8
8
  status;
@@ -49,6 +49,7 @@ export class PlatformApi {
49
49
  * Read before every tool call, so a key saved meanwhile is used without a restart.
50
50
  */
51
51
  async refresh() {
52
+ // A key in the MCP settings names no Constructor; it wins over the desk's and the file's.
52
53
  if (this.config.baseUrlFixed || this.config.accessKey)
53
54
  return;
54
55
  const saved = await readKeyFile(this.config.keyFile).catch(() => undefined);
@@ -88,10 +89,68 @@ export class PlatformApi {
88
89
  this.route = route;
89
90
  return route.origin;
90
91
  }
92
+ /** What Constructor said about the desk's key; see deskKey(). */
93
+ deskCheck;
94
+ /**
95
+ * Inside a Constructor desk, RESEARCH_ACCESS_KEY is the key the desk provides, so the user
96
+ * need not supply one. It is used first; a key the user saved for this Constructor takes over
97
+ * when Constructor rejects it. Once accepted it is saved to the key file (marked "desk") unless
98
+ * the user saved a key of their own there, so the wait command and hooks find it even when the
99
+ * agent's shell drops variables named *KEY*. Constructor is asked about the key once, and only
100
+ * when there is a choice or something to save.
101
+ */
102
+ async deskKey(env, saved) {
103
+ const usable = saved?.url === this.config.baseUrl ? saved : undefined;
104
+ const clean = cleanKey(env);
105
+ if (!clean)
106
+ return usable?.key ?? env;
107
+ if (usable && cleanKey(usable.key) === clean)
108
+ return clean;
109
+ const save = !saved || (saved.source === "desk" && !!usable);
110
+ if (!usable && !save)
111
+ return clean;
112
+ const result = await this.checkDeskKey(clean);
113
+ if (result === "rejected") {
114
+ if (usable)
115
+ return usable.key;
116
+ throw new ToolError("needs_key", this.keyHelp("Constructor rejected the access key this desk provides (RESEARCH_ACCESS_KEY)."), 401);
117
+ }
118
+ if (result === "ok" && save)
119
+ await saveKeyFile(this.config.keyFile, this.config.baseUrl, clean, "desk")
120
+ // The key still works from the environment; only the wait command misses the copy.
121
+ .catch(() => undefined);
122
+ return clean;
123
+ }
124
+ checkDeskKey(key) {
125
+ const home = this.config.baseUrl;
126
+ const server = this.config.localDesk?.server;
127
+ const tag = createHash("sha256")
128
+ .update(`${home}\n${server}\n${key}`)
129
+ .digest("hex");
130
+ if (this.deskCheck?.tag === tag && Date.now() < this.deskCheck.until)
131
+ return this.deskCheck.result;
132
+ const check = {
133
+ tag,
134
+ until: Infinity,
135
+ result: routeKey(home, server, this.config.apiPath, key, {
136
+ checkHome: true,
137
+ timeoutMs: Math.min(5000, this.config.requestTimeoutMs),
138
+ }).then((r) => {
139
+ // Only a clear yes or no holds; an unreachable Constructor is asked again in a minute.
140
+ if (r.result !== "ok" && r.result !== "rejected")
141
+ check.until = Date.now() + 60000;
142
+ return r.result ?? "unreachable";
143
+ }),
144
+ };
145
+ this.deskCheck = check;
146
+ return check.result;
147
+ }
91
148
  /** The access-key header for a request, and the origin the request goes to. */
92
149
  async auth() {
93
150
  let key = this.config.accessKey;
94
- if (key === undefined) {
151
+ if (key === undefined && this.config.deskKey)
152
+ key = await this.deskKey(this.config.deskKey, await readKeyFile(this.config.keyFile).catch(() => undefined));
153
+ else if (key === undefined) {
95
154
  let saved;
96
155
  try {
97
156
  saved = await readKeyFile(this.config.keyFile);
@@ -115,6 +174,9 @@ export class PlatformApi {
115
174
  };
116
175
  }
117
176
  rejected() {
177
+ // The next call asks again which key to use and where it goes.
178
+ this.deskCheck = undefined;
179
+ this.route = undefined;
118
180
  return new ToolError("needs_key", this.keyHelp("Constructor rejected the access key (revoked, expired or for another Constructor)."), 401);
119
181
  }
120
182
  /**
package/dist/config.d.ts CHANGED
@@ -16,6 +16,8 @@ export interface Config {
16
16
  keeperPath?: string;
17
17
  /** Personal access key (rk-…) from CONSTRUCTOR_ACCESS_KEY; without it the key file is read. */
18
18
  accessKey?: string;
19
+ /** Inside a desk: the access key Constructor Research provides there (RESEARCH_ACCESS_KEY). */
20
+ deskKey?: string;
19
21
  /** Saved key and the Constructor it belongs to (JSON, mode 600); CONSTRUCTOR_KEY_FILE moves it. */
20
22
  keyFile: string;
21
23
  stateDir: string;
package/dist/config.js CHANGED
@@ -50,6 +50,7 @@ export function configFromEnv(env = process.env) {
50
50
  storagePath: storagePath.replace(/\/$/, ""),
51
51
  keeperPath: keeperPath.replace(/\/$/, ""),
52
52
  accessKey: env.CONSTRUCTOR_ACCESS_KEY?.trim() || undefined,
53
+ deskKey: (localDesk && env.RESEARCH_ACCESS_KEY?.trim()) || undefined,
53
54
  keyFile: expand(env.CONSTRUCTOR_KEY_FILE ?? DEFAULT_KEY_FILE),
54
55
  stateDir: expand(env.CONSTRUCTOR_STATE_DIR ?? "~/.local/state/constructor-research-mcp"),
55
56
  requestTimeoutMs: 15000,
@@ -158,6 +158,20 @@ export declare class DeploymentEngine {
158
158
  get(raw: unknown): Promise<any>;
159
159
  private mutate;
160
160
  private advance;
161
+ /**
162
+ * Creates a project for a deployment that has no target (no project or desk named, not
163
+ * running inside a desk), switches deployment on and returns it. Repeating the same
164
+ * request (same name and application within a day) returns the same project: a ledger in
165
+ * the state directory records the creation before and after the request, so a crash in
166
+ * between adopts the project instead of creating a second one. A name already taken by
167
+ * another project gets a number ("todo 2").
168
+ */
169
+ createProject(name: string, application?: string): Promise<{
170
+ id: string;
171
+ name: string;
172
+ url: string;
173
+ created: boolean;
174
+ }>;
161
175
  /** Switches on deployment; when the key may not, the operation stops with what to do instead. */
162
176
  private enableDeployment;
163
177
  /**
@@ -1072,6 +1072,74 @@ export class DeploymentEngine {
1072
1072
  return this.view(op);
1073
1073
  }
1074
1074
  }
1075
+ /**
1076
+ * Creates a project for a deployment that has no target (no project or desk named, not
1077
+ * running inside a desk), switches deployment on and returns it. Repeating the same
1078
+ * request (same name and application within a day) returns the same project: a ledger in
1079
+ * the state directory records the creation before and after the request, so a crash in
1080
+ * between adopts the project instead of creating a second one. A name already taken by
1081
+ * another project gets a number ("todo 2").
1082
+ */
1083
+ async createProject(name, application) {
1084
+ const wanted = name.trim().replace(/\s+/g, " ");
1085
+ const key = createHash("sha256")
1086
+ .update(`${this.store.endpoint}|${wanted}|${application ?? ""}`)
1087
+ .digest("hex");
1088
+ const link = (id) => `${this.api.config.baseUrl}/research/projects/${id}`;
1089
+ const found = await this.store.exclusive(async () => {
1090
+ const ledger = await this.store.created();
1091
+ const day = 24 * 60 * 60 * 1000;
1092
+ for (const k of Object.keys(ledger))
1093
+ if (Date.now() - ledger[k].at > day)
1094
+ delete ledger[k];
1095
+ const seen = ledger[key];
1096
+ const all = await this.rows("/projects");
1097
+ if (seen) {
1098
+ // Created before, or interrupted after asking Constructor: adopt that project.
1099
+ const mine = seen.project_id
1100
+ ? all.find((p) => p.id === seen.project_id)
1101
+ : all.find((p) => p.name === seen.name &&
1102
+ Date.parse(p.created_at ?? "") >= seen.at - 60000);
1103
+ if (mine && !mine.archived) {
1104
+ ledger[key] = { ...seen, project_id: mine.id };
1105
+ await this.store.saveCreated(ledger);
1106
+ return { project: mine, created: false };
1107
+ }
1108
+ }
1109
+ const taken = new Set(all.map((p) => p.name));
1110
+ let unique = wanted;
1111
+ for (let n = 2; taken.has(unique); n++)
1112
+ unique = `${wanted} ${n}`;
1113
+ ledger[key] = { name: unique, at: Date.now() };
1114
+ await this.store.saveCreated(ledger);
1115
+ const project = await this.api.request("POST", "/projects", {
1116
+ name: unique,
1117
+ description: `Created by the Constructor Research MCP${application ? ` for ${application}` : ""}.`,
1118
+ });
1119
+ if (!/^[a-zA-Z0-9_-]{4,128}$/.test(project?.id ?? ""))
1120
+ throw new ToolError("uncertain_outcome", "Creating the project returned no project ID. Check the user's projects (get_deployment) before trying again.");
1121
+ ledger[key] = {
1122
+ name: unique,
1123
+ at: ledger[key].at,
1124
+ project_id: project.id,
1125
+ };
1126
+ await this.store.saveCreated(ledger);
1127
+ return { project, created: true };
1128
+ });
1129
+ // A new project may take a moment to become active.
1130
+ let project = found.project;
1131
+ for (let i = 0; i < 20 && project.status && project.status !== "active"; i++) {
1132
+ await delay(1000);
1133
+ project = await this.project(project.id);
1134
+ }
1135
+ await this.ensureDeployment(project.id, project.deployment_enabled);
1136
+ return {
1137
+ id: project.id,
1138
+ name: project.name,
1139
+ url: link(project.id),
1140
+ created: found.created,
1141
+ };
1142
+ }
1075
1143
  /** Switches on deployment; when the key may not, the operation stops with what to do instead. */
1076
1144
  async enableDeployment(op, project) {
1077
1145
  try {
@@ -1177,19 +1245,9 @@ export class DeploymentEngine {
1177
1245
  }
1178
1246
  async advanceApp(op) {
1179
1247
  const input = op.input;
1180
- // For a new project all sources must be builds; image IDs are project-scoped.
1181
- if (!op.project_id) {
1182
- if (input.services.some((s) => !s.build || s.build.desk_id || s.service_id))
1183
- bad("A new project requires build sources without existing disk/service IDs.");
1184
- const matches = (await this.rows("/projects")).filter((p) => p.name === (input.project_name ?? input.application_name));
1185
- if (matches.length)
1186
- bad("A project with this name exists. Discover its ID with get_deployment before proceeding.");
1187
- await this.mutate(op, "POST", "/projects", { name: input.project_name ?? input.application_name }, (p) => {
1188
- op.project_id = p.id;
1189
- op.status = "preparing";
1190
- });
1191
- return this.view(op);
1192
- }
1248
+ // A new project is created before the operation (createProject), so one is always set.
1249
+ if (!op.project_id)
1250
+ bad("No project: pass desk_url or project_id, or project_name to create a new project.");
1193
1251
  const project = await this.project(op.project_id);
1194
1252
  if (project.status && project.status !== "active")
1195
1253
  throw new ToolError("not_ready", "Project is not active yet; retry later.");
package/dist/desk.d.ts CHANGED
@@ -11,6 +11,12 @@ export interface LocalDesk {
11
11
  /** The Constructor the desk belongs to. */
12
12
  server?: string;
13
13
  }
14
+ /**
15
+ * What Constructor sets in a desk that the MCP reads: the desk, its server, and the access key
16
+ * the desk provides. Agents that start the MCP with a reduced environment (Codex) are told to
17
+ * pass these on.
18
+ */
19
+ export declare const DESK_ENV: string[];
14
20
  export declare function localDeskFromEnv(env: NodeJS.ProcessEnv, origin: (link: string) => string): LocalDesk | undefined;
15
21
  /**
16
22
  * Disk path ("/a/Dockerfile") of a local path inside the desk's project folder, or undefined
package/dist/desk.js CHANGED
@@ -2,6 +2,20 @@ import { realpathSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  const ID = /^[a-zA-Z0-9_-]{4,128}$/;
5
+ /**
6
+ * What Constructor sets in a desk that the MCP reads: the desk, its server, and the access key
7
+ * the desk provides. Agents that start the MCP with a reduced environment (Codex) are told to
8
+ * pass these on.
9
+ */
10
+ export const DESK_ENV = [
11
+ "ROLOS_PROJECT_ID",
12
+ "ROLOS_DESK_ID",
13
+ "ROLOS_API_SERVER",
14
+ "RESEARCH_PROJECT_ID",
15
+ "RESEARCH_DESK_ID",
16
+ "RESEARCH_API_SERVER",
17
+ "RESEARCH_ACCESS_KEY",
18
+ ];
5
19
  export function localDeskFromEnv(env, origin) {
6
20
  if (["0", "false", "off"].includes((env.CONSTRUCTOR_LOCAL_DESK ?? "").toLowerCase()))
7
21
  return undefined;
package/dist/install.js CHANGED
@@ -230,11 +230,17 @@ export async function runInstall(argv) {
230
230
  let base;
231
231
  /** Inside a Constructor desk, the server it names; the key is checked there too. */
232
232
  const deskServer = config.localDesk?.server;
233
+ /** The access key the desk provides (RESEARCH_ACCESS_KEY); no question then. A key given for -y wins. */
234
+ const deskKey = config.deskKey &&
235
+ !flag("--key-stdin") &&
236
+ !(yes && env.CONSTRUCTOR_ACCESS_KEY)
237
+ ? accessKey(config.deskKey)
238
+ : undefined;
233
239
  try {
234
240
  const given = value("--constructor");
235
241
  if (given)
236
242
  base = linkOrigin(given);
237
- else if (yes)
243
+ else if (yes || deskKey)
238
244
  base = saved?.url ?? deskServer ?? DEFAULT_BASE_URL;
239
245
  else {
240
246
  // Inside a desk its server is the likely answer, but the user may open another address.
@@ -319,7 +325,30 @@ export async function runInstall(argv) {
319
325
  return route.result;
320
326
  };
321
327
  let key;
322
- if (yes) {
328
+ let keySource;
329
+ let deskDone = false;
330
+ if (deskKey) {
331
+ if ((await check(deskKey)) === "ok") {
332
+ deskDone = true;
333
+ // A key the user saved for this Constructor stays: the MCP falls back to it.
334
+ if (saved?.url === base && !saved.source && saved.key !== deskKey)
335
+ p.log.info(`This desk provides an access key (${mask(deskKey)}); the MCP uses it, and the key saved for ${short(base)} if Constructor rejects the desk's.`);
336
+ else {
337
+ key = deskKey;
338
+ keySource = "desk";
339
+ }
340
+ }
341
+ else {
342
+ if (yes)
343
+ keyProblem = "the access key this desk provides was not accepted";
344
+ else
345
+ p.log.warn("The access key this desk provides was not accepted.");
346
+ }
347
+ }
348
+ if (deskDone) {
349
+ // The desk's key is accepted; nothing to ask.
350
+ }
351
+ else if (yes) {
323
352
  const raw = flag("--key-stdin")
324
353
  ? await readStdin()
325
354
  : env.CONSTRUCTOR_ACCESS_KEY;
@@ -333,7 +362,7 @@ export async function runInstall(argv) {
333
362
  }
334
363
  }
335
364
  else if (!(saved && saved.url === base))
336
- keyProblem = "no key given (CONSTRUCTOR_ACCESS_KEY or --key-stdin)";
365
+ keyProblem ||= "no key given (CONSTRUCTOR_ACCESS_KEY or --key-stdin)";
337
366
  }
338
367
  else {
339
368
  const keep = saved?.url === base &&
@@ -371,9 +400,11 @@ export async function runInstall(argv) {
371
400
  if (dry)
372
401
  p.log.info(`Dry run: key ${mask(key)} not saved.`);
373
402
  else {
374
- await saveKeyFile(config.keyFile, base, key);
403
+ await saveKeyFile(config.keyFile, base, key, keySource);
375
404
  keySaved = true;
376
- p.log.success(`Key saved to ${bold(show(config.keyFile))} ${dim("(readable only by you)")}`);
405
+ p.log.success(keySource
406
+ ? `The access key this desk provides (${mask(key)}) is saved to ${bold(show(config.keyFile))} ${dim("(readable only by you)")}, so the wait command finds it too; no key from you is needed`
407
+ : `Key saved to ${bold(show(config.keyFile))} ${dim("(readable only by you)")}`);
377
408
  }
378
409
  }
379
410
  else if (keyProblem)
package/dist/key.d.ts CHANGED
@@ -2,11 +2,13 @@
2
2
  export interface SavedKey {
3
3
  url: string;
4
4
  key: string;
5
+ /** "desk": the MCP saved the key a Constructor desk provides (CONSTRUCTOR_ACCESS_KEY); absent: the user saved it. */
6
+ source?: "desk";
5
7
  }
6
8
  /** The saved key, or undefined when none was saved. A broken file throws. */
7
9
  export declare function readKeyFile(file: string): Promise<SavedKey | undefined>;
8
10
  /** Saves the key for one Constructor, mode 600, replacing the file in one step. */
9
- export declare function saveKeyFile(file: string, url: string, key: string): Promise<void>;
11
+ export declare function saveKeyFile(file: string, url: string, key: string, source?: "desk"): Promise<void>;
10
12
  export type KeyCheck = "ok" | "rejected" | "no_api" | "unreachable";
11
13
  /** Ask Constructor whether it accepts the key: 200 accepted, 401 rejected, else no public API. */
12
14
  export declare function checkKey(url: string, apiPath: string, key: string, timeoutMs?: number): Promise<{
package/dist/key.js CHANGED
@@ -23,13 +23,18 @@ export async function readKeyFile(file) {
23
23
  }
24
24
  if (typeof data?.key !== "string" || typeof data?.url !== "string")
25
25
  throw new Error("expected url and key");
26
- return { url: originOf(data.url), key: data.key };
26
+ return {
27
+ url: originOf(data.url),
28
+ key: data.key,
29
+ ...(data.source === "desk" ? { source: "desk" } : {}),
30
+ };
27
31
  }
28
32
  /** Saves the key for one Constructor, mode 600, replacing the file in one step. */
29
- export async function saveKeyFile(file, url, key) {
33
+ export async function saveKeyFile(file, url, key, source) {
30
34
  await mkdir(dirname(file), { recursive: true, mode: 0o700 });
31
35
  const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
32
- await writeFile(tmp, JSON.stringify({ url: originOf(url), key }) + "\n", {
36
+ await writeFile(tmp, JSON.stringify({ url: originOf(url), key, ...(source ? { source } : {}) }) +
37
+ "\n", {
33
38
  mode: 0o600,
34
39
  flag: "wx",
35
40
  });
package/dist/schemas.js CHANGED
@@ -145,7 +145,9 @@ const deploymentShape = {
145
145
  desk_url: deskUrl
146
146
  .optional()
147
147
  .describe("Desk link from the user: sets project_id and the desk for builds without desk_id."),
148
- project_name: name.optional(),
148
+ project_name: name
149
+ .optional()
150
+ .describe("Only when the user named no project or desk: a short name (one to three words, from the app) for a NEW project. The MCP creates it, switches deployment on and deploys there; tell the user. Ignored when a project or desk is given."),
149
151
  application_name: name.optional(),
150
152
  services: z.array(serviceInput).min(1).optional(),
151
153
  files_uploaded: z.boolean().default(false),
package/dist/server.js CHANGED
@@ -54,6 +54,21 @@ async function main() {
54
54
  };
55
55
  const prepared = async (fn, single, a, notes) => {
56
56
  const begun = Date.now();
57
+ // No target anywhere: a new project, named by the agent, or a clear ask for that name.
58
+ if (!single && !a.project_id && !a.deployment_id && a.services) {
59
+ if (!a.project_name?.trim())
60
+ throw new ToolError("no_target", "No target for this deployment: no desk_url or project_id, and this MCP does not run inside a Constructor desk. If the user named a project or desk earlier in the conversation, pass it. Otherwise do not ask: repeat the same call with project_name, a short name (one to three words, from the app) for a new project, and tell the user that a new Constructor project with that name is created for the app.");
61
+ const p = await engine.createProject(a.project_name, a.application_name);
62
+ notes.push(p.created
63
+ ? `Created a new Constructor project "${p.name}" for this app, with deployment on: ${p.url}. Tell the user.`
64
+ : `Deploying to the project "${p.name}" this MCP created for this app earlier: ${p.url}.`);
65
+ const { project_name: _n, ...rest } = a;
66
+ a = { ...rest, project_id: p.id };
67
+ }
68
+ else if (!single && a.project_name && a.project_id) {
69
+ const { project_name: _n, ...rest } = a;
70
+ a = rest;
71
+ }
57
72
  if (!single && a.project_id && a.services) {
58
73
  // Images the project has (by reference or name) are used as they are. Any other
59
74
  // registry image is added to the project as an external image: no desk, no build.
@@ -230,10 +245,10 @@ async function main() {
230
245
  };
231
246
  /** Inside a desk, the agent edits its files in place instead of asking for a desk link. */
232
247
  const withDesk = (text) => config.localDesk
233
- ? 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) + " ")
248
+ ? text.replace(/Where to act: use the project or desk the user named.*?is created for the app\. /, deskInstructions(config.localDesk) + " ")
234
249
  : text;
235
250
  const server = new McpServer({ name: "constructor-research", version: VERSION }, {
236
- 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. Never read the key file or call Constructor's API yourself (curl, scripts): everything goes through these tools, and if they cannot do something, tell the user. 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 public 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 adds it to the project as an external image, with no desk and no build; if Constructor refuses it (image_refused), tell the user the reason. 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. To remove applications, services or images, use delete_resources (it asks the user first). 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.`),
251
+ 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. Never read the key file or call Constructor's API yourself (curl, scripts): everything goes through these tools, and if they cannot do something, tell the user. Where to act: use the project or desk the user named, now or earlier in the conversation; a desk link (the browser address of a desk, with /projects/<project>/desks/<desk>) goes in desk_url. Do not pick an existing project yourself. When the user named none, do not ask: call deploy_app with project_name, a short name (one to three words, from the app), and the MCP creates a new project with deployment on; tell the user a new Constructor project with that name is created for the app. 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 public 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 adds it to the project as an external image, with no desk and no build; if Constructor refuses it (image_refused), tell the user the reason. 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. To remove applications, services or images, use delete_resources (it asks the user first). 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.`),
237
252
  });
238
253
  const register = (name, description, schema, fn, readOnly = false, budget = 20000, scope) => {
239
254
  const here = config.localDesk && DESK_DEFAULT.has(name) ? config.localDesk : undefined;
package/dist/store.d.ts CHANGED
@@ -81,6 +81,13 @@ export declare class StateStore {
81
81
  lastBeat(id: string): Promise<number>;
82
82
  private alive;
83
83
  save(op: Operation): Promise<void>;
84
+ /** Projects this MCP created for deployments without a target, by request key. */
85
+ created(): Promise<Record<string, {
86
+ name: string;
87
+ at: number;
88
+ project_id?: string;
89
+ }>>;
90
+ saveCreated(ledger: Record<string, unknown>): Promise<void>;
84
91
  exclusive<T>(fn: () => Promise<T>): Promise<T>;
85
92
  }
86
93
  /**
package/dist/store.js CHANGED
@@ -73,6 +73,25 @@ export class StateStore {
73
73
  });
74
74
  await rename(tmp, target);
75
75
  }
76
+ /** Projects this MCP created for deployments without a target, by request key. */
77
+ async created() {
78
+ try {
79
+ const data = JSON.parse(await readFile(join(this.config.stateDir, "created-projects.json"), "utf8"));
80
+ return data && typeof data === "object" ? data : {};
81
+ }
82
+ catch {
83
+ return {};
84
+ }
85
+ }
86
+ async saveCreated(ledger) {
87
+ await this.init();
88
+ const target = join(this.config.stateDir, "created-projects.json"), tmp = target + "." + randomUUID() + ".tmp";
89
+ await writeFile(tmp, JSON.stringify(ledger, null, 2), {
90
+ mode: 0o600,
91
+ flag: "wx",
92
+ });
93
+ await rename(tmp, target);
94
+ }
76
95
  async exclusive(fn) {
77
96
  await this.init();
78
97
  const lock = join(this.config.stateDir, ".lock");
@@ -1,6 +1,8 @@
1
1
  [mcp_servers.constructor-research]
2
2
  command = "npx"
3
3
  args = ["-y", "constructor-research-mcp@latest"]
4
+ # Inside a Constructor desk: pass the desk and its access key on (Codex passes only a few variables).
5
+ env_vars = ["ROLOS_PROJECT_ID", "ROLOS_DESK_ID", "ROLOS_API_SERVER", "RESEARCH_PROJECT_ID", "RESEARCH_DESK_ID", "RESEARCH_API_SERVER", "RESEARCH_ACCESS_KEY"]
4
6
  # The first start downloads the package.
5
7
  startup_timeout_sec = 60
6
8
  tool_timeout_sec = 30
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructor-research-mcp",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
4
4
  "type": "module",
5
5
  "description": "Local deployment MCP for Constructor Research",
6
6
  "license": "MIT",