constructor-research-mcp 0.4.0-beta.2 → 0.4.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/INSTALL.md CHANGED
@@ -8,24 +8,32 @@ The MCP lets Claude Code, Codex or OpenCode deploy apps to Constructor Research:
8
8
  - a personal access key (`rk-…`) for your Constructor
9
9
  - macOS, Windows or Linux
10
10
 
11
- ## 1. Add it to your tool
11
+ ## 1. Add it to your tool, with your key
12
+
13
+ The key is required: the MCP does nothing without it. The address is `https://constructor.app`; if your organisation has its own Constructor, use its address instead (e.g. `https://acme.constructor.app`). Replace `rk-your-key` with your key.
12
14
 
13
15
  **Claude Code**: run once:
14
16
 
15
17
  ```sh
16
- claude mcp add --scope user constructor-research -- npx -y constructor-research-mcp@beta
18
+ claude mcp add --scope user constructor-research \
19
+ -e CONSTRUCTOR_BASE_URL=https://constructor.app \
20
+ -e CONSTRUCTOR_ACCESS_KEY=rk-your-key \
21
+ -- npx -y constructor-research-mcp@beta
17
22
  ```
18
23
 
19
24
  On Windows (not WSL), use this instead:
20
25
 
21
26
  ```bat
22
- claude mcp add --scope user constructor-research -- cmd /c npx -y constructor-research-mcp@beta
27
+ claude mcp add --scope user constructor-research -e CONSTRUCTOR_BASE_URL=https://constructor.app -e CONSTRUCTOR_ACCESS_KEY=rk-your-key -- cmd /c npx -y constructor-research-mcp@beta
23
28
  ```
24
29
 
25
30
  **Codex**: run once:
26
31
 
27
32
  ```sh
28
- codex mcp add constructor-research -- npx -y constructor-research-mcp@beta
33
+ codex mcp add constructor-research \
34
+ --env CONSTRUCTOR_BASE_URL=https://constructor.app \
35
+ --env CONSTRUCTOR_ACCESS_KEY=rk-your-key \
36
+ -- npx -y constructor-research-mcp@beta
29
37
  ```
30
38
 
31
39
  The first start downloads the package and can exceed Codex's 10-second start limit. If Codex reports a timeout, restart it once, or add `startup_timeout_sec = 60` under `[mcp_servers.constructor-research]` in `~/.codex/config.toml`. The full entry, if you prefer to write it by hand:
@@ -36,21 +44,13 @@ command = "npx"
36
44
  args = ["-y", "constructor-research-mcp@beta"]
37
45
  startup_timeout_sec = 60
38
46
  tool_timeout_sec = 30
39
- ```
40
-
41
- **OpenCode**: run once; it adds the entry to your OpenCode config and keeps what is already there. Check your version with `opencode --version`. OpenCode 2.x:
42
-
43
- ```sh
44
- opencode mcp add --global constructor-research -- npx -y constructor-research-mcp@beta
45
- ```
46
47
 
47
- Without `--global`, OpenCode 2.x adds it to the current folder's project config instead. OpenCode 1.x has no `--global` and writes to your user config when run outside a project:
48
-
49
- ```sh
50
- opencode mcp add constructor-research -- npx -y constructor-research-mcp@beta
48
+ [mcp_servers.constructor-research.env]
49
+ CONSTRUCTOR_BASE_URL = "https://constructor.app"
50
+ CONSTRUCTOR_ACCESS_KEY = "rk-your-key"
51
51
  ```
52
52
 
53
- Or add it by hand to `~/.config/opencode/opencode.json` (or a project's `opencode.json`). This is the 1.x layout; in 2.x the entry goes one level deeper, under `mcp.servers`, as in [examples/opencode-v2.json](examples/opencode-v2.json):
53
+ **OpenCode**: add the entry to `~/.config/opencode/opencode.json` (or a project's `opencode.json`), keeping what is already there. Check your version with `opencode --version`. OpenCode 1.x:
54
54
 
55
55
  ```json
