constructor-research-mcp 0.6.0 → 0.6.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/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Constructor Research MCP
2
2
 
3
+ > **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.
4
+ >
5
+ > **0.6.1:** inside a Constructor desk, a key saved for your Constructor works even when the desk names another address for it (`ROLOS_API_SERVER`, e.g. `constructor.app` in a desk opened on `acme.constructor.app`).
6
+ >
3
7
  > **0.6:** a registry `image` the project does not have is added to it as an external image, with no desk and no build; Constructor refuses a bad one at once, with its reason.
4
8
  >
5
9
  > **0.5:** one command sets it up: `npx -y constructor-research-mcp@latest install` finds your coding agents, saves your access key and adds the MCP to each of them.
@@ -83,7 +87,7 @@ When the MCP runs in VS Code inside a Constructor Research desk, it finds that d
83
87
  - the desk's project folder (`~/project`, or `CONSTRUCTOR_DESK_ROOT`) is its disk, so the agent creates and changes files there directly; nothing is uploaded, and `sync_files`, `list_files`, `create_folder`, `move_path` and `delete_path` answer `local_desk` for this desk;
84
88
  - `build_image`, `deploy_app`, `update_app`, `start_app`, `stop_app` and `list_images` act on this desk and project without a desk link; a `desk_url` or other IDs still name another desk;
85
89
  - `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;
86
- - the MCP works with the desk's Constructor (`ROLOS_API_SERVER`) unless `CONSTRUCTOR_BASE_URL` is set.
90
+ - 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.
87
91
 
88
92
  `CONSTRUCTOR_LOCAL_DESK=0` turns this off.
89
93
 
@@ -95,7 +99,7 @@ When the MCP runs in VS Code inside a Constructor Research desk, it finds that d
95
99
  | `update_app` | Describe selected changes/additions; the MCP builds and restarts affected services. |
96
100
  | `start_app` / `stop_app` | Request lifecycle changes for all or selected services. |
97
101
  | `get_deployment` | Map all deployments, inspect a project or app, or wait for background execution. |
98
- | `get_logs` | Last 10–50 lines of a build or service log (see "Logs"). |
102
+ | `get_logs` | Last 10–500 lines of a build or service log (see "Logs"). |
99
103
  | `build_image` | Build an image independently when needed. |
100
104
  | `list_images` | List image IDs, Dockerfiles and native build statuses. |
101
105
  | `list_files` | List a disk's files and folders; `recursive:true` walks subfolders. |
@@ -114,7 +118,7 @@ The agent does not choose a project or desk. It asks the user for the desk link:
114
118
  https://constructor.app/research/projects/<project_id>/desks/<desk_id>/viewer/file
115
119
  ```
116
120
 
117
- 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.
121
+ 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.
118
122
 
119
123
  Given only `project_id`, the MCP finds the desk itself:
120
124
 
@@ -260,15 +264,15 @@ For `needs_reconciliation`, inspect the possible remote mutation before submitti
260
264
 
261
265
  ## Logs
262
266
 
263
- Constructor serves logs only live, as a stream: a build log while the build runs, a service log for the service's current container. Each connection replays the log from the start, then streams. Nothing is kept afterwards: a finished build has no log, and a restarted container starts with an empty one, so a crash-looping service shows no log at all. The MCP therefore follows every build and service it starts and keeps only the last 50 lines of each, in memory and in `logs/` in the state directory, so it stays small however long the log is.
267
+ Constructor serves logs only live, as a stream: a build log while the build runs, a service log for the service's current container. Each connection replays the log from the start, then streams. Nothing is kept afterwards: a finished build has no log, and a restarted container starts with an empty one, so a crash-looping service shows no log at all. The MCP therefore follows every build and service it starts and keeps the last 2000 lines of each in `logs/` in the state directory, where other MCP processes, the wait command and a restarted agent read them too. Files untouched for 14 days are deleted, and the oldest go first when all of them pass 100 MB.
264
268
 
265
269
  - A build is followed from its first status check until it ends; a dropped connection is reopened and replayed lines are skipped. When the stream closes, reopening it answers "not found" and the kept lines are final.
266
- - A service is followed from its start request, or from when `get_deployment` shows it running, for 15 minutes after anyone last asked for it.
270
+ - A service is followed from its start request, or from when `get_deployment` shows it running, for two hours after anyone last asked for it. `watched` lists when the MCP followed it: a container that started and stopped outside those periods, or while no agent or wait command was running, left no lines, because Constructor keeps none.
267
271
  - Restarts: Constructor reports no restart count, so the MCP detects them in the stream. When a new container starts (the platform's "Container is waiting to start" line after the container's own lines, or a reconnect that begins with newer lines than were kept), it inserts `--- new container (restart N) ---` and keeps the old container's last lines above it, which usually show why it stopped. `get_logs` and the services in `get_deployment` report `restarts_seen` and `restarted_at`.
268
272
  - `get_deployment` services also carry `status_changes`: the native statuses this MCP process saw, with times, once a service has had more than one.
269
273
  - Lines that are only a timestamp are dropped, and identical consecutive lines are collapsed into one with a count (`(×5)`).
270
274
  - A failed build or start puts the last 20 lines into `failure.log_tail`.
271
- - `get_logs` takes `image_id`, `service_id` or `deployment_id` (all its builds and services) and `lines` (10–50, default 20). It also reads builds and services this MCP did not start, but only while they run.
275
+ - `get_logs` takes `image_id`, `service_id` or `deployment_id` (all its builds and services) and `lines` (10–500, default 20). It also reads builds and services this MCP did not start, but only while they run.
272
276
 
273
277
  ## Waiting for long builds
274
278
 
