@maind-dev/mcp-bridge 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -0
- package/build/auth.js +179 -0
- package/build/auth.js.map +1 -0
- package/build/device-id.js +149 -0
- package/build/device-id.js.map +1 -0
- package/build/forward.js +247 -0
- package/build/forward.js.map +1 -0
- package/build/index.js +120 -0
- package/build/index.js.map +1 -0
- package/build/version.js +7 -0
- package/build/version.js.map +1 -0
- package/package.json +43 -0
package/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# @maind-dev/mcp-bridge
|
|
2
|
+
|
|
3
|
+
A tiny local MCP wrapper that pins your [maind](https://maind.dev) API key to
|
|
4
|
+
a single device. The bridge speaks MCP over stdio to your IDE (Claude Code,
|
|
5
|
+
Cursor, Windsurf, …) and forwards every request to `https://mcp.maind.dev/mcp`
|
|
6
|
+
with an `X-Maind-Device-Id` header, so the server can refuse calls from any
|
|
7
|
+
other machine that tries to reuse the same key.
|
|
8
|
+
|
|
9
|
+
Required for Pro and higher tiers; optional for Free.
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
1. **First run** opens your browser at `https://maind.dev/devices?code=…` and
|
|
14
|
+
prints a short verification code. You sign in (if needed) and click
|
|
15
|
+
**Approve** — the bridge receives an API key and stores it locally under
|
|
16
|
+
`~/.config/maind/` (or platform equivalent). A stable device-id is created
|
|
17
|
+
in the same directory.
|
|
18
|
+
2. **Every subsequent run** reuses the cached key plus device-id and forwards
|
|
19
|
+
stdio JSON-RPC frames to maind, attaching both the `Authorization: Bearer …`
|
|
20
|
+
and `X-Maind-Device-Id` headers.
|
|
21
|
+
3. **If you re-pair from the dashboard** (or move to a new machine), the next
|
|
22
|
+
call returns `401 device_revoked`. The bridge drops its cached key and
|
|
23
|
+
re-runs the device flow once before exiting non-zero on a second failure.
|
|
24
|
+
|
|
25
|
+
The device-id is an opaque UUID; knowing it does not authorize anything. The
|
|
26
|
+
bridge does not transmit your hostname, OS user, or any other identifying
|
|
27
|
+
metadata beyond what the dashboard already shows for VS Code extension
|
|
28
|
+
pairings.
|
|
29
|
+
|
|
30
|
+
## Install / configure
|
|
31
|
+
|
|
32
|
+
You normally don't install anything — `npx` fetches the bridge on first run.
|
|
33
|
+
|
|
34
|
+
Add this to your MCP client's config (`.mcp.json` or equivalent):
|
|
35
|
+
|
|
36
|
+
```json
|
|
37
|
+
{
|
|
38
|
+
"mcpServers": {
|
|
39
|
+
"maind": {
|
|
40
|
+
"command": "npx",
|
|
41
|
+
"args": ["-y", "@maind-dev/mcp-bridge"]
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Restart the MCP client. The first invocation walks you through the device
|
|
48
|
+
flow; subsequent ones are silent (you should never see the verification code
|
|
49
|
+
again unless you re-pair).
|
|
50
|
+
|
|
51
|
+
## Commands
|
|
52
|
+
|
|
53
|
+
| Command | Effect |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `npx -y @maind-dev/mcp-bridge` | Run as MCP server (default; what your IDE invokes) |
|
|
56
|
+
| `npx -y @maind-dev/mcp-bridge --reauth` | Drop the cached key and re-run the device flow |
|
|
57
|
+
| `npx -y @maind-dev/mcp-bridge --version` | Print the bridge version |
|
|
58
|
+
| `npx -y @maind-dev/mcp-bridge --help` | Show usage |
|
|
59
|
+
|
|
60
|
+
## Where things live
|
|
61
|
+
|
|
62
|
+
| Path | Purpose |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `~/Library/Application Support/maind/device-id` (macOS) | Stable per-install UUID |
|
|
65
|
+
| `~/.config/maind/device-id` (Linux/BSD) | Same, on XDG-style systems |
|
|
66
|
+
| `%APPDATA%\maind\device-id` (Windows) | Same, on Windows |
|
|
67
|
+
| `device-id`-sibling file `api-key` | API key returned by approve flow (mode 0600) |
|
|
68
|
+
|
|
69
|
+
To rebind the bridge to a different account: delete the directory above (or run
|
|
70
|
+
`--reauth`) and restart the bridge.
|
|
71
|
+
|
|
72
|
+
## Troubleshooting
|
|
73
|
+
|
|
74
|
+
**"device_mismatch" on every call.** Another machine has bound this key —
|
|
75
|
+
the server is doing the right thing by refusing yours. Either unpair the
|
|
76
|
+
other device from `https://maind.dev/devices`, or `--reauth` here to bind
|
|
77
|
+
this machine and revoke the other.
|
|
78
|
+
|
|
79
|
+
**Browser doesn't open.** The bridge falls back to printing the URL +
|
|
80
|
+
verification code to stderr. Copy the URL into any browser, paste the code on
|
|
81
|
+
the page, click Approve.
|
|
82
|
+
|
|
83
|
+
**Behind a corporate proxy.** Set `HTTPS_PROXY=https://proxy:port` before
|
|
84
|
+
launching your MCP client. The bridge uses Node's built-in `fetch`, which
|
|
85
|
+
respects the proxy env vars on Node 22+.
|
|
86
|
+
|
|
87
|
+
**`npx` can't reach `registry.npmjs.org`.** Install the bridge globally
|
|
88
|
+
(`npm install -g @maind-dev/mcp-bridge`) and point your `.mcp.json` at
|
|
89
|
+
`"command": "maind-mcp-bridge"` instead of `npx`.
|
|
90
|
+
|
|
91
|
+
## Environment overrides
|
|
92
|
+
|
|
93
|
+
Rarely useful outside maind's own development environments:
|
|
94
|
+
|
|
95
|
+
| Variable | Default | Purpose |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `MAIND_MCP_URL` | `https://mcp.maind.dev/mcp` | Streamable-HTTP endpoint to forward to |
|
|
98
|
+
| `MAIND_FUNCTIONS_ORIGIN` | maind's Supabase Edge Functions URL | Device-flow base URL |
|
|
99
|
+
| `XDG_CONFIG_HOME` | `~/.config` (Linux/BSD) | Parent of the `maind/` config dir |
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
MIT — see `LICENSE`.
|
package/build/auth.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// Device-Authorization-Flow client (RFC 8628, adapted for Supabase Edge Functions).
|
|
2
|
+
//
|
|
3
|
+
// Mirrors apps/vscode-extension/src/auth/deviceFlow.ts. The server side
|
|
4
|
+
// (device-authorization-start / -poll Edge Functions + approve_device_authorization
|
|
5
|
+
// RPC chain) is shared between the bridge and the VS Code extension. By using
|
|
6
|
+
// the same flow we get the existing devices-aggregate + revoke-on-pair
|
|
7
|
+
// (ADR-103) for free.
|
|
8
|
+
//
|
|
9
|
+
// Critical: the bridge speaks MCP over stdio. STDOUT is reserved for the JSON-RPC
|
|
10
|
+
// protocol — any progress or auth-flow text MUST go to STDERR. Writing to
|
|
11
|
+
// STDOUT here would corrupt the MCP framing and crash the upstream client.
|
|
12
|
+
import { spawn } from "node:child_process";
|
|
13
|
+
import { platform } from "node:os";
|
|
14
|
+
import { clientMeta, writeApiKey, clearApiKey, ensureDeviceId } from "./device-id.js";
|
|
15
|
+
/**
|
|
16
|
+
* Default Supabase Edge Function origin. Override via env `MAIND_FUNCTIONS_ORIGIN`
|
|
17
|
+
* for self-hosted/preview environments. Production points at the maind
|
|
18
|
+
* project's Supabase Functions endpoint.
|
|
19
|
+
*/
|
|
20
|
+
const DEFAULT_FUNCTIONS_ORIGIN = "https://vsddmiosisvfrairepxv.supabase.co/functions/v1";
|
|
21
|
+
function functionsOrigin() {
|
|
22
|
+
const v = process.env.MAIND_FUNCTIONS_ORIGIN;
|
|
23
|
+
return v && v.length > 0 ? v.replace(/\/+$/, "") : DEFAULT_FUNCTIONS_ORIGIN;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Runs the device-authorization flow end-to-end:
|
|
27
|
+
* 1. POST /device-authorization-start → user_code + verification_uri_complete
|
|
28
|
+
* 2. Open the verification URL in the user's default browser (best-effort)
|
|
29
|
+
* 3. Print the user_code to STDERR as a fallback (so the user can paste manually)
|
|
30
|
+
* 4. Poll /device-authorization-poll every `interval` seconds until approved/denied/expired
|
|
31
|
+
*
|
|
32
|
+
* On approval, persists the returned api_key to disk (api-key file in configDir)
|
|
33
|
+
* and returns it for immediate use. On denial/expiry/timeout, returns null —
|
|
34
|
+
* the caller should exit non-zero so the MCP client treats the bridge as failed.
|
|
35
|
+
*/
|
|
36
|
+
export async function runDeviceFlow(version) {
|
|
37
|
+
const origin = functionsOrigin();
|
|
38
|
+
const startUrl = `${origin}/device-authorization-start`;
|
|
39
|
+
const pollUrl = `${origin}/device-authorization-poll`;
|
|
40
|
+
const meta = clientMeta(version);
|
|
41
|
+
const label = `mcp-bridge-${meta.device_id.slice(0, 8)}`;
|
|
42
|
+
const startRes = await fetch(startUrl, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "content-type": "application/json" },
|
|
45
|
+
body: JSON.stringify({ label, meta }),
|
|
46
|
+
});
|
|
47
|
+
if (!startRes.ok) {
|
|
48
|
+
const txt = await startRes.text();
|
|
49
|
+
throw new Error(`device-authorization-start failed: ${startRes.status} ${txt}`);
|
|
50
|
+
}
|
|
51
|
+
const start = (await startRes.json());
|
|
52
|
+
// Best-effort browser open. If it fails (headless servers, CI, restricted
|
|
53
|
+
// sandbox), the printed verification_uri + user_code is the fallback path.
|
|
54
|
+
await openExternalBrowser(start.verification_uri_complete).catch(() => {
|
|
55
|
+
// ignore — printed instructions below cover the fallback
|
|
56
|
+
});
|
|
57
|
+
printAuthInstructions(start);
|
|
58
|
+
const deadline = Date.now() + start.expires_in * 1000;
|
|
59
|
+
const intervalMs = Math.max(start.interval, 3) * 1000;
|
|
60
|
+
while (Date.now() < deadline) {
|
|
61
|
+
await sleep(intervalMs);
|
|
62
|
+
const poll = await pollOnce(pollUrl, start.device_code).catch((e) => {
|
|
63
|
+
// Transient network failures shouldn't abort the flow; the user has
|
|
64
|
+
// expires_in seconds to sort it out. Log to stderr for visibility.
|
|
65
|
+
process.stderr.write(`[maind-mcp-bridge] poll error (will retry): ${String(e)}\n`);
|
|
66
|
+
return null;
|
|
67
|
+
});
|
|
68
|
+
if (!poll)
|
|
69
|
+
continue;
|
|
70
|
+
if (poll.status === "approved") {
|
|
71
|
+
writeApiKey(poll.api_key);
|
|
72
|
+
process.stderr.write(`[maind-mcp-bridge] signed in (plan: ${poll.plan}). API key saved to ~/.config/maind/api-key\n`);
|
|
73
|
+
return { apiKey: poll.api_key, plan: poll.plan };
|
|
74
|
+
}
|
|
75
|
+
if (poll.status === "denied") {
|
|
76
|
+
process.stderr.write("[maind-mcp-bridge] sign-in denied by user\n");
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
if (poll.status === "expired" || poll.status === "consumed") {
|
|
80
|
+
process.stderr.write(`[maind-mcp-bridge] sign-in ${poll.status}\n`);
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
// status: "pending" → keep polling
|
|
84
|
+
}
|
|
85
|
+
process.stderr.write("[maind-mcp-bridge] sign-in timed out\n");
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
async function pollOnce(url, deviceCode) {
|
|
89
|
+
const res = await fetch(url, {
|
|
90
|
+
method: "POST",
|
|
91
|
+
headers: { "content-type": "application/json" },
|
|
92
|
+
body: JSON.stringify({ device_code: deviceCode }),
|
|
93
|
+
});
|
|
94
|
+
if (!res.ok) {
|
|
95
|
+
const txt = await res.text();
|
|
96
|
+
throw new Error(`poll ${res.status}: ${txt}`);
|
|
97
|
+
}
|
|
98
|
+
return (await res.json());
|
|
99
|
+
}
|
|
100
|
+
function sleep(ms) {
|
|
101
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
102
|
+
}
|
|
103
|
+
function printAuthInstructions(start) {
|
|
104
|
+
const lines = [
|
|
105
|
+
"",
|
|
106
|
+
" ┌─────────────────────────────────────────────────────────────────┐",
|
|
107
|
+
" │ │",
|
|
108
|
+
" │ maind-mcp-bridge — first-time setup │",
|
|
109
|
+
" │ │",
|
|
110
|
+
" │ Approve this bridge to bind it to your maind account: │",
|
|
111
|
+
" │ │",
|
|
112
|
+
` │ Open: ${pad(start.verification_uri, 56)} │`,
|
|
113
|
+
` │ Code: ${pad(start.user_code, 56)} │`,
|
|
114
|
+
" │ │",
|
|
115
|
+
` │ (expires in ${Math.round(start.expires_in / 60)} minutes)`.padEnd(67) + "│",
|
|
116
|
+
" │ │",
|
|
117
|
+
" └─────────────────────────────────────────────────────────────────┘",
|
|
118
|
+
"",
|
|
119
|
+
];
|
|
120
|
+
// STDERR — STDOUT is the MCP framing channel
|
|
121
|
+
process.stderr.write(lines.join("\n") + "\n");
|
|
122
|
+
}
|
|
123
|
+
function pad(s, width) {
|
|
124
|
+
if (s.length >= width)
|
|
125
|
+
return s.slice(0, width);
|
|
126
|
+
return s + " ".repeat(width - s.length);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Spawns a platform-appropriate command to open the given URL in the user's
|
|
130
|
+
* default browser. Detached so it doesn't keep the bridge process alive.
|
|
131
|
+
* Errors are swallowed — the printed verification_uri + user_code in
|
|
132
|
+
* printAuthInstructions() is the fallback path.
|
|
133
|
+
*/
|
|
134
|
+
async function openExternalBrowser(url) {
|
|
135
|
+
let cmd;
|
|
136
|
+
let args;
|
|
137
|
+
switch (platform()) {
|
|
138
|
+
case "darwin":
|
|
139
|
+
cmd = "open";
|
|
140
|
+
args = [url];
|
|
141
|
+
break;
|
|
142
|
+
case "win32":
|
|
143
|
+
cmd = "cmd";
|
|
144
|
+
args = ["/c", "start", "", url];
|
|
145
|
+
break;
|
|
146
|
+
default:
|
|
147
|
+
cmd = "xdg-open";
|
|
148
|
+
args = [url];
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
return new Promise((resolve, reject) => {
|
|
152
|
+
try {
|
|
153
|
+
const child = spawn(cmd, args, {
|
|
154
|
+
stdio: "ignore",
|
|
155
|
+
detached: true,
|
|
156
|
+
});
|
|
157
|
+
child.on("error", reject);
|
|
158
|
+
child.unref();
|
|
159
|
+
// Resolve immediately — we don't wait for the browser process to finish.
|
|
160
|
+
resolve();
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
reject(err);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Forces a re-authorization after the server reports the api_key was revoked.
|
|
169
|
+
* The device-id is preserved — the server will recognize the re-pair on its
|
|
170
|
+
* side and atomically revoke the old key + bind the new one (see ADR-103
|
|
171
|
+
* `upsert_device_on_pair`).
|
|
172
|
+
*/
|
|
173
|
+
export async function reauthorize(version) {
|
|
174
|
+
clearApiKey();
|
|
175
|
+
// Make sure the device-id is materialised even if it wasn't before.
|
|
176
|
+
ensureDeviceId();
|
|
177
|
+
return runDeviceFlow(version);
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,EAAE;AACF,wEAAwE;AACxE,oFAAoF;AACpF,8EAA8E;AAC9E,uEAAuE;AACvE,sBAAsB;AACtB,EAAE;AACF,kFAAkF;AAClF,0EAA0E;AAC1E,2EAA2E;AAE3E,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAqBtF;;;;GAIG;AACH,MAAM,wBAAwB,GAAG,uDAAuD,CAAC;AAEzF,SAAS,eAAe;IACtB,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;IAC7C,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,wBAAwB,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAAe;IACjD,MAAM,MAAM,GAAG,eAAe,EAAE,CAAC;IACjC,MAAM,QAAQ,GA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OAAe;IAC/C,WAAW,EAAE,CAAC;IACd,oEAAoE;IACpE,cAAc,EAAE,CAAC;IACjB,OAAO,aAAa,CAAC,OAAO,CAAC,CAAC;AAChC,CAAC"}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Stable device identifier persisted on disk. Generated once on first run and
|
|
2
|
+
// reused for every subsequent invocation of the bridge. Survives bridge
|
|
3
|
+
// upgrades and `npx` cache invalidations because it's stored OUTSIDE the
|
|
4
|
+
// package directory (in the user's config dir).
|
|
5
|
+
//
|
|
6
|
+
// Same role as `ensureDeviceId()` in apps/vscode-extension/src/util/platform.ts —
|
|
7
|
+
// the server side relies on this UUID to dedupe (user_id, device_id) and
|
|
8
|
+
// revoke the previously-bound api_key on re-pair (see migration
|
|
9
|
+
// 20260518000012_devices_aggregate_table.sql).
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
|
11
|
+
import { homedir, hostname, platform, release } from "node:os";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
/**
|
|
15
|
+
* Returns the XDG-style config directory for maind on this platform.
|
|
16
|
+
*
|
|
17
|
+
* - macOS: `~/Library/Application Support/maind`
|
|
18
|
+
* - Linux/BSD: `$XDG_CONFIG_HOME/maind` (default `~/.config/maind`)
|
|
19
|
+
* - Windows: `%APPDATA%/maind` (defaults to `~/AppData/Roaming/maind`)
|
|
20
|
+
*
|
|
21
|
+
* The directory is created on first access with 0700 permissions — the
|
|
22
|
+
* api-key file is stored alongside the device-id and must not be world-readable.
|
|
23
|
+
*/
|
|
24
|
+
export function configDir() {
|
|
25
|
+
const home = homedir();
|
|
26
|
+
const env = process.env;
|
|
27
|
+
if (platform() === "darwin") {
|
|
28
|
+
return join(home, "Library", "Application Support", "maind");
|
|
29
|
+
}
|
|
30
|
+
if (platform() === "win32") {
|
|
31
|
+
const appdata = env.APPDATA && env.APPDATA.length > 0
|
|
32
|
+
? env.APPDATA
|
|
33
|
+
: join(home, "AppData", "Roaming");
|
|
34
|
+
return join(appdata, "maind");
|
|
35
|
+
}
|
|
36
|
+
const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0
|
|
37
|
+
? env.XDG_CONFIG_HOME
|
|
38
|
+
: join(home, ".config");
|
|
39
|
+
return join(xdg, "maind");
|
|
40
|
+
}
|
|
41
|
+
function ensureDir(path) {
|
|
42
|
+
if (existsSync(path))
|
|
43
|
+
return;
|
|
44
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
45
|
+
}
|
|
46
|
+
const DEVICE_ID_FILE = "device-id";
|
|
47
|
+
const API_KEY_FILE = "api-key";
|
|
48
|
+
/**
|
|
49
|
+
* Reads the persisted device-id, generating one on first call. The value is a
|
|
50
|
+
* v4 UUID so it can be sent verbatim to /device-authorization-start as
|
|
51
|
+
* `client_meta.device_id` (same shape the VS Code extension uses).
|
|
52
|
+
*
|
|
53
|
+
* The file is plain text — no encryption needed. Knowledge of the device_id
|
|
54
|
+
* alone does not authorize anything; it's an opaque dedup key, not a credential.
|
|
55
|
+
*/
|
|
56
|
+
export function ensureDeviceId() {
|
|
57
|
+
const dir = configDir();
|
|
58
|
+
ensureDir(dir);
|
|
59
|
+
const file = join(dir, DEVICE_ID_FILE);
|
|
60
|
+
if (existsSync(file)) {
|
|
61
|
+
const stored = readFileSync(file, "utf8").trim();
|
|
62
|
+
if (isUuid(stored))
|
|
63
|
+
return stored;
|
|
64
|
+
// File corrupt or written by a different version — regenerate. Better to
|
|
65
|
+
// bind a new device than crash; the user can /devices/unpair the orphan.
|
|
66
|
+
}
|
|
67
|
+
const id = randomUUID();
|
|
68
|
+
writeFileSync(file, id + "\n", { encoding: "utf8", mode: 0o600 });
|
|
69
|
+
try {
|
|
70
|
+
chmodSync(file, 0o600);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// best-effort; some filesystems (FAT, exFAT on USB sticks) ignore chmod
|
|
74
|
+
}
|
|
75
|
+
return id;
|
|
76
|
+
}
|
|
77
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
78
|
+
function isUuid(s) {
|
|
79
|
+
return UUID_RE.test(s);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Returns the full path to the api-key file. Used by auth.ts to persist the
|
|
83
|
+
* key returned by the device-authorization flow.
|
|
84
|
+
*/
|
|
85
|
+
export function apiKeyPath() {
|
|
86
|
+
return join(configDir(), API_KEY_FILE);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Persists the api-key with 0600 permissions in the same directory as the
|
|
90
|
+
* device-id. Overwrites any existing key (used during re-auth after a server
|
|
91
|
+
* 401 device_revoked response).
|
|
92
|
+
*/
|
|
93
|
+
export function writeApiKey(key) {
|
|
94
|
+
const dir = configDir();
|
|
95
|
+
ensureDir(dir);
|
|
96
|
+
const file = apiKeyPath();
|
|
97
|
+
writeFileSync(file, key + "\n", { encoding: "utf8", mode: 0o600 });
|
|
98
|
+
try {
|
|
99
|
+
chmodSync(file, 0o600);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// ignore — see comment in ensureDeviceId()
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Reads the persisted api-key, returns null if not yet authorized. Trimmed
|
|
107
|
+
* because writeApiKey appends a newline.
|
|
108
|
+
*/
|
|
109
|
+
export function readApiKey() {
|
|
110
|
+
const file = apiKeyPath();
|
|
111
|
+
if (!existsSync(file))
|
|
112
|
+
return null;
|
|
113
|
+
const raw = readFileSync(file, "utf8").trim();
|
|
114
|
+
return raw.length > 0 ? raw : null;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Removes the api-key (but keeps the device-id). Called after a server-side
|
|
118
|
+
* revoke so the next invocation triggers a fresh device-flow with the same
|
|
119
|
+
* device-id, which the server will recognize as a re-pair and atomically
|
|
120
|
+
* revoke the old key + bind the new one via upsert_device_on_pair.
|
|
121
|
+
*/
|
|
122
|
+
export function clearApiKey() {
|
|
123
|
+
const file = apiKeyPath();
|
|
124
|
+
if (!existsSync(file))
|
|
125
|
+
return;
|
|
126
|
+
writeFileSync(file, "", { encoding: "utf8", mode: 0o600 });
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Best-effort identifier sent in `client_meta.label` so the user can identify
|
|
130
|
+
* the binding in the dashboard `/devices` list. Falls back to a static string
|
|
131
|
+
* if hostname lookup fails.
|
|
132
|
+
*/
|
|
133
|
+
export function bridgeLabel() {
|
|
134
|
+
try {
|
|
135
|
+
return `mcp-bridge-${hostname()}`;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return "mcp-bridge";
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export function clientMeta(version) {
|
|
142
|
+
return {
|
|
143
|
+
os: `${platform()} ${release()}`,
|
|
144
|
+
ide: "mcp-bridge",
|
|
145
|
+
ext_version: version,
|
|
146
|
+
device_id: ensureDeviceId(),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=device-id.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"device-id.js","sourceRoot":"","sources":["../src/device-id.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,wEAAwE;AACxE,yEAAyE;AACzE,gDAAgD;AAChD,EAAE;AACF,kFAAkF;AAClF,yEAAyE;AACzE,gEAAgE;AAChE,+CAA+C;AAE/C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,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,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACP,2CAA2C;IAC7C,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU;IACxB,MAAM,IAAI,GAAG,UAAU,EAAE,CAAC;IAC1B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACnC,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IAC9C,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AACrC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,IAAI,GAAG,UAAU,EAAE,CAAC;IAC1B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO;IAC9B,aAAa,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW;IACzB,IAAI,CAAC;QACH,OAAO,cAAc,QAAQ,EAAE,EAAE,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,YAAY,CAAC;IACtB,CAAC;AACH,CAAC;AAaD,MAAM,UAAU,UAAU,CAAC,OAAe;IACxC,OAAO;QACL,EAAE,EAAE,GAAG,QAAQ,EAAE,IAAI,OAAO,EAAE,EAAE;QAChC,GAAG,EAAE,YAAY;QACjB,WAAW,EAAE,OAAO;QACpB,SAAS,EAAE,cAAc,EAAE;KAC5B,CAAC;AACJ,CAAC"}
|
package/build/forward.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// JSON-RPC forwarding between a local stdio MCP client (Claude Code, Cursor,
|
|
2
|
+
// Windsurf) and the remote maind Streamable-HTTP MCP server. The bridge stays
|
|
3
|
+
// intentionally thin: it does not parse, validate, or alter the JSON-RPC
|
|
4
|
+
// payloads. It only adds Bearer-auth + device-binding headers and demuxes
|
|
5
|
+
// SSE streams back to stdout line-by-line.
|
|
6
|
+
//
|
|
7
|
+
// Two channels per session:
|
|
8
|
+
// - stdin (line-delimited JSON-RPC frames from the local client)
|
|
9
|
+
// - stdout (line-delimited JSON-RPC frames going back to the client)
|
|
10
|
+
//
|
|
11
|
+
// The remote endpoint uses Streamable HTTP — each forwarded POST may return
|
|
12
|
+
// either a single JSON body or an SSE stream (text/event-stream). Both are
|
|
13
|
+
// unpacked to JSON-RPC frames on stdout.
|
|
14
|
+
import { createInterface } from "node:readline";
|
|
15
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
16
|
+
/**
|
|
17
|
+
* Default Streamable-HTTP MCP endpoint for the production maind server.
|
|
18
|
+
* Override via env `MAIND_MCP_URL` for self-hosted/preview environments.
|
|
19
|
+
*/
|
|
20
|
+
const DEFAULT_MCP_URL = "https://mcp.maind.dev/mcp";
|
|
21
|
+
export class BridgeReauthNeeded extends Error {
|
|
22
|
+
reason;
|
|
23
|
+
constructor(reason) {
|
|
24
|
+
super(`re-authorization required: ${reason}`);
|
|
25
|
+
this.reason = reason;
|
|
26
|
+
this.name = "BridgeReauthNeeded";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Long-lived forwarder. One instance per bridge process. Tracks the
|
|
31
|
+
* Mcp-Session-Id header returned by the server's initialize response so
|
|
32
|
+
* subsequent calls land in the same MCP session.
|
|
33
|
+
*/
|
|
34
|
+
export class Forwarder {
|
|
35
|
+
mcpUrl;
|
|
36
|
+
apiKey;
|
|
37
|
+
deviceId;
|
|
38
|
+
bridgeVersion;
|
|
39
|
+
/** Set by the first response that carries an Mcp-Session-Id header. */
|
|
40
|
+
sessionId = null;
|
|
41
|
+
/** Set true once an unrecoverable auth condition is detected. */
|
|
42
|
+
terminated = false;
|
|
43
|
+
constructor(cfg) {
|
|
44
|
+
this.apiKey = cfg.apiKey;
|
|
45
|
+
this.deviceId = cfg.deviceId;
|
|
46
|
+
this.bridgeVersion = cfg.bridgeVersion;
|
|
47
|
+
this.mcpUrl =
|
|
48
|
+
cfg.mcpUrl ??
|
|
49
|
+
process.env.MAIND_MCP_URL ??
|
|
50
|
+
DEFAULT_MCP_URL;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Read line-delimited JSON-RPC from stdin and forward each frame to the
|
|
54
|
+
* remote server. Returns when stdin is closed. Throws `BridgeReauthNeeded`
|
|
55
|
+
* if the server reports device_mismatch / device_revoked, so the caller can
|
|
56
|
+
* re-run the device flow and retry.
|
|
57
|
+
*/
|
|
58
|
+
async run() {
|
|
59
|
+
const rl = createInterface({
|
|
60
|
+
input: process.stdin,
|
|
61
|
+
crlfDelay: Infinity,
|
|
62
|
+
});
|
|
63
|
+
// Process frames sequentially. MCP allows concurrency, but doing this
|
|
64
|
+
// serially keeps the bridge simple and avoids out-of-order session-id
|
|
65
|
+
// capture on the initialize response. Latency cost is negligible — most
|
|
66
|
+
// tool-calls take >100ms server-side, far above the serialization overhead.
|
|
67
|
+
for await (const line of rl) {
|
|
68
|
+
if (this.terminated)
|
|
69
|
+
return;
|
|
70
|
+
const trimmed = line.trim();
|
|
71
|
+
if (trimmed.length === 0)
|
|
72
|
+
continue;
|
|
73
|
+
await this.forwardFrame(trimmed);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async forwardFrame(frame) {
|
|
77
|
+
const headers = {
|
|
78
|
+
"content-type": "application/json",
|
|
79
|
+
// Streamable HTTP allows either a one-shot JSON body or an SSE stream
|
|
80
|
+
// back. Advertising both lets the server pick.
|
|
81
|
+
"accept": "application/json, text/event-stream",
|
|
82
|
+
"authorization": `Bearer ${this.apiKey}`,
|
|
83
|
+
"x-maind-device-id": this.deviceId,
|
|
84
|
+
"x-maind-bridge-version": this.bridgeVersion,
|
|
85
|
+
};
|
|
86
|
+
if (this.sessionId !== null) {
|
|
87
|
+
headers["mcp-session-id"] = this.sessionId;
|
|
88
|
+
}
|
|
89
|
+
let response;
|
|
90
|
+
try {
|
|
91
|
+
response = await fetch(this.mcpUrl, {
|
|
92
|
+
method: "POST",
|
|
93
|
+
headers,
|
|
94
|
+
body: frame,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
// Network error — surface a JSON-RPC error on stdout so the local
|
|
99
|
+
// client doesn't hang. id may be missing if we can't parse the frame;
|
|
100
|
+
// best-effort.
|
|
101
|
+
const id = tryExtractId(frame);
|
|
102
|
+
emitJsonRpcError(id, -32603, `bridge network error: ${stringifyErr(err)}`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
// Capture session id once on the initialize response. Subsequent responses
|
|
106
|
+
// generally omit it (server expects the client to send it back), but if it
|
|
107
|
+
// changes we honor the latest.
|
|
108
|
+
const sid = response.headers.get("mcp-session-id");
|
|
109
|
+
if (sid && sid !== this.sessionId) {
|
|
110
|
+
this.sessionId = sid;
|
|
111
|
+
}
|
|
112
|
+
if (response.status === 401) {
|
|
113
|
+
await this.handle401(response, frame);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (!response.ok) {
|
|
117
|
+
const id = tryExtractId(frame);
|
|
118
|
+
const body = await response.text().catch(() => "");
|
|
119
|
+
emitJsonRpcError(id, -32603, `bridge upstream error (HTTP ${response.status}): ${body.slice(0, 500)}`);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
123
|
+
if (contentType.startsWith("text/event-stream")) {
|
|
124
|
+
await pipeSseToStdout(response);
|
|
125
|
+
}
|
|
126
|
+
else if (response.status === 202) {
|
|
127
|
+
// Accepted — server acknowledged a notification, no body to emit.
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
const text = await response.text();
|
|
132
|
+
if (text.trim().length > 0) {
|
|
133
|
+
process.stdout.write(text + "\n");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* 401 path. We inspect the body for the maind-specific hint to decide if a
|
|
139
|
+
* re-auth would help (device_mismatch / device_revoked / device_required)
|
|
140
|
+
* vs. a flat invalid-key (then re-auth would also help — clear the cached
|
|
141
|
+
* key and start fresh).
|
|
142
|
+
*/
|
|
143
|
+
async handle401(response, frame) {
|
|
144
|
+
const body = await response.text().catch(() => "");
|
|
145
|
+
const lower = body.toLowerCase();
|
|
146
|
+
const recoverable = lower.includes("device_mismatch") ||
|
|
147
|
+
lower.includes("device_revoked") ||
|
|
148
|
+
lower.includes("device_required") ||
|
|
149
|
+
lower.includes("invalid or revoked");
|
|
150
|
+
if (recoverable) {
|
|
151
|
+
this.terminated = true;
|
|
152
|
+
throw new BridgeReauthNeeded(extractHint(lower));
|
|
153
|
+
}
|
|
154
|
+
const id = tryExtractId(frame);
|
|
155
|
+
emitJsonRpcError(id, -32001, `bridge auth error: ${body.slice(0, 200)}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Streams an SSE response body and emits each `data:` payload as a single
|
|
160
|
+
* line-delimited JSON-RPC frame on stdout. Per the SSE spec, multiple `data:`
|
|
161
|
+
* lines inside one event are joined with `\n` — we collapse and emit only if
|
|
162
|
+
* the resulting payload is non-empty.
|
|
163
|
+
*/
|
|
164
|
+
async function pipeSseToStdout(response) {
|
|
165
|
+
if (!response.body)
|
|
166
|
+
return;
|
|
167
|
+
const reader = response.body.getReader();
|
|
168
|
+
const decoder = new TextDecoder();
|
|
169
|
+
let buffer = "";
|
|
170
|
+
let dataLines = [];
|
|
171
|
+
const flushEvent = () => {
|
|
172
|
+
if (dataLines.length === 0)
|
|
173
|
+
return;
|
|
174
|
+
const payload = dataLines.join("\n").trim();
|
|
175
|
+
dataLines = [];
|
|
176
|
+
if (payload.length > 0) {
|
|
177
|
+
process.stdout.write(payload + "\n");
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
try {
|
|
181
|
+
while (true) {
|
|
182
|
+
const { value, done } = await reader.read();
|
|
183
|
+
if (done)
|
|
184
|
+
break;
|
|
185
|
+
buffer += decoder.decode(value, { stream: true });
|
|
186
|
+
let nlIdx;
|
|
187
|
+
while ((nlIdx = buffer.indexOf("\n")) !== -1) {
|
|
188
|
+
const rawLine = buffer.slice(0, nlIdx);
|
|
189
|
+
buffer = buffer.slice(nlIdx + 1);
|
|
190
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
191
|
+
if (line === "") {
|
|
192
|
+
// Blank line terminates an SSE event.
|
|
193
|
+
flushEvent();
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (line.startsWith(":")) {
|
|
197
|
+
// SSE comment / keep-alive; ignore.
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (line.startsWith("data:")) {
|
|
201
|
+
dataLines.push(line.slice(5).replace(/^\s/, ""));
|
|
202
|
+
}
|
|
203
|
+
// Other SSE fields (event:, id:, retry:) are not used by MCP currently.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
// Flush any trailing event the server didn't terminate with a blank line.
|
|
209
|
+
flushEvent();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
function tryExtractId(frame) {
|
|
213
|
+
try {
|
|
214
|
+
const parsed = JSON.parse(frame);
|
|
215
|
+
return parsed.id ?? null;
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function stringifyErr(err) {
|
|
222
|
+
if (err instanceof Error)
|
|
223
|
+
return err.message;
|
|
224
|
+
return String(err);
|
|
225
|
+
}
|
|
226
|
+
function emitJsonRpcError(id, code, message) {
|
|
227
|
+
const env = {
|
|
228
|
+
jsonrpc: "2.0",
|
|
229
|
+
id,
|
|
230
|
+
error: { code, message },
|
|
231
|
+
};
|
|
232
|
+
process.stdout.write(JSON.stringify(env) + "\n");
|
|
233
|
+
}
|
|
234
|
+
function extractHint(lowerBody) {
|
|
235
|
+
if (lowerBody.includes("device_mismatch"))
|
|
236
|
+
return "device_mismatch";
|
|
237
|
+
if (lowerBody.includes("device_revoked"))
|
|
238
|
+
return "device_revoked";
|
|
239
|
+
if (lowerBody.includes("device_required"))
|
|
240
|
+
return "device_required";
|
|
241
|
+
return "auth_failed";
|
|
242
|
+
}
|
|
243
|
+
// Re-export delay so callers can wait between retries without pulling in
|
|
244
|
+
// node:timers/promises themselves. Kept here because the forwarder is the
|
|
245
|
+
// only consumer.
|
|
246
|
+
export { delay };
|
|
247
|
+
//# sourceMappingURL=forward.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"forward.js","sourceRoot":"","sources":["../src/forward.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,yEAAyE;AACzE,0EAA0E;AAC1E,2CAA2C;AAC3C,EAAE;AACF,4BAA4B;AAC5B,mEAAmE;AACnE,uEAAuE;AACvE,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,yCAAyC;AAEzC,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAG3D;;;GAGG;AACH,MAAM,eAAe,GAAG,2BAA2B,CAAC;AAEpD,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IACf;IAA5B,YAA4B,MAAc;QACxC,KAAK,CAAC,8BAA8B,MAAM,EAAE,CAAC,CAAC;QADpB,WAAM,GAAN,MAAM,CAAQ;QAExC,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAUD;;;;GAIG;AACH,MAAM,OAAO,SAAS;IACH,MAAM,CAAS;IACf,MAAM,CAAS;IACf,QAAQ,CAAS;IACjB,aAAa,CAA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BAAgB,CACvB,EAA0B,EAC1B,IAAY,EACZ,OAAe;IAEf,MAAM,GAAG,GAAG;QACV,OAAO,EAAE,KAAK;QACd,EAAE;QACF,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;KACzB,CAAC;IACF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;AACnD,CAAC;AAED,SAAS,WAAW,CAAC,SAAiB;IACpC,IAAI,SAAS,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QAAE,OAAO,iBAAiB,CAAC;IACpE,IAAI,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC;QAAE,OAAO,gBAAgB,CAAC;IAClE,IAAI,SAAS,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QAAE,OAAO,iBAAiB,CAAC;IACpE,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,yEAAyE;AACzE,0EAA0E;AAC1E,iBAAiB;AACjB,OAAO,EAAE,KAAK,EAAE,CAAC"}
|
package/build/index.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
//
|
|
3
|
+
// @maind-dev/mcp-bridge — entry point.
|
|
4
|
+
//
|
|
5
|
+
// Lifecycle:
|
|
6
|
+
// 1. Resolve cached api-key from ~/.config/maind/api-key. If absent, run
|
|
7
|
+
// the device-authorization flow (browser-open + user-code) to obtain one.
|
|
8
|
+
// 2. Forward stdin↔HTTP between the local MCP client and mcp.maind.dev, adding
|
|
9
|
+
// Authorization + X-Maind-Device-Id headers on every POST.
|
|
10
|
+
// 3. On a 401 device_mismatch / device_revoked, clear the cached api-key, run
|
|
11
|
+
// the device flow again, and resume forwarding once. A second failure exits
|
|
12
|
+
// non-zero so the MCP client surfaces it instead of silently looping.
|
|
13
|
+
//
|
|
14
|
+
// STDOUT is reserved for the MCP JSON-RPC framing. Every log message goes to
|
|
15
|
+
// STDERR. Anything that leaks to STDOUT will corrupt the stream and crash the
|
|
16
|
+
// upstream client (Claude Code, Cursor, etc.) with an opaque parser error.
|
|
17
|
+
import { BridgeReauthNeeded, Forwarder } from "./forward.js";
|
|
18
|
+
import { clearApiKey, ensureDeviceId, readApiKey, } from "./device-id.js";
|
|
19
|
+
import { runDeviceFlow } from "./auth.js";
|
|
20
|
+
import { BRIDGE_VERSION } from "./version.js";
|
|
21
|
+
const MAX_REAUTH_ATTEMPTS = 1;
|
|
22
|
+
async function ensureApiKey() {
|
|
23
|
+
const cached = readApiKey();
|
|
24
|
+
if (cached !== null)
|
|
25
|
+
return cached;
|
|
26
|
+
const result = await runDeviceFlow(BRIDGE_VERSION);
|
|
27
|
+
if (result === null) {
|
|
28
|
+
process.stderr.write("[maind-mcp-bridge] sign-in did not complete; exiting.\n");
|
|
29
|
+
process.exit(1);
|
|
30
|
+
}
|
|
31
|
+
return result.apiKey;
|
|
32
|
+
}
|
|
33
|
+
async function reauth() {
|
|
34
|
+
clearApiKey();
|
|
35
|
+
const result = await runDeviceFlow(BRIDGE_VERSION);
|
|
36
|
+
if (result === null) {
|
|
37
|
+
process.stderr.write("[maind-mcp-bridge] re-authorization failed; exiting.\n");
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
return result.apiKey;
|
|
41
|
+
}
|
|
42
|
+
async function main() {
|
|
43
|
+
if (process.argv.includes("--version") || process.argv.includes("-v")) {
|
|
44
|
+
process.stdout.write(BRIDGE_VERSION + "\n");
|
|
45
|
+
process.exit(0);
|
|
46
|
+
}
|
|
47
|
+
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
48
|
+
printHelp();
|
|
49
|
+
process.exit(0);
|
|
50
|
+
}
|
|
51
|
+
if (process.argv.includes("--reauth")) {
|
|
52
|
+
// Explicit reset: clear the cached key and re-run the device flow. Useful
|
|
53
|
+
// when a user wants to re-pair without unpairing from the dashboard.
|
|
54
|
+
clearApiKey();
|
|
55
|
+
const result = await runDeviceFlow(BRIDGE_VERSION);
|
|
56
|
+
if (result === null)
|
|
57
|
+
process.exit(1);
|
|
58
|
+
process.stderr.write("[maind-mcp-bridge] re-authorization complete.\n");
|
|
59
|
+
process.exit(0);
|
|
60
|
+
}
|
|
61
|
+
const deviceId = ensureDeviceId();
|
|
62
|
+
let apiKey = await ensureApiKey();
|
|
63
|
+
let attempts = 0;
|
|
64
|
+
while (true) {
|
|
65
|
+
const forwarder = new Forwarder({
|
|
66
|
+
apiKey,
|
|
67
|
+
deviceId,
|
|
68
|
+
bridgeVersion: BRIDGE_VERSION,
|
|
69
|
+
});
|
|
70
|
+
try {
|
|
71
|
+
await forwarder.run();
|
|
72
|
+
// stdin closed — local client disconnected. Normal shutdown.
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
if (err instanceof BridgeReauthNeeded && attempts < MAX_REAUTH_ATTEMPTS) {
|
|
77
|
+
attempts += 1;
|
|
78
|
+
process.stderr.write(`[maind-mcp-bridge] server reported ${err.message}; re-authorizing…\n`);
|
|
79
|
+
apiKey = await reauth();
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function printHelp() {
|
|
87
|
+
const help = [
|
|
88
|
+
"",
|
|
89
|
+
"@maind-dev/mcp-bridge — local MCP wrapper that pins your maind API key to this device.",
|
|
90
|
+
"",
|
|
91
|
+
"Usage:",
|
|
92
|
+
" npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)",
|
|
93
|
+
" npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow",
|
|
94
|
+
" npx -y @maind-dev/mcp-bridge --version",
|
|
95
|
+
" npx -y @maind-dev/mcp-bridge --help",
|
|
96
|
+
"",
|
|
97
|
+
"Environment overrides (rarely needed):",
|
|
98
|
+
" MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)",
|
|
99
|
+
" MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth",
|
|
100
|
+
" XDG_CONFIG_HOME Override config-dir parent on Linux/BSD",
|
|
101
|
+
"",
|
|
102
|
+
"Place this in your .mcp.json (or equivalent):",
|
|
103
|
+
"",
|
|
104
|
+
" {",
|
|
105
|
+
' "mcpServers": {',
|
|
106
|
+
' "maind": {',
|
|
107
|
+
' "command": "npx",',
|
|
108
|
+
' "args": ["-y", "@maind-dev/mcp-bridge"]',
|
|
109
|
+
" }",
|
|
110
|
+
" }",
|
|
111
|
+
" }",
|
|
112
|
+
"",
|
|
113
|
+
];
|
|
114
|
+
process.stderr.write(help.join("\n"));
|
|
115
|
+
}
|
|
116
|
+
main().catch((err) => {
|
|
117
|
+
process.stderr.write(`[maind-mcp-bridge] fatal: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
118
|
+
process.exit(1);
|
|
119
|
+
});
|
|
120
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,EAAE;AACF,uCAAuC;AACvC,EAAE;AACF,aAAa;AACb,2EAA2E;AAC3E,+EAA+E;AAC/E,iFAAiF;AACjF,gEAAgE;AAChE,gFAAgF;AAChF,iFAAiF;AACjF,2EAA2E;AAC3E,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,2EAA2E;AAE3E,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EACL,WAAW,EACX,cAAc,EACd,UAAU,GACX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAE9B,KAAK,UAAU,YAAY;IACzB,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;IAC5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ACF,+CAA+C;QAC/C,EAAE;QACF,KAAK;QACL,qBAAqB;QACrB,kBAAkB;QAClB,2BAA2B;QAC3B,iDAAiD;QACjD,SAAS;QACT,OAAO;QACP,KAAK;QACL,EAAE;KACH,CAAC;IACF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACxC,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;IAC5B,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,6BAA6B,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAClF,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
|
package/build/version.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Hard-coded version constant. Bumped by hand on each release. Read separately
|
|
2
|
+
// from package.json because reading JSON at runtime would force a different
|
|
3
|
+
// import shape under Node16 module resolution.
|
|
4
|
+
//
|
|
5
|
+
// Keep in sync with the `version` field in package.json.
|
|
6
|
+
export const BRIDGE_VERSION = "0.1.0";
|
|
7
|
+
//# sourceMappingURL=version.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,+CAA+C;AAC/C,EAAE;AACF,yDAAyD;AACzD,MAAM,CAAC,MAAM,cAAc,GAAG,OAAO,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@maind-dev/mcp-bridge",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Local MCP bridge for maind.dev — wraps any MCP-compatible client (Claude Code, Cursor, Windsurf) and pins your API key to a single device via the maind device authorization flow.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./build/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"maind-mcp-bridge": "./build/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"build",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc",
|
|
16
|
+
"start": "node build/index.js",
|
|
17
|
+
"dev": "node --watch --watch-path=src --import tsx src/index.ts",
|
|
18
|
+
"type-check": "tsc --noEmit",
|
|
19
|
+
"typecheck": "tsc --noEmit"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@modelcontextprotocol/sdk": "^1.0.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/node": "^20.11.0",
|
|
26
|
+
"tsx": "^4.7.0",
|
|
27
|
+
"typescript": "^5.4.0"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=20.0.0"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"mcp",
|
|
34
|
+
"model-context-protocol",
|
|
35
|
+
"maind",
|
|
36
|
+
"bridge",
|
|
37
|
+
"device-binding"
|
|
38
|
+
],
|
|
39
|
+
"license": "MIT",
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
}
|
|
43
|
+
}
|