56
56
  {
@@ -58,29 +58,33 @@ Or add it by hand to `~/.config/opencode/opencode.json` (or a project's `opencod
58
58
  "mcp": {
59
59
  "constructor-research": {
60
60
  "type": "local",
61
- "command": ["npx", "-y", "constructor-research-mcp@beta"]
61
+ "command": ["npx", "-y", "constructor-research-mcp@beta"],
62
+ "environment": {
63
+ "CONSTRUCTOR_BASE_URL": "https://constructor.app",
64
+ "CONSTRUCTOR_ACCESS_KEY": "rk-your-key"
65
+ }
62
66
  }
63
67
  }
64
68
  }
65
69
  ```
66
70
 
67
- Do not put the key in these settings unless you have to; the next step saves it where every tool finds it.
71
+ In 2.x the entry goes one level deeper, under `mcp.servers`, as in [examples/opencode-v2.json](examples/opencode-v2.json), with the same `environment`.
72
+
73
+ Then restart the tool, or run `/mcp` in Claude Code, so it starts the MCP. The first start downloads it and can take a minute.
68
74
 
69
- ## 2. Save your access key
75
+ ## 2. Or keep the key out of the tool's settings
70
76
 
71
- In a terminal, run this with your Constructor's address and paste the key when asked (it is not shown):
77
+ Step 1 stores the key in the tool's settings file (`~/.claude.json`, `~/.codex/config.toml`, `opencode.json`). To avoid that, add the MCP without the two variables (`claude mcp add --scope user constructor-research -- npx -y constructor-research-mcp@beta`, and the same for Codex and OpenCode) and save the key in a terminal; it asks for the key without showing it:
72
78
 
73
79
  ```sh
74
- npx -y -p constructor-research-mcp@beta constructor-research-set-key https://acme.constructor.app
80
+ npx -y -p constructor-research-mcp@beta constructor-research-set-key https://constructor.app
75
81
  ```
76
82
 
77
- It checks the key with Constructor and saves it, with that address, to `~/.config/constructor-research/access-key.json` (readable only by you). Claude Code, Codex and OpenCode all use this one key, and the MCP works with that Constructor. To switch Constructor or replace a revoked key, run it again. Never paste the key into the chat.
78
-
79
- Then restart the tool, or run `/mcp` in Claude Code, so it starts the MCP. The first start downloads it and can take a minute.
83
+ It checks the key with Constructor and saves it, with that address, to `~/.config/constructor-research/access-key.json` (readable only by you). Claude Code, Codex, OpenCode and the wait hooks all use this one file, and a new key needs no restart. To switch Constructor or replace a revoked key, run it again. A key set in the tool's settings wins over the file. Never paste the key into the chat.
80
84
 
81
85
  ## 3. Optional: get told when a deployment finishes
82
86
 
83
- Builds can take many minutes. These add-ons wake the agent when a deployment it started finishes:
87
+ Builds can take many minutes. These add-ons wake the agent when a deployment it started finishes. They do not see the MCP settings: with the key in step 1, also save it with `set-key` (step 2), or give the hooks the same two variables.
84
88
 
85
89
  - Claude Code: merge [examples/claude-hooks.json](examples/claude-hooks.json) into `~/.claude/settings.json`.
86
90
  - Codex: copy [examples/codex-hooks.json](examples/codex-hooks.json) to `~/.codex/hooks.json`, then trust it in `/hooks`.
package/README.md CHANGED
@@ -6,37 +6,35 @@ Local stdio MCP for Codex CLI, Claude Code and OpenCode. Submit the whole applic
6
6
 
7
7
  ## Install
8
8
 
9
- You need Node.js 22+. Then add the MCP to your tool.
9
+ You need Node.js 22+ and your personal access key (`rk-…`); the MCP does not work without it. Add the MCP with the key; the address is `https://constructor.app` unless your organisation has its own Constructor (e.g. `https://acme.constructor.app`).
10
10
 
11
11
  **Claude Code**
12
12
 
13
13
  ```sh
14
- claude mcp add --scope user constructor-research -- npx -y constructor-research-mcp@beta
14
+ claude mcp add --scope user constructor-research \
15
+ -e CONSTRUCTOR_BASE_URL=https://constructor.app \
16
+ -e CONSTRUCTOR_ACCESS_KEY=rk-your-key \
17
+ -- npx -y constructor-research-mcp@beta
15
18
  ```
16
19
 
17
20
  **Codex**
18
21
 
19
22
  ```sh
20
- codex mcp add constructor-research -- npx -y constructor-research-mcp@beta
23
+ codex mcp add constructor-research \
24
+ --env CONSTRUCTOR_BASE_URL=https://constructor.app \
25
+ --env CONSTRUCTOR_ACCESS_KEY=rk-your-key \
26
+ -- npx -y constructor-research-mcp@beta
21
27
  ```
22
28
 
23
- **OpenCode 2.x**
29
+ **OpenCode**: add the entry to `~/.config/opencode/opencode.json` (layouts for 1.x and 2.x in [INSTALL.md](INSTALL.md)).
24
30
 
25
- ```sh
26
- opencode mcp add --global constructor-research -- npx -y constructor-research-mcp@beta
27
- ```
28
-
29
- **OpenCode 1.x** (no `--global` there):
30
-
31
- ```sh
32
- opencode mcp add constructor-research -- npx -y constructor-research-mcp@beta
33
- ```
31
+ Then restart the tool and ask the agent anything about Constructor. Windows notes, the optional wake-up hooks and troubleshooting are in [INSTALL.md](INSTALL.md). Restarting the tool picks up a new version.
34
32
 
35
- Then save your personal access key (see below), restart the tool and ask the agent anything about Constructor. Windows notes, the optional wake-up hooks and troubleshooting are in [INSTALL.md](INSTALL.md). Restarting the tool picks up a new version.
33
+ The key then sits in the tool's settings file (`~/.claude.json`, `~/.codex/config.toml`, `opencode.json`). To keep it out of there, add the MCP without the two variables and save the key with `set-key` (below).
36
34
 
37
35
  ## Access key and connection
38
36
 
39
- The MCP uses only a personal access key (`rk-…`) from Constructor's public API; there is no browser sign-in. Every request carries it as `X-Research-AccessKey: Bearer rk-…`, to the account API (`/api/platform-account/v1`), the desk storage (WebDAV) and the logs alike. The key never goes through the chat: the user saves it in a terminal, where it is read hidden, checked against Constructor and saved:
37
+ The MCP uses only a personal access key (`rk-…`) from Constructor's public API; there is no browser sign-in. Every request carries it as `X-Research-AccessKey: Bearer rk-…`, to the account API (`/api/platform-account/v1`), the desk storage (WebDAV) and the logs alike. The key never goes through the chat. It comes from the MCP settings (`CONSTRUCTOR_ACCESS_KEY`, with `CONSTRUCTOR_BASE_URL`, as in Install), or from a key file the user saves in a terminal, where the key is read hidden, checked against Constructor and saved:
40
38
 
41
39
  ```sh
42
40
  npx -y -p constructor-research-mcp@beta constructor-research-set-key https://acme.constructor.app
@@ -44,7 +42,7 @@ npx -y -p constructor-research-mcp@beta constructor-research-set-key https://acm
44
42
 
45
43
  It goes to `~/.config/constructor-research/access-key.json` (mode 600) together with the Constructor it belongs to, and the MCP works with that Constructor. All harnesses (Claude Code, Codex, OpenCode) and the wait command share this one file. Every request rereads it, so a new key needs no restart. A key is never sent to a Constructor other than the one it was saved for.
46
44
 
47
- Instead of the file, `CONSTRUCTOR_ACCESS_KEY` (with `CONSTRUCTOR_BASE_URL`) can be set in the MCP settings; it takes precedence. The wait hooks do not see the MCP settings, so with this option they need the same variables in their own environment.
45
+ `CONSTRUCTOR_ACCESS_KEY` in the MCP settings takes precedence over the file. The wait hooks do not see the MCP settings: with the key there, give the hooks the same two variables in their own environment, or save the key with `set-key` as well.
48
46
 
49
47
  Without a key, or when Constructor rejects it (401: revoked, expired or for another Constructor), tools return `needs_key` with the command above; a deployment pauses as `needs_key` and resumes on the next check once a valid key is saved. A desk link from another Constructor returns `wrong_environment`.
50
48
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructor-research-mcp",
3
- "version": "0.4.0-beta.2",
3
+ "version": "0.4.0-beta.3",
4
4
  "type": "module",
5
5
  "description": "Local deployment MCP for Constructor Research",
6
6
  "license": "MIT",
package/dist/login.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/dist/login.js DELETED
@@ -1,25 +0,0 @@
1
- #!/usr/bin/env node
2
- // Sign in from a terminal; the MCP's sign_in tool does the same from an agent session.
3
- // Usage: npx -y -p constructor-research-mcp constructor-research-login [--url <any link to your Constructor>] --for claude-code|codex|opencode (or --to <session file>)
4
- import { configFromEnv, HARNESSES, originOf, sessionArgs } from "./config.js";
5
- import { signIn } from "./signin.js";
6
- const config = configFromEnv();
7
- const args = process.argv.slice(2);
8
- const at = args.indexOf("--url");
9
- const url = at >= 0 ? args.splice(at, 2)[1] : undefined;
10
- const { file } = sessionArgs(args, config);
11
- if (!file || (at >= 0 && !url)) {
12
- console.error(`Usage: npx -y -p constructor-research-mcp constructor-research-login [--url <any link to your Constructor>] --for ${HARNESSES.join("|")} (or --to <session file>)`);
13
- process.exit(2);
14
- }
15
- if (url) {
16
- const host = originOf(url);
17
- if (config.baseUrlFixed && host !== config.baseUrl) {
18
- console.error(`CONSTRUCTOR_BASE_URL fixes the MCP to ${config.baseUrl}.`);
19
- process.exit(2);
20
- }
21
- config.baseUrl = host;
22
- }
23
- const result = await signIn(config, file, () => console.log(`A Chrome window opened at ${config.baseUrl}. Sign in there; it closes by itself afterwards.`));
24
- (result.status === "signed_in" ? console.log : console.error)(result.message);
25
- process.exit(result.status === "signed_in" ? 0 : 1);
package/dist/session.d.ts DELETED
@@ -1,21 +0,0 @@
1
- /** The cookies the MCP keeps: the access token for requests, the refresh token to renew it. */
2
- export declare const SESSION_COOKIES: readonly ["ap_access_token", "ap_id_token", "ap_refresh_token"];
3
- /** Claims of a JWT, or undefined when it is not one. */
4
- export declare function claims(jwt?: string): Record<string, any> | undefined;
5
- /** Session cookies found in a Cookie header, a cURL, a Set-Cookie list or a bare JWT. */
6
- export declare function sessionCookies(text: string): Map<string, string>;
7
- /** The session saved in a cookie file; only its cookie line is read. */
8
- export declare function readSession(file: string): Promise<Map<string, string>>;
9
- /**
10
- * The Constructor (an origin) a saved session belongs to: its host line, written at sign-in,
11
- * or else the issuer of its access token. Undefined when nothing is saved.
12
- */
13
- export declare function sessionHost(file: string): Promise<string | undefined>;
14
- /**
15
- * Replaces the cookie line of a file with these cookies, keeping its other lines, and with
16
- * `host` its host line. Written to a temporary file and renamed, mode 600, so a reader never
17
- * sees half a token and a crash never loses the session.
18
- */
19
- export declare function saveSession(file: string, cookies: Map<string, string>, host?: string): Promise<void>;
20
- /** New session cookies from a response's Set-Cookie headers. */
21
- export declare function setCookies(response: Response): Map<string, string>;
package/dist/session.js DELETED
@@ -1,108 +0,0 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { dirname } from "node:path";
3
- import { randomUUID } from "node:crypto";
4
- /** The cookies the MCP keeps: the access token for requests, the refresh token to renew it. */
5
- export const SESSION_COOKIES = [
6
- "ap_access_token",
7
- "ap_id_token",
8
- "ap_refresh_token",
9
- ];
10
- /** Claims of a JWT, or undefined when it is not one. */
11
- export function claims(jwt) {
12
- try {
13
- return JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString());
14
- }
15
- catch {
16
- return undefined;
17
- }
18
- }
19
- /** Session cookies found in a Cookie header, a cURL, a Set-Cookie list or a bare JWT. */
20
- export function sessionCookies(text) {
21
- const found = new Map();
22
- for (const name of SESSION_COOKIES) {
23
- const value = [
24
- ...text.matchAll(new RegExp(`(?:^|[\\s;'"])${name}=([\\w.~+/=-]+)`, "g")),
25
- ].at(-1)?.[1];
26
- if (value)
27
- found.set(name, value);
28
- }
29
- const bare = /^\s*(ey[\w-]+\.[\w-]+\.[\w-]+)\s*$/.exec(text)?.[1];
30
- if (bare && !found.size)
31
- found.set("ap_access_token", bare);
32
- return found;
33
- }
34
- /** Index of the line holding the tokens in a cookie file, or -1. */
35
- const cookieLine = (lines) => lines.findIndex((l) => /^\s*(Cookie:\s*)?(ey[\w-]+\.|.*\bap_(access|refresh)_token=)/.test(l));
36
- /** The session saved in a cookie file; only its cookie line is read. */
37
- export async function readSession(file) {
38
- const lines = (await readFile(file, "utf8")).split(/\r?\n/);
39
- const line = lines[cookieLine(lines)] ?? "";
40
- if (/[\x00-\x1f]/.test(line))
41
- return new Map();
42
- return sessionCookies(line.trim().replace(/^Cookie:\s*/i, ""));
43
- }
44
- /** The line naming the Constructor the session belongs to. */
45
- const HOST = /^host=(\S+)\s*$/;
46
- /**
47
- * The Constructor (an origin) a saved session belongs to: its host line, written at sign-in,
48
- * or else the issuer of its access token. Undefined when nothing is saved.
49
- */
50
- export async function sessionHost(file) {
51
- let lines;
52
- try {
53
- lines = (await readFile(file, "utf8")).split(/\r?\n/);
54
- }
55
- catch {
56
- return undefined;
57
- }
58
- const named = lines.map((l) => HOST.exec(l)?.[1]).find(Boolean);
59
- const line = lines[cookieLine(lines)] ?? "";
60
- const issuer = claims(sessionCookies(line.replace(/^\s*Cookie:\s*/i, "")).get("ap_access_token"))?.iss;
61
- try {
62
- return new URL(named ?? issuer).origin;
63
- }
64
- catch {
65
- return undefined;
66
- }
67
- }
68
- /**
69
- * Replaces the cookie line of a file with these cookies, keeping its other lines, and with
70
- * `host` its host line. Written to a temporary file and renamed, mode 600, so a reader never
71
- * sees half a token and a crash never loses the session.
72
- */
73
- export async function saveSession(file, cookies, host) {
74
- let lines = [];
75
- try {
76
- lines = (await readFile(file, "utf8")).split(/\r?\n/);
77
- }
78
- catch (e) {
79
- if (e.code !== "ENOENT")
80
- throw e;
81
- }
82
- const line = SESSION_COOKIES.filter((n) => cookies.get(n))
83
- .map((n) => `${n}=${cookies.get(n)}`)
84
- .join("; ");
85
- const i = cookieLine(lines);
86
- if (i >= 0)
87
- lines[i] = line;
88
- else
89
- lines.unshift(line);
90
- if (host) {
91
- lines = lines.filter((l) => !HOST.test(l));
92
- lines.splice(lines.indexOf(line) + 1, 0, `host=${host}`);
93
- }
94
- await mkdir(dirname(file), { recursive: true });
95
- const tmp = `${file}.${randomUUID()}.tmp`;
96
- await writeFile(tmp, lines.join("\n").replace(/\n*$/, "\n"), {
97
- mode: 0o600,
98
- flag: "wx",
99
- });
100
- await rename(tmp, file);
101
- }
102
- /** New session cookies from a response's Set-Cookie headers. */
103
- export function setCookies(response) {
104
- return sessionCookies(response.headers
105
- .getSetCookie()
106
- .map((c) => c.split(";")[0])
107
- .join("; "));
108
- }
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/dist/set-token.js DELETED
@@ -1,48 +0,0 @@
1
- #!/usr/bin/env node
2
- // Save the session from a copied cURL (or a bare token) for the MCP without printing it.
3
- // Usage: npx -y -p constructor-research-mcp constructor-research-set-token <file with a copied cURL, or a token> --for claude-code|codex|opencode
4
- // (or --to <session file>); the session belongs to the Constructor the cURL was sent to.
5
- import { readFileSync } from "node:fs";
6
- import { configFromEnv, HARNESSES, originOf, sessionArgs } from "./config.js";
7
- import { claims, saveSession, sessionCookies } from "./session.js";
8
- const { file: target, rest } = sessionArgs(process.argv.slice(2), configFromEnv());
9
- const source = rest[0];
10
- if (!source || !target) {
11
- console.error(`Usage: npx -y -p constructor-research-mcp constructor-research-set-token <file with a copied cURL> --for ${HARNESSES.join("|")} (or --to <session file>)`);
12
- process.exit(2);
13
- }
14
- const text = readFileSync(source, "utf8");
15
- const found = sessionCookies(text);
16
- const token = found.get("ap_access_token");
17
- if (!token) {
18
- console.error("No ap_access_token found in " + source + ".");
19
- process.exit(1);
20
- }
21
- const { exp, max_slt } = claims(token) ?? {};
22
- if (exp && exp * 1000 <= Date.now() && !found.has("ap_refresh_token")) {
23
- console.error("That token already expired at " +
24
- new Date(exp * 1000).toISOString() +
25
- "; copy a fresh one.");
26
- process.exit(1);
27
- }
28
- // The Constructor the cURL was sent to; a bare token names its own issuer.
29
- const sent = /\bcurl\s+(?:-\S+\s+)*['"]?(https?:\/\/[^\s'"]+)/.exec(text)?.[1];
30
- let host;
31
- try {
32
- host = sent ? originOf(sent) : undefined;
33
- }
34
- catch { }
35
- await saveSession(target, found, host);
36
- const time = (s) => new Date(s * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
37
- console.log("Saved to " +
38
- target +
39
- (host ? ` (for ${host})` : "") +
40
- (found.has("ap_refresh_token")
41
- ? `, with the refresh token: the MCP renews the session itself${max_slt ? " until " + time(max_slt) : ""}. The browser this cURL came from holds the same session, and a refresh token works once: whichever renews first logs the other out. The sign_in tool (or constructor-research-login) gives the MCP a session of its own.`
42
- : exp
43
- ? "; expires " +
44
- time(exp) +
45
- " (in " +
46
- Math.round((exp * 1000 - Date.now()) / 60000) +
47
- " min). Copy the cURL with the ap_refresh_token cookie, or use the sign_in tool, and the MCP renews it itself."
48
- : "."));
package/dist/signin.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { Config } from "./config.js";
2
- export type SignInResult = {
3
- status: "signed_in";
4
- message: string;
5
- session_file: string;
6
- host: string;
7
- until?: string;
8
- } | {
9
- status: "sign_in_failed";
10
- message: string;
11
- };
12
- /** A Chromium-based browser on macOS, Windows or Linux; CONSTRUCTOR_BROWSER overrides. */
13
- export declare function findBrowser(): string | undefined;
14
- /**
15
- * Opens the sign-in window, waits for the user to sign in (up to 15 min), saves the
16
- * session cookies to `file`, and closes the window at once. Never returns a token.
17
- * `opened` runs once the window is up.
18
- */
19
- export declare function signIn(config: Pick<Config, "baseUrl" | "apiPath" | "requestTimeoutMs">, file: string, opened?: () => void): Promise<SignInResult>;
package/dist/signin.js DELETED
@@ -1,209 +0,0 @@
1
- // Sign in to Constructor in a separate Chrome window and save the session.
2
- // The window uses a fresh temporary profile: a session nothing else holds, so the MCP can
3
- // renew it without logging out the user's own browser (a refresh token works only once).
4
- import { spawn } from "node:child_process";
5
- import { existsSync } from "node:fs";
6
- import { mkdtemp, readFile, rm } from "node:fs/promises";
7
- import { homedir, tmpdir } from "node:os";
8
- import { delimiter, join } from "node:path";
9
- import { setTimeout as delay } from "node:timers/promises";
10
- import { claims, saveSession, setCookies, SESSION_COOKIES } from "./session.js";
11
- const SIGN_IN_MINUTES = 15;
12
- /** A Chromium-based browser on macOS, Windows or Linux; CONSTRUCTOR_BROWSER overrides. */
13
- export function findBrowser() {
14
- if (process.env.CONSTRUCTOR_BROWSER)
15
- return existsSync(process.env.CONSTRUCTOR_BROWSER)
16
- ? process.env.CONSTRUCTOR_BROWSER
17
- : undefined;
18
- const env = process.env;
19
- const installed = process.platform === "win32"
20
- ? [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA]
21
- .filter((d) => !!d)
22
- .flatMap((d) => [
23
- join(d, "Google", "Chrome", "Application", "chrome.exe"),
24
- join(d, "Microsoft", "Edge", "Application", "msedge.exe"),
25
- join(d, "Chromium", "Application", "chrome.exe"),
26
- join(d, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
27
- ])
28
- : process.platform === "darwin"
29
- ? [
30
- "Google Chrome.app/Contents/MacOS/Google Chrome",
31
- "Chromium.app/Contents/MacOS/Chromium",
32
- "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
33
- "Brave Browser.app/Contents/MacOS/Brave Browser",
34
- ].flatMap((app) => [
35
- join("/Applications", app),
36
- join(homedir(), "Applications", app),
37
- ])
38
- : [];
39
- // Then the PATH, as Linux installs them (and any OS where the user put one there).
40
- const names = [
41
- "google-chrome",
42
- "google-chrome-stable",
43
- "chromium",
44
- "chromium-browser",
45
- "microsoft-edge",
46
- "brave-browser",
47
- "chrome",
48
- "msedge",
49
- ];
50
- const exts = process.platform === "win32"
51
- ? (env.PATHEXT ?? ".EXE").split(";").filter(Boolean)
52
- : [""];
53
- const onPath = (env.PATH ?? "")
54
- .split(delimiter)
55
- .filter(Boolean)
56
- .flatMap((dir) => names.flatMap((n) => exts.map((e) => join(dir, n + e.toLowerCase()))));
57
- return [...installed, ...onPath].find((c) => existsSync(c));
58
- }
59
- /** Minimal Chrome DevTools Protocol client over the browser's WebSocket. */
60
- async function devtools(url) {
61
- const ws = new WebSocket(url);
62
- await new Promise((ok, fail) => {
63
- ws.onopen = ok;
64
- ws.onerror = () => fail(new Error("Could not connect to the browser."));
65
- });
66
- let id = 0;
67
- const waiting = new Map();
68
- ws.onmessage = (e) => {
69
- const m = JSON.parse(String(e.data));
70
- waiting.get(m.id)?.(m);
71
- waiting.delete(m.id);
72
- };
73
- return {
74
- send(method, params = {}) {
75
- return new Promise((ok, fail) => {
76
- const n = ++id;
77
- waiting.set(n, (m) => m.error ? fail(new Error(m.error.message)) : ok(m.result));
78
- ws.send(JSON.stringify({ id: n, method, params }));
79
- });
80
- },
81
- close: () => ws.close(),
82
- };
83
- }
84
- /**
85
- * Opens the sign-in window, waits for the user to sign in (up to 15 min), saves the
86
- * session cookies to `file`, and closes the window at once. Never returns a token.
87
- * `opened` runs once the window is up.
88
- */
89
- export async function signIn(config, file, opened = () => { }) {
90
- const fallback = `save a session from a copied cURL instead: npx -y -p constructor-research-mcp constructor-research-set-token <file with the cURL> --to ${file}`;
91
- const headless = !!process.env.CONSTRUCTOR_LOGIN_HEADLESS;
92
- if (process.platform === "linux" &&
93
- !headless &&
94
- !process.env.DISPLAY &&
95
- !process.env.WAYLAND_DISPLAY)
96
- return {
97
- status: "sign_in_failed",
98
- message: `This machine has no screen to open a sign-in window on (no DISPLAY or WAYLAND_DISPLAY). Sign in where the MCP has a desktop, or ${fallback}.`,
99
- };
100
- const exe = findBrowser();
101
- if (!exe)
102
- return {
103
- status: "sign_in_failed",
104
- message: `No Chrome, Edge, Chromium or Brave found. Set CONSTRUCTOR_BROWSER in the MCP settings to the browser's executable, or ${fallback}.`,
105
- };
106
- const host = new URL(config.baseUrl).hostname;
107
- const profile = await mkdtemp(join(tmpdir(), "constructor-login-"));
108
- const chrome = spawn(exe, [
109
- `--user-data-dir=${profile}`,
110
- "--remote-debugging-port=0",
111
- "--remote-allow-origins=http://127.0.0.1",
112
- "--no-first-run",
113
- "--no-default-browser-check",
114
- "--disable-sync",
115
- // Tests run the browser without a window.
116
- ...(headless ? ["--headless=new"] : []),
117
- "--new-window",
118
- `${config.baseUrl}/research/`,
119
- ], { stdio: "ignore" });
120
- let exited = false;
121
- chrome.on("exit", () => (exited = true));
122
- chrome.on("error", () => (exited = true));
123
- const failed = (message) => ({
124
- status: "sign_in_failed",
125
- message,
126
- });
127
- try {
128
- let port, path;
129
- for (let i = 0; i < 300 && !port && !exited; i++) {
130
- try {
131
- [port, path] = (await readFile(join(profile, "DevToolsActivePort"), "utf8")).split("\n");
132
- }
133
- catch {
134
- await delay(100);
135
- }
136
- }
137
- if (!port)
138
- return failed(`The browser did not start (${exe}); ${fallback}.`);
139
- const cdp = await devtools(`ws://127.0.0.1:${port}${path}`);
140
- opened();
141
- const session = async () => {
142
- const { cookies } = await cdp.send("Storage.getCookies");
143
- return new Map(cookies
144
- .filter((c) => SESSION_COOKIES.includes(c.name) &&
145
- (c.domain.replace(/^\./, "") === host ||
146
- host.endsWith(c.domain.startsWith(".") ? c.domain : "." + c.domain)))
147
- .map((c) => [c.name, c.value]));
148
- };
149
- const deadline = Date.now() + SIGN_IN_MINUTES * 60000;
150
- let found;
151
- while (!exited && Date.now() < deadline) {
152
- const s = await session().catch(() => undefined);
153
- const exp = claims(s?.get("ap_access_token"))?.exp;
154
- if (s?.has("ap_refresh_token") && exp && exp * 1000 > Date.now()) {
155
- // The page may still be loading; read again once it settles, then close at once so
156
- // the window never renews this session itself.
157
- await delay(3000);
158
- found = (await session().catch(() => undefined)) ?? s;
159
- break;
160
- }
161
- await delay(1000);
162
- }
163
- await cdp.send("Browser.close").catch(() => { });
164
- cdp.close();
165
- if (!found)
166
- return failed(exited
167
- ? "The window was closed before sign-in finished; nothing was saved."
168
- : `No sign-in within ${SIGN_IN_MINUTES} min; nothing was saved.`);
169
- // Check the access token without sending the refresh token, so nothing is renewed.
170
- const response = await fetch(config.baseUrl + config.apiPath + "/auth/session", {
171
- headers: {
172
- Cookie: `ap_access_token=${found.get("ap_access_token")}`,
173
- Accept: "application/json",
174
- },
175
- redirect: "manual",
176
- signal: AbortSignal.timeout(config.requestTimeoutMs),
177
- }).catch(() => undefined);
178
- await response?.body?.cancel();
179
- if (response?.status === 401)
180
- return failed("Constructor rejected the new session; nothing was saved.");
181
- await saveSession(file, new Map([...found, ...(response ? setCookies(response) : [])]), config.baseUrl);
182
- const end = claims(found.get("ap_access_token"))?.max_slt;
183
- const until = end
184
- ? new Date(end * 1000).toISOString().slice(0, 16).replace("T", " ") +
185
- " UTC"
186
- : undefined;
187
- return {
188
- status: "signed_in",
189
- message: `Signed in to ${config.baseUrl}. Session saved to ${file}` +
190
- (until ? `; the MCP renews it automatically until ${until}.` : "."),
191
- session_file: file,
192
- host: config.baseUrl,
193
- until,
194
- };
195
- }
196
- catch (e) {
197
- return failed(`Sign-in failed: ${e?.message ?? e}. Nothing was saved.`);
198
- }
199
- finally {
200
- if (!exited) {
201
- chrome.kill();
202
- for (let i = 0; i < 50 && !exited; i++)
203
- await delay(100);
204
- if (!exited)
205
- chrome.kill("SIGKILL"); // TerminateProcess on Windows
206
- }
207
- await rm(profile, { recursive: true, force: true }).catch(() => { });
208
- }
209
- }