package/dist/api.d.ts CHANGED
@@ -28,7 +28,17 @@ export declare class PlatformApi {
28
28
  * Read before every tool call, so a key saved meanwhile is used without a restart.
29
29
  */
30
30
  refresh(): Promise<void>;
31
- /** The access-key header for a request. */
31
+ /** Where requests went for the last key and pair of addresses; see origin(). */
32
+ private route?;
33
+ /**
34
+ * Where requests with this key go. Outside a desk, or when the desk's server is the user's
35
+ * Constructor, that is the user's Constructor. Inside a desk whose server (ROLOS_API_SERVER)
36
+ * differs, the server is asked once whether it accepts the key: if so, requests go there,
37
+ * else to the user's Constructor (routeKey). The answer holds until the key or an address
38
+ * changes; an unreachable server is asked again after a minute.
39
+ */
40
+ origin(key: string): Promise<string>;
41
+ /** The access-key header for a request, and the origin the request goes to. */
32
42
  private auth;
33
43
  private rejected;
34
44
  /**
package/dist/api.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash } from "node:crypto";
2
3
  import { setTimeout as delay } from "node:timers/promises";
3
4
  import { DEFAULT_BASE_URL, VERSION } from "./config.js";
4
- import { readKeyFile } from "./key.js";
5
+ import { readKeyFile, routeKey } from "./key.js";
5
6
  export class ToolError extends Error {
6
7
  code;
7
8
  status;
@@ -51,9 +52,43 @@ export class PlatformApi {
51
52
  if (this.config.baseUrlFixed || this.config.accessKey)
52
53
  return;
53
54
  const saved = await readKeyFile(this.config.keyFile).catch(() => undefined);
54
- this.config.baseUrl = saved?.url ?? DEFAULT_BASE_URL;
55
+ this.config.baseUrl =
56
+ saved?.url ?? this.config.localDesk?.server ?? DEFAULT_BASE_URL;
55
57
  }
56
- /** The access-key header for a request. */
58
+ /** Where requests went for the last key and pair of addresses; see origin(). */
59
+ route;
60
+ /**
61
+ * Where requests with this key go. Outside a desk, or when the desk's server is the user's
62
+ * Constructor, that is the user's Constructor. Inside a desk whose server (ROLOS_API_SERVER)
63
+ * differs, the server is asked once whether it accepts the key: if so, requests go there,
64
+ * else to the user's Constructor (routeKey). The answer holds until the key or an address
65
+ * changes; an unreachable server is asked again after a minute.
66
+ */
67
+ async origin(key) {
68
+ const home = this.config.baseUrl;
69
+ const server = this.config.localDesk?.server;
70
+ if (!server || server === home)
71
+ return home;
72
+ const tag = createHash("sha256")
73
+ .update(`${home}\n${server}\n${key}`)
74
+ .digest("hex");
75
+ if (this.route?.tag === tag && Date.now() < this.route.until)
76
+ return this.route.origin;
77
+ const route = {
78
+ tag,
79
+ until: Infinity,
80
+ origin: routeKey(home, server, this.config.apiPath, key, {
81
+ timeoutMs: Math.min(5000, this.config.requestTimeoutMs),
82
+ }).then((r) => {
83
+ if (r.server === "unreachable")
84
+ route.until = Date.now() + 60000;
85
+ return r.origin;
86
+ }),
87
+ };
88
+ this.route = route;
89
+ return route.origin;
90
+ }
91
+ /** The access-key header for a request, and the origin the request goes to. */
57
92
  async auth() {
58
93
  let key = this.config.accessKey;
59
94
  if (key === undefined) {
@@ -74,7 +109,10 @@ export class PlatformApi {
74
109
  const clean = cleanKey(key);
75
110
  if (!clean)
76
111
  throw new ToolError("needs_key", this.keyHelp("The access key is not in a valid format."));
77
- return { "X-Research-AccessKey": `Bearer ${clean}` };
112
+ return {
113
+ headers: { "X-Research-AccessKey": `Bearer ${clean}` },
114
+ origin: await this.origin(clean),
115
+ };
78
116
  }
79
117
  rejected() {
80
118
  return new ToolError("needs_key", this.keyHelp("Constructor rejected the access key (revoked, expired or for another Constructor)."), 401);
@@ -85,7 +123,7 @@ export class PlatformApi {
85
123
  * safe to repeat (all but MOVE and DELETE) are retried a few times with backoff.
86
124
  */
87
125
  async storage(method, desk, path, init = {}) {
88
- const auth = await this.auth();
126
+ const { headers: auth, origin } = await this.auth();
89
127
  const retries = ["MOVE", "DELETE"].includes(method)
90
128
  ? []
91
129
  : this.storageRetryMs;
@@ -97,7 +135,7 @@ export class PlatformApi {
97
135
  const again = wait !== undefined && wait < remaining - 1000;
98
136
  let response;
99
137
  try {
100
- response = await fetch(this.config.baseUrl + this.davRoot(desk) + path, {
138
+ response = await fetch(origin + this.davRoot(desk) + path, {
101
139
  method,
102
140
  headers: { ...auth, ...init.headers },
103
141
  body: init.body,
@@ -129,12 +167,10 @@ export class PlatformApi {
129
167
  * body and aborts through `signal`. 401 becomes needs_key; other statuses are returned.
130
168
  */
131
169
  async stream(path, signal) {
132
- const auth = await this.auth();
170
+ const { headers: auth, origin } = await this.auth();
133
171
  let response;
134
172
  try {
135
- response = await fetch(this.config.baseUrl +
136
- (this.config.keeperPath ?? "/api/platform-keeper") +
137
- path, {
173
+ response = await fetch(origin + (this.config.keeperPath ?? "/api/platform-keeper") + path, {
138
174
  headers: { ...auth, Accept: "text/event-stream" },
139
175
  redirect: "manual",
140
176
  signal,
@@ -156,13 +192,13 @@ export class PlatformApi {
156
192
  return `${this.config.storagePath ?? "/api/platform-storage"}/desks/${segment(desk)}/dav/project/`;
157
193
  }
158
194
  async request(method, path, body) {
159
- const auth = await this.auth();
195
+ const { headers: auth, origin } = await this.auth();
160
196
  const remaining = (this.deadline.getStore() ?? Infinity) - Date.now();
161
197
  if (remaining <= 0)
162
198
  throw new ToolError("connection_error", "Operation time budget exhausted before sending the next request; resume with get_deployment.");
163
199
  let response;
164
200
  try {
165
- response = await fetch(this.config.baseUrl + this.config.apiPath + path, {
201
+ response = await fetch(origin + this.config.apiPath + path, {
166
202
  method,
167
203
  headers: {
168
204
  ...auth,
package/dist/config.d.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import { type LocalDesk } from "./desk.js";
2
2
  export interface Config {
3
- /** The Constructor the MCP works with: CONSTRUCTOR_BASE_URL, else the one the saved key belongs to. */
3
+ /**
4
+ * The user's Constructor: CONSTRUCTOR_BASE_URL, else the one the saved key belongs to, else
5
+ * the desk's. Links shown to the user, key help and the key file name it. Requests go there
6
+ * too, unless the desk's own server accepts the key (see PlatformApi.origin).
7
+ */
4
8
  baseUrl: string;
9
+ /** Set by CONSTRUCTOR_BASE_URL: a saved key for another Constructor is not used. */
5
10
  baseUrlFixed?: boolean;
6
11
  /** The Constructor desk this MCP runs inside (VS Code in Constructor Research), if any. */
7
12
  localDesk?: LocalDesk;
package/dist/config.js CHANGED
@@ -29,7 +29,7 @@ export function configFromEnv(env = process.env) {
29
29
  if (url.search || url.hash || url.pathname !== "/")
30
30
  throw new Error("CONSTRUCTOR_BASE_URL must be an origin without a path or credentials.");
31
31
  }
32
- // Inside a Constructor desk, its Constructor is the one to work with.
32
+ // Inside a Constructor desk, its server is where the user works unless a key says otherwise.
33
33
  const localDesk = localDeskFromEnv(env, originOf);
34
34
  const baseUrl = originOf(fixed ?? localDesk?.server ?? DEFAULT_BASE_URL);
35
35
  const apiPath = env.CONSTRUCTOR_API_PATH ?? "/api/platform-account/v1";
@@ -44,7 +44,7 @@ export function configFromEnv(env = process.env) {
44
44
  const expand = (s) => resolve(s.startsWith("~/") ? homedir() + s.slice(1) : s);
45
45
  return {
46
46
  baseUrl,
47
- baseUrlFixed: !!fixed || !!localDesk?.server,
47
+ baseUrlFixed: !!fixed,
48
48
  localDesk,
49
49
  apiPath: apiPath.replace(/\/$/, ""),
50
50
  storagePath: storagePath.replace(/\/$/, ""),
@@ -65,7 +65,7 @@ export declare class DeploymentEngine {
65
65
  * non-amd64 or malformed image with its reason. Undefined when this Constructor
66
66
  * has no such endpoint yet (the caller then builds it from FROM).
67
67
  */
68
- registerExternal(project: string, service: string, reference: string): Promise<any>;
68
+ registerExternal(project: string, service: string, reference: string, retried?: boolean): Promise<any>;
69
69
  listImages(raw: unknown): Promise<{
70
70
  results: any[];
71
71
  total: number;
@@ -90,6 +90,12 @@ export declare class DeploymentEngine {
90
90
  private advance;
91
91
  /** Switches on deployment; when the key may not, the operation stops with what to do instead. */
92
92
  private enableDeployment;
93
+ /**
94
+ * Switches on deployment for a project that has it off, before anything else is added to
95
+ * it: Constructor adds an external image only to a project with deployment on. Switching
96
+ * it on twice is harmless, so this runs outside a saved operation.
97
+ */
98
+ ensureDeployment(project: string, known?: boolean): Promise<void>;
93
99
  private advanceBuild;
94
100
  private advanceLifecycle;
95
101
  private advanceApp;
@@ -144,6 +144,12 @@ function hardwareOptions(hardware) {
144
144
  .sort((a, b) => +!!a.gpu - +!!b.gpu || a.cpu - b.cpu || a.ram_gb - b.ram_gb)
145
145
  .filter((o) => !seen.has(JSON.stringify(o)) && !!seen.add(JSON.stringify(o)));
146
146
  }
147
+ /** Only the project owner may switch deployment on (421, error 40005; older servers 403). */
148
+ function ownerOnly(err) {
149
+ if (err instanceof ToolError && (err.apiCode === 40005 || err.status === 403))
150
+ return 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);
151
+ return err;
152
+ }
147
153
  export class DeploymentEngine {
148
154
  api;
149
155
  store;
@@ -275,7 +281,7 @@ export class DeploymentEngine {
275
281
  if (log)
276
282
  op.failure.log_tail = log.lines;
277
283
  op.message = `Image build${service ? ` for ${service}` : ""} failed${first ? ` twice (${first}, then ${image.name} after re-checking the files)` : ` (${image.name})`}. ${log
278
- ? "The last build log lines are in failure.log_tail (get_logs with the image ID shows up to 50)."
284
+ ? "The last build log lines are in failure.log_tail (get_logs with the image ID shows up to 500)."
279
285
  : `No build log was captured. To see the error, open the desk (${link}), rebuild ${dockerfile} from the UI and watch the live log.`} Fix the Dockerfile or source, then deploy again.`;
280
286
  }
281
287
  /** Poll public URLs after start until they answer or readinessSeconds pass. */
@@ -434,7 +440,7 @@ export class DeploymentEngine {
434
440
  * non-amd64 or malformed image with its reason. Undefined when this Constructor
435
441
  * has no such endpoint yet (the caller then builds it from FROM).
436
442
  */
437
- async registerExternal(project, service, reference) {
443
+ async registerExternal(project, service, reference, retried = false) {
438
444
  try {
439
445
  return await this.api.request("POST", this.root(project) + "/images/external", { name: externalName(reference), reference });
440
446
  }
@@ -443,6 +449,12 @@ export class DeploymentEngine {
443
449
  throw err;
444
450
  if (err.status === 404 || err.status === 405)
445
451
  return undefined;
452
+ // The project's deployment is off (switched off meanwhile, or the caller did not
453
+ // check): switch it on and ask once more.
454
+ if (!retried && /deployment is not enabled/i.test(err.reason ?? "")) {
455
+ await this.ensureDeployment(project, false);
456
+ return this.registerExternal(project, service, reference, true);
457
+ }
446
458
  if ([400, 421, 422].includes(err.status ?? 0)) {
447
459
  const why = cleanReason(err.reason);
448
460
  throw new ToolError("image_refused", `Service ${service}: Constructor refused image ${reference}${why ? `: ${why}` : ""}. Nothing was deployed. Only public images with a linux/amd64 variant can be used; check the name and tag (Docker Hub images as name:tag or user/name:tag). Tell the user, or use build with a Dockerfile instead.`, err.status, err.apiCode, { stage: "register", service, image: reference });
@@ -861,7 +873,7 @@ export class DeploymentEngine {
861
873
  const log = id && (await this.logs?.peek(id, "service", 20));
862
874
  if (log) {
863
875
  op.failure = { ...op.failure, log_tail: log.lines };
864
- op.message = `${op.failure.stage} failed for ${op.failure.service}. The last service log lines are in failure.log_tail (get_logs with the service ID shows up to 50).`;
876
+ op.message = `${op.failure.stage} failed for ${op.failure.service}. The last service log lines are in failure.log_tail (get_logs with the service ID shows up to 500).`;
865
877
  }
866
878
  }
867
879
  await this.store.save(op);
@@ -876,11 +888,24 @@ export class DeploymentEngine {
876
888
  });
877
889
  }
878
890
  catch (err) {
879
- // Only the project owner may switch it on (421, error 40005); older servers answer 403.
880
- if (err instanceof ToolError &&
881
- (err.apiCode === 40005 || err.status === 403))
882
- 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);
883
- throw err;
891
+ throw ownerOnly(err);
892
+ }
893
+ }
894
+ /**
895
+ * Switches on deployment for a project that has it off, before anything else is added to
896
+ * it: Constructor adds an external image only to a project with deployment on. Switching
897
+ * it on twice is harmless, so this runs outside a saved operation.
898
+ */
899
+ async ensureDeployment(project, known) {
900
+ if (known ?? (await this.project(project)).deployment_enabled)
901
+ return;
902
+ try {
903
+ await this.api.request("POST", this.root(project) + "/deployment", {
904
+ enabled: true,
905
+ });
906
+ }
907
+ catch (err) {
908
+ throw ownerOnly(err);
884
909
  }
885
910
  }
886
911
  async advanceBuild(op) {
package/dist/install.js CHANGED
@@ -9,7 +9,7 @@ import { styleText } from "node:util";
9
9
  import { AGENTS, PACKAGE_SPEC, SERVER, applyEntry, claudeCliWorks, describe, detect, mcpCommand, succeeded, } from "./agents.js";
10
10
  import { cleanKey } from "./api.js";
11
11
  import { DEFAULT_BASE_URL, configFromEnv, originOf } from "./config.js";
12
- import { checkKey, readKeyFile, saveKeyFile } from "./key.js";
12
+ import { readKeyFile, routeKey, saveKeyFile } from "./key.js";
13
13
  const bold = (s) => styleText("bold", s);
14
14
  const dim = (s) => styleText("dim", s);
15
15
  const accent = (s) => styleText("cyan", s);
@@ -228,14 +228,18 @@ export async function runInstall(argv) {
228
228
  saved = undefined; // A broken key file is replaced by the new key.
229
229
  }
230
230
  let base;
231
+ /** Inside a Constructor desk, the server it names; the key is checked there too. */
232
+ const deskServer = config.localDesk?.server;
231
233
  try {
232
234
  const given = value("--constructor");
233
235
  if (given)
234
236
  base = linkOrigin(given);
235
237
  else if (yes)
236
- base = saved?.url ?? DEFAULT_BASE_URL;
238
+ base = saved?.url ?? deskServer ?? DEFAULT_BASE_URL;
237
239
  else {
238
- const savedOrg = saved && saved.url !== DEFAULT_BASE_URL ? saved.url : "";
240
+ // Inside a desk its server is the likely answer, but the user may open another address.
241
+ const known = saved?.url ?? deskServer;
242
+ const savedOrg = known && known !== DEFAULT_BASE_URL ? known : "";
239
243
  const where = await ask(p.select({
240
244
  message: `Where do you have access to ${bold("Constructor Research")}?`,
241
245
  initialValue: savedOrg ? "org" : "public",
@@ -286,21 +290,33 @@ export async function runInstall(argv) {
286
290
  // ---- 4. the access key ---------------------------------------------------------------------
287
291
  let keySaved = false;
288
292
  let keyProblem = "";
293
+ const short = (u) => u.replace(/^https:\/\//, "");
289
294
  const check = async (key) => {
290
295
  if (demo)
291
296
  return "ok";
292
297
  const s = p.spinner();
293
- s.start(`Checking the key with ${base.replace(/^https:\/\//, "")}`);
294
- const { result } = await checkKey(base, config.apiPath, key);
295
- if (result === "ok")
296
- s.stop("Key accepted");
297
- else if (result === "rejected")
298
- s.error(`${base} rejected this key`);
298
+ const also = deskServer && deskServer !== base;
299
+ s.start(`Checking the key with ${short(base)}${also ? ` and this desk's server ${short(deskServer)}` : ""}`);
300
+ const route = await routeKey(base, deskServer, config.apiPath, key, {
301
+ checkHome: true,
302
+ });
303
+ const said = (where, r) => r === "rejected"
304
+ ? `${where} rejected this key`
305
+ : r === "unreachable"
306
+ ? `Could not reach ${where} (VPN?)`
307
+ : `${where} answered without the public API`;
308
+ if (route.result === "ok")
309
+ s.stop(route.origin === base
310
+ ? "Key accepted"
311
+ : `Key accepted by this desk's server ${short(route.origin)}; requests from this desk go there${route.home === "ok" ? "" : ` (${said(short(base), route.home)})`}`);
299
312
  else
300
- s.error(result === "unreachable"
301
- ? `Could not reach ${base} (VPN?)`
302
- : `${base} answered without the public API`);
303
- return result;
313
+ s.error([
314
+ said(base, route.home),
315
+ ...(route.server
316
+ ? [said(`this desk's server ${deskServer}`, route.server)]
317
+ : []),
318
+ ].join("; "));
319
+ return route.result;
304
320
  };
305
321
  let key;
306
322
  if (yes) {
package/dist/key.d.ts CHANGED
@@ -13,3 +13,25 @@ export declare function checkKey(url: string, apiPath: string, key: string, time
13
13
  result: KeyCheck;
14
14
  status?: number;
15
15
  }>;
16
+ /**
17
+ * Inside a Constructor desk two addresses can lead to the user's Constructor: the one the user
18
+ * named (the key's: links, key help and the key file keep it) and the server the desk names
19
+ * (ROLOS_API_SERVER), which may differ, e.g. https://constructor.app in a desk the user opened on
20
+ * https://acme.constructor.app. Requests go to the desk's server when it accepts the key, else to
21
+ * the user's address. The desk's server is the Constructor the desk runs on, so asking it about
22
+ * the key sends the key nowhere new.
23
+ */
24
+ export interface KeyRoute {
25
+ /** Where requests with this key go. */
26
+ origin: string;
27
+ /** "ok" when an address accepted the key, else the user's address's answer; undefined when nothing was asked. */
28
+ result?: KeyCheck;
29
+ /** The user's address's answer; only when asked for (setup). */
30
+ home?: KeyCheck;
31
+ /** The desk server's answer; only inside a desk whose server differs from the user's address. */
32
+ server?: KeyCheck;
33
+ }
34
+ export declare function routeKey(home: string, server: string | undefined, apiPath: string, key: string, { checkHome, timeoutMs }?: {
35
+ checkHome?: boolean | undefined;
36
+ timeoutMs?: number | undefined;
37
+ }): Promise<KeyRoute>;
package/dist/key.js CHANGED
@@ -63,3 +63,17 @@ export async function checkKey(url, apiPath, key, timeoutMs = 15000) {
63
63
  return { result: "unreachable" };
64
64
  }
65
65
  }
66
+ export async function routeKey(home, server, apiPath, key, { checkHome = false, timeoutMs = 15000 } = {}) {
67
+ const other = server && server !== home ? server : undefined;
68
+ const [h, s] = await Promise.all([
69
+ checkHome ? checkKey(home, apiPath, key, timeoutMs) : undefined,
70
+ other ? checkKey(other, apiPath, key, timeoutMs) : undefined,
71
+ ]);
72
+ const accepted = h?.result === "ok" || s?.result === "ok";
73
+ return {
74
+ origin: s?.result === "ok" ? other : home,
75
+ result: accepted ? "ok" : (h ?? s)?.result,
76
+ home: h?.result,
77
+ server: s?.result,
78
+ };
79
+ }
@@ -10,10 +10,13 @@ implied?: boolean): z.ZodObject<{
10
10
  desk_id?: z.ZodOptional<z.ZodString> | undefined;
11
11
  desk_url: z.ZodOptional<z.ZodString>;
12
12
  }, z.core.$strip>;
13
- /** Project and desk IDs from a desk link; the host must be the Constructor this MCP uses. */
14
- export declare function parseDeskUrl(link: string, baseUrl: string, fixed?: boolean): {
13
+ /**
14
+ * Project and desk IDs from a desk link. Its host must be the user's Constructor (the first
15
+ * address) or, inside a desk, the server that desk names, which may differ from it.
16
+ */
17
+ export declare function parseDeskUrl(link: string, baseUrl: string | string[], fixed?: boolean): {
15
18
  project_id: string;
16
19
  desk_id: string;
17
20
  };
18
21
  /** Replace desk_url with the IDs it carries; explicit IDs must agree with it. */
19
- export declare function resolveDeskUrl(args: any, baseUrl: string, scope: Scope, fixed?: boolean): any;
22
+ export declare function resolveDeskUrl(args: any, baseUrl: string | string[], scope: Scope, fixed?: boolean): any;
package/dist/location.js CHANGED
@@ -25,7 +25,10 @@ implied = false) {
25
25
  function bad(code, message) {
26
26
  throw new ToolError(code, message);
27
27
  }
28
- /** Project and desk IDs from a desk link; the host must be the Constructor this MCP uses. */
28
+ /**
29
+ * Project and desk IDs from a desk link. Its host must be the user's Constructor (the first
30
+ * address) or, inside a desk, the server that desk names, which may differ from it.
31
+ */
29
32
  export function parseDeskUrl(link, baseUrl, fixed = false) {
30
33
  let url;
31
34
  try {
@@ -37,10 +40,10 @@ export function parseDeskUrl(link, baseUrl, fixed = false) {
37
40
  const m = url.pathname.match(/\/projects\/([a-zA-Z0-9_-]{4,128})\/desks\/([a-zA-Z0-9_-]{4,128})(?:\/|$)/);
38
41
  if (!m)
39
42
  bad("invalid_input", "desk_url must contain /projects/<project>/desks/<desk>. Ask the user to open the desk in Constructor and copy the address bar.");
40
- const base = new URL(baseUrl).origin;
41
- if (url.origin !== base)
43
+ const [base, ...also] = [baseUrl].flat().map((u) => new URL(u).origin);
44
+ if (url.origin !== base && !also.includes(url.origin))
42
45
  bad("wrong_environment", fixed
43
- ? `The link is for ${url.origin}, but this MCP is fixed to ${base} by CONSTRUCTOR_BASE_URL or the desk it runs in. Ask the user for a link from ${base}.`
46
+ ? `The link is for ${url.origin}, but this MCP is fixed to ${base} by CONSTRUCTOR_BASE_URL. Ask the user for a link from ${base}.`
44
47
  : `The link is for ${url.origin}, but the saved access key is for ${base}. If they work on ${url.origin}, the user saves a key for it in a terminal (it replaces the key for ${base}): npx -y -p constructor-research-mcp@${VERSION} constructor-research-set-key ${url.origin}. Never ask for the key in the chat.`);
45
48
  return { project_id: m[1], desk_id: m[2] };
46
49
  }
package/dist/logs.d.ts CHANGED
@@ -1,9 +1,16 @@
1
1
  import { PlatformApi } from "./api.js";
2
- /** Lines kept per build; the tool returns up to this many. */
3
- export declare const KEEP = 50;
2
+ /** Lines kept per build or service, in memory and in its file. */
3
+ export declare const KEEP = 2000;
4
+ /** The most lines get_logs returns at once. */
5
+ export declare const SHOW = 500;
4
6
  export type LogState = "live" | "finished" | "unavailable";
5
7
  /** Every connection replays the log from the start (a service: its current container), then streams. */
6
8
  export type LogKind = "build" | "service";
9
+ /** A stretch of time the MCP followed a log; `to` is missing while it still does. */
10
+ export interface Period {
11
+ from: string;
12
+ to?: string;
13
+ }
7
14
  export interface LogView {
8
15
  kind: LogKind;
9
16
  id: string;
@@ -13,11 +20,13 @@ export interface LogView {
13
20
  /** New containers seen starting while the MCP followed this service. */
14
21
  restarts_seen?: number;
15
22
  restarted_at?: string[];
23
+ /** When the MCP followed this log; lines printed outside these periods were never seen. */
24
+ watched?: Period[];
16
25
  message?: string;
17
26
  }
18
27
  /**
19
- * Follows build and service log streams and keeps only the last KEEP lines of each, in
20
- * memory and in a small file in the state directory. The platform serves a build log only
28
+ * Follows build and service log streams and keeps the last KEEP lines of each, in memory
29
+ * and in a file in the state directory; old files are deleted (rotate). The platform serves a build log only
21
30
  * while the build runs, and every connection replays it from the start, so a dropped
22
31
  * stream is reopened and already-seen lines are skipped. When the build ends the stream
23
32
  * closes and reopening answers "not found"; the kept lines stay readable. A service log
@@ -35,6 +44,12 @@ export declare class LogFollower {
35
44
  idleMs: number;
36
45
  /** How long to follow after the last interest: builds until they end, services briefly. */
37
46
  followMs: Record<LogKind, number>;
47
+ /** Kept files older than this are deleted. */
48
+ retainMs: number;
49
+ /** Beyond this many bytes of kept files, the oldest are deleted. */
50
+ maxBytes: number;
51
+ /** When old files were last looked for. */
52
+ private rotated;
38
53
  constructor(api: PlatformApi, dir?: string);
39
54
  /** Start following if nobody is; cheap to call on every poll. */
40
55
  follow(id: string, kind?: LogKind): void;
@@ -54,6 +69,11 @@ export declare class LogFollower {
54
69
  /** At most every few seconds while streaming, and once at the end. */
55
70
  private save;
56
71
  private load;
57
- /** Forget the oldest finished builds; their files remain. */
72
+ /** Forget the oldest finished logs; their files remain. */
58
73
  private prune;
74
+ /**
75
+ * Deletes kept files older than retainMs, then the oldest until all of them fit in
76
+ * maxBytes. Logs being followed now are never deleted. Runs at most hourly, on save.
77
+ */
78
+ rotate(): Promise<void>;
59
79
  }
package/dist/logs.js CHANGED
@@ -1,9 +1,13 @@
1
- import { mkdir, readFile, writeFile } from "node:fs/promises";
1
+ import { mkdir, readdir, readFile, rm, stat, writeFile, } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { ToolError, segment } from "./api.js";
5
- /** Lines kept per build; the tool returns up to this many. */
6
- export const KEEP = 50;
5
+ /** Lines kept per build or service, in memory and in its file. */
6
+ export const KEEP = 2000;
7
+ /** The most lines get_logs returns at once. */
8
+ export const SHOW = 500;
9
+ /** Periods of watching kept per log. */
10
+ const PERIODS = 20;
7
11
  /** Longer lines are cut, so one runaway line cannot fill memory. */
8
12
  const WIDTH = 1000;
9
13
  const ID = /^[a-zA-Z0-9_-]{4,128}$/;
@@ -18,8 +22,8 @@ const PATH = {
18
22
  service: "services",
19
23
  };
20
24
  /**
21
- * Follows build and service log streams and keeps only the last KEEP lines of each, in
22
- * memory and in a small file in the state directory. The platform serves a build log only
25
+ * Follows build and service log streams and keeps the last KEEP lines of each, in memory
26
+ * and in a file in the state directory; old files are deleted (rotate). The platform serves a build log only
23
27
  * while the build runs, and every connection replays it from the start, so a dropped
24
28
  * stream is reopened and already-seen lines are skipped. When the build ends the stream
25
29
  * closes and reopening answers "not found"; the kept lines stay readable. A service log
@@ -38,8 +42,14 @@ export class LogFollower {
38
42
  /** How long to follow after the last interest: builds until they end, services briefly. */
39
43
  followMs = {
40
44
  build: 2 * 60 * 60 * 1000,
41
- service: 15 * 60 * 1000,
45
+ service: 2 * 60 * 60 * 1000,
42
46
  };
47
+ /** Kept files older than this are deleted. */
48
+ retainMs = 14 * 24 * 60 * 60 * 1000;
49
+ /** Beyond this many bytes of kept files, the oldest are deleted. */
50
+ maxBytes = 100 * 1024 * 1024;
51
+ /** When old files were last looked for. */
52
+ rotated = 0;
43
53
  constructor(api, dir = join(api.config.stateDir, "logs")) {
44
54
  this.api = api;
45
55
  this.dir = dir;
@@ -61,15 +71,22 @@ export class LogFollower {
61
71
  restarts: [],
62
72
  state: "live",
63
73
  saved: 0,
74
+ watched: [],
64
75
  };
65
76
  this.logs.set(`${kind}:${id}`, log);
66
77
  this.prune();
67
78
  }
68
79
  log.state = "live";
69
80
  log.error = undefined;
81
+ log.watched.push({ from: new Date().toISOString() });
82
+ if (log.watched.length > PERIODS)
83
+ log.watched.shift();
70
84
  const current = log;
71
85
  current.reader = this.read(id, current).finally(() => {
72
86
  current.reader = undefined;
87
+ const period = current.watched.at(-1);
88
+ if (period && !period.to)
89
+ period.to = new Date().toISOString();
73
90
  if (current.state === "live")
74
91
  current.state = current.lines.length ? "finished" : "unavailable";
75
92
  return this.save(id, current, true);
@@ -109,30 +126,43 @@ export class LogFollower {
109
126
  view(id, log, count) {
110
127
  const service = log.kind === "service";
111
128
  const restarts = log.restarts.length;
129
+ const lines = log.lines.slice(-Math.max(1, Math.min(KEEP, count)));
130
+ const said = log.error ??
131
+ (restarts
132
+ ? `The container restarted ${restarts} time${restarts > 1 ? "s" : ""} while the MCP followed it (last at ${log.restarts.at(-1)}). Lines above each "--- new container" marker come from the container before it; its last lines usually show why it stopped.`
133
+ : undefined) ??
134
+ (log.state === "unavailable"
135
+ ? service
136
+ ? "No log: the service is not running, or its current container has printed nothing (a container that keeps crashing has no current log)."
137
+ : "No log: the build is not running and this MCP did not follow it while it ran. Constructor serves build logs only during the build."
138
+ : log.state === "finished"
139
+ ? service
140
+ ? "No longer following; these are the last lines kept."
141
+ : "The build is no longer running; these are the last lines it wrote."
142
+ : service
143
+ ? "Following the log of the service's current container. No lines can mean the container keeps restarting (crash loop) or has printed nothing yet."
144
+ : undefined);
145
+ // Every connection replays the current container from its start, so only a container
146
+ // that started and stopped while nobody followed is lost: Constructor keeps no old logs.
147
+ const gaps = service && log.state !== "live" && log.watched.length
148
+ ? `The MCP followed this service's log ${log.watched
149
+ .map((p) => `from ${p.from} to ${p.to ?? "now"}`)
150
+ .join(", ")}. A container that started and stopped outside ${log.watched.length > 1 ? "those periods" : "that period"} left no lines here, because Constructor serves logs only while they are live.`
151
+ : undefined;
152
+ const more = log.lines.length > lines.length
153
+ ? `${log.lines.length} lines are kept; ask for more with lines (up to ${SHOW}).`
154
+ : undefined;
112
155
  return {
113
156
  kind: log.kind,
114
157
  id,
115
158
  state: log.state,
116
- lines: log.lines.slice(-Math.max(1, Math.min(KEEP, count))),
159
+ lines,
117
160
  last_received_at: log.received,
118
161
  ...(restarts
119
162
  ? { restarts_seen: restarts, restarted_at: log.restarts }
120
163
  : {}),
121
- message: log.error ??
122
- (restarts
123
- ? `The container restarted ${restarts} time${restarts > 1 ? "s" : ""} while the MCP followed it (last at ${log.restarts.at(-1)}). Lines above each "--- new container" marker come from the container before it; its last lines usually show why it stopped.`
124
- : undefined) ??
125
- (log.state === "unavailable"
126
- ? service
127
- ? "No log: the service is not running, or its current container has printed nothing (a container that keeps crashing has no current log)."
128
- : "No log: the build is not running and this MCP did not follow it while it ran. Constructor serves build logs only during the build."
129
- : log.state === "finished"
130
- ? service
131
- ? "No longer following; these are the last lines kept."
132
- : "The build is no longer running; these are the last lines it wrote."
133
- : service
134
- ? "Following the log of the service's current container. No lines can mean the container keeps restarting (crash loop) or has printed nothing yet."
135
- : undefined),
164
+ ...(log.watched.length ? { watched: log.watched } : {}),
165
+ message: [said, gaps, more].filter(Boolean).join(" ") || undefined,
136
166
  };
137
167
  }
138
168
  async read(id, log) {
@@ -290,7 +320,10 @@ export class LogFollower {
290
320
  restarts: log.restarts,
291
321
  received: log.received,
292
322
  error: log.error,
323
+ watched: log.watched,
293
324
  }), { mode: 0o600 });
325
+ if (Date.now() - this.rotated > 60 * 60 * 1000)
326
+ await this.rotate();
294
327
  }
295
328
  catch {
296
329
  /* Logs are a convenience; never fail a deployment over them. */
@@ -310,7 +343,14 @@ export class LogFollower {
310
343
  received: kept.received,
311
344
  error: kept.error,
312
345
  saved: 0,
346
+ watched: Array.isArray(kept.watched)
347
+ ? kept.watched.filter((p) => typeof p?.from === "string")
348
+ : [],
313
349
  };
350
+ // A period another process left open ended when it last wrote the file, at the latest.
351
+ const open = log.watched.at(-1);
352
+ if (open && !open.to)
353
+ open.to = log.received ?? open.from;
314
354
  this.logs.set(`${kind}:${id}`, log);
315
355
  return log;
316
356
  }
@@ -318,13 +358,50 @@ export class LogFollower {
318
358
  return undefined;
319
359
  }
320
360
  }
321
- /** Forget the oldest finished builds; their files remain. */
361
+ /** Forget the oldest finished logs; their files remain. */
322
362
  prune() {
323
363
  for (const [id, log] of this.logs) {
324
- if (this.logs.size <= 100)
364
+ if (this.logs.size <= 30)
325
365
  return;
326
366
  if (!log.reader)
327
367
  this.logs.delete(id);
328
368
  }
329
369
  }
370
+ /**
371
+ * Deletes kept files older than retainMs, then the oldest until all of them fit in
372
+ * maxBytes. Logs being followed now are never deleted. Runs at most hourly, on save.
373
+ */
374
+ async rotate() {
375
+ this.rotated = Date.now();
376
+ try {
377
+ const live = new Set([...this.logs]
378
+ .filter(([, log]) => log.reader)
379
+ .map(([key]) => key.replace(":", "-") + ".json"));
380
+ const files = [];
381
+ for (const name of await readdir(this.dir)) {
382
+ if (!/^(build|service)-[a-zA-Z0-9_-]+\.json$/.test(name))
383
+ continue;
384
+ const info = await stat(join(this.dir, name)).catch(() => undefined);
385
+ if (info)
386
+ files.push({ name, at: info.mtimeMs, size: info.size });
387
+ }
388
+ files.sort((a, b) => b.at - a.at); // newest first
389
+ let total = 0;
390
+ for (const f of files) {
391
+ total += f.size;
392
+ const old = Date.now() - f.at > this.retainMs || total > this.maxBytes;
393
+ if (old && !live.has(f.name)) {
394
+ await rm(join(this.dir, f.name), { force: true });
395
+ total -= f.size;
396
+ const [kind, ...rest] = f.name.slice(0, -5).split("-");
397
+ const key = `${kind}:${rest.join("-")}`;
398
+ if (!this.logs.get(key)?.reader)
399
+ this.logs.delete(key);
400
+ }
401
+ }
402
+ }
403
+ catch {
404
+ /* Logs are a convenience; never fail over them. */
405
+ }
406
+ }
330
407
  }
package/dist/schemas.js CHANGED
@@ -205,9 +205,9 @@ export const logsInput = z
205
205
  .number()
206
206
  .int()
207
207
  .min(10)
208
- .max(50)
208
+ .max(500)
209
209
  .default(20)
210
- .describe("How many of the last log lines to return."),
210
+ .describe("How many of the last log lines to return (up to 500; the MCP keeps 2000 per log)."),
211
211
  })
212
212
  .refine((x) => [x.image_id, x.service_id, x.deployment_id].filter(Boolean).length === 1, "Pass one of image_id, service_id or deployment_id.");
213
213
  export const listFilesInput = z.strictObject({
package/dist/server.js CHANGED
@@ -58,11 +58,18 @@ async function main() {
58
58
  // registry image is added to the project as an external image: no desk, no build.
59
59
  const added = new Map();
60
60
  let services = [];
61
+ let switchedOn = false;
61
62
  for (const x of await engine.resolveImages(a.project_id, a.services)) {
62
63
  if (!x.image) {
63
64
  services.push(x);
64
65
  continue;
65
66
  }
67
+ // Constructor adds external images only to a project with deployment on, which the
68
+ // deployment itself would switch on only later.
69
+ if (!switchedOn) {
70
+ await engine.ensureDeployment(a.project_id);
71
+ switchedOn = true;
72
+ }
66
73
  if (!/^[a-z0-9][a-z0-9._/:@-]*$/i.test(x.image))
67
74
  throw new ToolError("invalid_input", `Service ${x.name}: invalid image reference.`);
68
75
  const ref = shortReference(x.image);
@@ -255,7 +262,9 @@ async function main() {
255
262
  ...args,
256
263
  desk_url: `${config.baseUrl}/research/projects/${here.projectId}/desks/${here.deskId}`,
257
264
  }
258
- : args, config.baseUrl, scope, config.baseUrlFixed)
265
+ : args,
266
+ // Links from the desk's own server work too.
267
+ [config.baseUrl, config.localDesk?.server ?? []].flat(), scope, config.baseUrlFixed)
259
268
  : args;
260
269
  // A desk tool given only the project acts on its only desk, or asks which one.
261
270
  if (scope === "desk" &&
@@ -321,7 +330,7 @@ async function main() {
321
330
  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");
322
331
  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");
323
332
  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");
324
- 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) => {
333
+ register("get_logs", "Last lines (default 20, up to 500) 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 it starts until they end, and the services it starts or shows for two hours after that (or after the last get_logs), and keeps their last 2000 lines on this machine for 14 days, so they stay readable after the build ends, the container restarts or the agent restarts; watched says when it followed. 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) => {
325
334
  const i = logsInput.parse(a);
326
335
  let targets = [];
327
336
  if (i.image_id)
package/dist/set-key.js CHANGED
@@ -4,7 +4,13 @@
4
4
  // Usage: npx -y -p constructor-research-mcp constructor-research-set-key <Constructor link>
5
5
  import { configFromEnv, originOf } from "./config.js";
6
6
  import { cleanKey } from "./api.js";
7
- import { checkKey, saveKeyFile } from "./key.js";
7
+ import { routeKey, saveKeyFile } from "./key.js";
8
+ /** What an address answered about the key, for messages. */
9
+ const said = (r) => r === "rejected"
10
+ ? "rejected this key"
11
+ : r === "unreachable"
12
+ ? "could not be reached (VPN?)"
13
+ : "answered without the public API";
8
14
  const USAGE = "Usage: npx -y -p constructor-research-mcp constructor-research-set-key <Constructor link, e.g. https://acme.constructor.app>\nThen paste the access key (rk-…) when asked, or pipe it in on stdin.";
9
15
  /** One line from the terminal without echoing it, or all of stdin when piped. */
10
16
  async function readSecret(prompt) {
@@ -71,22 +77,22 @@ async function main() {
71
77
  console.error("That is not an access key; nothing saved.");
72
78
  return 1;
73
79
  }
74
- // Check the key with Constructor before saving it.
75
- const { result, status } = await checkKey(url, config.apiPath, key);
76
- if (result === "unreachable") {
77
- console.error(`Could not reach ${url} (VPN?); nothing saved.`);
78
- return 1;
79
- }
80
- if (result === "rejected") {
81
- console.error(`${url} rejected this key; nothing saved.`);
82
- return 1;
83
- }
84
- if (result !== "ok") {
85
- console.error(`${url} answered HTTP ${status}: it may not have the public API yet; nothing saved.`);
80
+ // Check the key with Constructor before saving it; inside a desk, with its server too.
81
+ const server = config.localDesk?.server;
82
+ const route = await routeKey(url, server, config.apiPath, key, {
83
+ checkHome: true,
84
+ });
85
+ if (route.result !== "ok") {
86
+ const also = route.server
87
+ ? `; this desk's server ${server} ${said(route.server)}`
88
+ : "";
89
+ console.error(`${url} ${said(route.home)}${also}; nothing saved.`);
86
90
  return 1;
87
91
  }
88
92
  await saveKeyFile(config.keyFile, url, key);
89
93
  console.log(`Key for ${url} saved to ${config.keyFile}. The MCP uses it from the next call; no restart needed.`);
94
+ if (route.origin !== url)
95
+ console.log(`This desk's server ${route.origin} accepts it${route.home === "ok" ? " too" : ` (${url} ${said(route.home)})`}: requests from this desk go there.`);
90
96
  return 0;
91
97
  }
92
98
  main().then((code) => (process.exitCode = code), () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructor-research-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "Local deployment MCP for Constructor Research",
6
6
  "license": "MIT",