@muhkoo/cli 0.15.0-alpha.14 → 0.15.0-alpha.15
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 +23 -1
- package/bin/muhkoo.js +7 -1
- package/package.json +9 -5
- package/src/commands/deploy.js +87 -46
- package/src/commands/kv.js +0 -2
- package/src/commands/login.js +49 -3
- package/src/commands/logout.js +4 -2
- package/src/commands/mcp.js +28 -0
- package/src/commands/promote.js +0 -1
- package/src/commands/provision.js +17 -1
- package/src/commands/vfs.js +100 -89
- package/src/index.js +7 -3
- package/src/lib/auth.js +7 -2
- package/src/lib/bases.js +8 -0
- package/src/lib/ui.js +30 -5
- package/src/lib/vfs.js +46 -44
- package/src/lib/webLogin.js +85 -20
- package/src/mcp/node.js +90 -0
- package/src/mcp/run.js +125 -0
- package/src/mcp/secrets.js +130 -0
- package/src/mcp/server.js +87 -0
- package/src/mcp/tools.js +782 -0
package/src/lib/webLogin.js
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
* 4. the hosted page redirects back to the loopback with ?code&state
|
|
9
9
|
* 5. exchange the code (+ PKCE verifier) at /api/auth/token → a session token
|
|
10
10
|
*
|
|
11
|
-
* The
|
|
12
|
-
*
|
|
13
|
-
* the
|
|
11
|
+
* The sealed master seed comes back from the token exchange, but the key that
|
|
12
|
+
* opens it rides in the URL fragment, which browsers never send to the loopback
|
|
13
|
+
* server. So the callback page posts it back to `/fragment`, and the seed lets
|
|
14
|
+
* `muhkoo login` pair this machine in the same step.
|
|
14
15
|
*
|
|
15
16
|
* The loopback redirect URIs below are registered as first-party on the
|
|
16
17
|
* accelerator (FIRST_PARTY_REDIRECT_URIS), so the constant `muhkoo-cli` app id
|
|
@@ -29,13 +30,29 @@ export const DEFAULT_CLI_APP_ID = "muhkoo-cli";
|
|
|
29
30
|
/** Loopback ports tried in order — each must be registered in FIRST_PARTY_REDIRECT_URIS. */
|
|
30
31
|
const PORTS = [8976, 8977, 8978];
|
|
31
32
|
|
|
33
|
+
/** How long the loopback stays open after the code for the browser's `/fragment` POST. */
|
|
34
|
+
const FRAGMENT_WAIT_MS = 10_000;
|
|
35
|
+
|
|
32
36
|
/** HTML-escape untrusted text before interpolating it into the loopback page. */
|
|
33
37
|
function escapeHtml(s) {
|
|
34
38
|
return String(s).replace(/[&<>"']/g, (c) =>
|
|
35
39
|
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
36
40
|
}
|
|
37
41
|
|
|
38
|
-
|
|
42
|
+
/**
|
|
43
|
+
* The unlock key rides in the URL fragment (`#k=…`), which a browser never sends
|
|
44
|
+
* to us. This script, served from the loopback itself, reads it and POSTs it
|
|
45
|
+
* back, then strips it from the address bar. `state` is our own random value,
|
|
46
|
+
* never request data. Without a `k` the script does nothing.
|
|
47
|
+
*/
|
|
48
|
+
function fragmentScript(state) {
|
|
49
|
+
return `<script>(function(){var m=/[#&]k=([^&]+)/.exec(location.hash);if(!m)return;
|
|
50
|
+
var k=decodeURIComponent(m[1]);
|
|
51
|
+
fetch("/fragment",{method:"POST",body:JSON.stringify({state:${JSON.stringify(state)},k:k})})
|
|
52
|
+
.catch(function(){}).then(function(){history.replaceState(null,"",location.pathname)})})();</script>`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function successPage(message, isError, state) {
|
|
39
56
|
const color = isError ? "#c0392b" : "#0a1929";
|
|
40
57
|
const title = isError ? "Sign-in failed" : "Signed in to the Muhkoo CLI";
|
|
41
58
|
const body = isError ? escapeHtml(message) : "You can close this tab and return to your terminal.";
|
|
@@ -44,7 +61,7 @@ function successPage(message, isError) {
|
|
|
44
61
|
display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
|
|
45
62
|
.card{background:#fff;border-radius:12px;padding:40px 48px;box-shadow:0 6px 24px rgba(10,25,41,.08);text-align:center;max-width:420px}
|
|
46
63
|
h1{font-size:20px;margin:0 0 8px}p{color:#5b6b7b;margin:0}</style></head>
|
|
47
|
-
<body><div class="card"><h1>${title}</h1><p>${body}</p></div
|
|
64
|
+
<body><div class="card"><h1>${title}</h1><p>${body}</p></div>${isError ? "" : fragmentScript(state)}</body></html>`;
|
|
48
65
|
}
|
|
49
66
|
|
|
50
67
|
function listen(port) {
|
|
@@ -68,11 +85,24 @@ async function startLoopback() {
|
|
|
68
85
|
die(`All loopback ports are busy (${PORTS.join(", ")}). Close whatever's using them and retry.`);
|
|
69
86
|
}
|
|
70
87
|
|
|
88
|
+
/** The master seed as base64, or null when the key or envelope is missing or does not open. */
|
|
89
|
+
async function unsealFragment(sealedKeys, fragmentKey) {
|
|
90
|
+
if (!sealedKeys || !fragmentKey) return null;
|
|
91
|
+
try {
|
|
92
|
+
const { unsealSeed, toBase64 } = await import("@muhkoo/connect");
|
|
93
|
+
return toBase64(await unsealSeed(sealedKeys, fragmentKey));
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
71
99
|
/**
|
|
72
|
-
* Run the browser login and resolve `{ token, username, commitment }`.
|
|
100
|
+
* Run the browser login and resolve `{ token, username, commitment, seed }`.
|
|
101
|
+
* `seed` is the master seed (base64) when the browser handed over the unlock
|
|
102
|
+
* key, else null.
|
|
73
103
|
* `baseUrl` is the API base; `appId` is the CLI client id.
|
|
74
104
|
*/
|
|
75
|
-
export async function webLogin({ baseUrl, appId }) {
|
|
105
|
+
export async function webLogin({ baseUrl, appId, fragmentWaitMs = FRAGMENT_WAIT_MS }) {
|
|
76
106
|
const { srv, port } = await startLoopback();
|
|
77
107
|
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
78
108
|
const { verifier, challenge } = generatePkce();
|
|
@@ -85,6 +115,10 @@ export async function webLogin({ baseUrl, appId }) {
|
|
|
85
115
|
code_challenge_method: "S256",
|
|
86
116
|
}).toString();
|
|
87
117
|
|
|
118
|
+
let fragmentKey = null;
|
|
119
|
+
let gotFragment;
|
|
120
|
+
const fragmentPromise = new Promise((r) => (gotFragment = r));
|
|
121
|
+
|
|
88
122
|
const codePromise = new Promise((resolve, reject) => {
|
|
89
123
|
const timer = setTimeout(
|
|
90
124
|
() => reject(new Error("Timed out waiting for browser sign-in (5 min).")),
|
|
@@ -92,6 +126,26 @@ export async function webLogin({ baseUrl, appId }) {
|
|
|
92
126
|
);
|
|
93
127
|
srv.on("request", (req, res) => {
|
|
94
128
|
const u = new URL(req.url, redirectUri);
|
|
129
|
+
if (u.pathname === "/fragment" && req.method === "POST") {
|
|
130
|
+
let raw = "";
|
|
131
|
+
req.on("data", (d) => {
|
|
132
|
+
if (raw.length < 4096) raw += d;
|
|
133
|
+
});
|
|
134
|
+
req.on("end", () => {
|
|
135
|
+
let b = null;
|
|
136
|
+
try { b = JSON.parse(raw); } catch {}
|
|
137
|
+
if (!b || b.state !== state || typeof b.k !== "string" || !b.k) {
|
|
138
|
+
res.writeHead(400);
|
|
139
|
+
res.end("Bad request");
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
fragmentKey = b.k;
|
|
143
|
+
gotFragment();
|
|
144
|
+
res.writeHead(204);
|
|
145
|
+
res.end();
|
|
146
|
+
});
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
95
149
|
if (u.pathname !== "/callback") {
|
|
96
150
|
res.writeHead(404);
|
|
97
151
|
res.end("Not found");
|
|
@@ -112,6 +166,7 @@ export async function webLogin({ baseUrl, appId }) {
|
|
|
112
166
|
? "State mismatch — please start the login again."
|
|
113
167
|
: "",
|
|
114
168
|
!!failed,
|
|
169
|
+
state,
|
|
115
170
|
),
|
|
116
171
|
);
|
|
117
172
|
clearTimeout(timer);
|
|
@@ -126,21 +181,31 @@ export async function webLogin({ baseUrl, appId }) {
|
|
|
126
181
|
const opened = openBrowser(authUrl);
|
|
127
182
|
info(`${opened ? "If it didn't open, visit:" : "Open this URL to sign in:"}`, ` ${c.cyan(authUrl)}`, "");
|
|
128
183
|
|
|
129
|
-
let code;
|
|
130
184
|
try {
|
|
131
|
-
code = await codePromise;
|
|
185
|
+
const code = await codePromise;
|
|
186
|
+
|
|
187
|
+
// The page's script POSTs the fragment key a moment after the code lands, so
|
|
188
|
+
// the server stays open for it (bounded) while the code is exchanged.
|
|
189
|
+
let waitTimer;
|
|
190
|
+
const fragmentWait = Promise.race([
|
|
191
|
+
fragmentPromise,
|
|
192
|
+
new Promise((r) => (waitTimer = setTimeout(r, fragmentWaitMs))),
|
|
193
|
+
]).finally(() => clearTimeout(waitTimer));
|
|
194
|
+
|
|
195
|
+
step("Exchanging authorization code…");
|
|
196
|
+
const res = await fetch(`${baseUrl}/api/auth/token`, {
|
|
197
|
+
method: "POST",
|
|
198
|
+
headers: { "Content-Type": "application/json" },
|
|
199
|
+
body: JSON.stringify({ code, codeVerifier: verifier, appId }),
|
|
200
|
+
});
|
|
201
|
+
if (!res.ok) die(`Token exchange failed (${res.status}): ${redact(await res.text())}`);
|
|
202
|
+
const body = await res.json().catch(() => null);
|
|
203
|
+
if (!body?.sessionToken) die("No session token returned from the token exchange.");
|
|
204
|
+
|
|
205
|
+
await fragmentWait;
|
|
206
|
+
const seed = await unsealFragment(body.sealedKeys, fragmentKey);
|
|
207
|
+
return { token: body.sessionToken, username: body.username, commitment: body.commitment, seed };
|
|
132
208
|
} finally {
|
|
133
209
|
srv.close();
|
|
134
210
|
}
|
|
135
|
-
|
|
136
|
-
step("Exchanging authorization code…");
|
|
137
|
-
const res = await fetch(`${baseUrl}/api/auth/token`, {
|
|
138
|
-
method: "POST",
|
|
139
|
-
headers: { "Content-Type": "application/json" },
|
|
140
|
-
body: JSON.stringify({ code, codeVerifier: verifier, appId }),
|
|
141
|
-
});
|
|
142
|
-
if (!res.ok) die(`Token exchange failed (${res.status}): ${redact(await res.text())}`);
|
|
143
|
-
const body = await res.json().catch(() => null);
|
|
144
|
-
if (!body?.sessionToken) die("No session token returned from the token exchange.");
|
|
145
|
-
return { token: body.sessionToken, username: body.username, commitment: body.commitment };
|
|
146
211
|
}
|
package/src/mcp/node.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The program the MCP server starts the CLI with.
|
|
3
|
+
*
|
|
4
|
+
* Under plain Node that is the running Node (`process.execPath`). Claude
|
|
5
|
+
* Desktop can instead run the server in its own built-in runtime, where
|
|
6
|
+
* `process.execPath` is the Claude app, and the app cannot be made to act as
|
|
7
|
+
* Node (its RunAsNode fuse is off). There a real `node` has to be found on
|
|
8
|
+
* this computer: PATH first, then the usual install places, then the login
|
|
9
|
+
* shell, which is slow and so asked last.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { accessSync, constants, readdirSync } from "node:fs";
|
|
13
|
+
import { execFileSync } from "node:child_process";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { delimiter, join } from "node:path";
|
|
16
|
+
|
|
17
|
+
const isExecutableFile = (p) => {
|
|
18
|
+
try {
|
|
19
|
+
accessSync(p, constants.X_OK);
|
|
20
|
+
return true;
|
|
21
|
+
} catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const listDirSafe = (d) => {
|
|
27
|
+
try {
|
|
28
|
+
return readdirSync(d);
|
|
29
|
+
} catch {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** `node` as the user's login shell resolves it (nvm, asdf, fnm and the like hook in there). */
|
|
35
|
+
function loginShellNodeDefault() {
|
|
36
|
+
const shell = process.env.SHELL || "/bin/zsh";
|
|
37
|
+
try {
|
|
38
|
+
const out = execFileSync(shell, ["-ilc", "command -v node"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] });
|
|
39
|
+
return out.trim().split("\n").pop() || null;
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const semverDesc = (a, b) => {
|
|
46
|
+
const pa = a.replace(/^v/, "").split(".").map(Number);
|
|
47
|
+
const pb = b.replace(/^v/, "").split(".").map(Number);
|
|
48
|
+
for (let i = 0; i < 3; i++) if ((pb[i] || 0) !== (pa[i] || 0)) return (pb[i] || 0) - (pa[i] || 0);
|
|
49
|
+
return 0;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @returns {string | null} a path to a Node binary, or null when there is none
|
|
54
|
+
*/
|
|
55
|
+
export function findNode({
|
|
56
|
+
versions = process.versions,
|
|
57
|
+
execPath = process.execPath,
|
|
58
|
+
env = process.env,
|
|
59
|
+
home = homedir(),
|
|
60
|
+
isExecutable = isExecutableFile,
|
|
61
|
+
listDir = listDirSafe,
|
|
62
|
+
loginShellNode = loginShellNodeDefault,
|
|
63
|
+
} = {}) {
|
|
64
|
+
if (!versions.electron) return execPath;
|
|
65
|
+
|
|
66
|
+
const candidates = [
|
|
67
|
+
...String(env.PATH ?? "").split(delimiter).filter(Boolean).map((d) => join(d, "node")),
|
|
68
|
+
"/opt/homebrew/bin/node",
|
|
69
|
+
"/usr/local/bin/node",
|
|
70
|
+
join(home, ".volta", "bin", "node"),
|
|
71
|
+
...listDir(join(home, ".nvm", "versions", "node"))
|
|
72
|
+
.sort(semverDesc)
|
|
73
|
+
.map((v) => join(home, ".nvm", "versions", "node", v, "bin", "node")),
|
|
74
|
+
];
|
|
75
|
+
for (const c of candidates) if (c !== execPath && isExecutable(c)) return c;
|
|
76
|
+
|
|
77
|
+
const viaShell = loginShellNode();
|
|
78
|
+
if (viaShell && viaShell !== execPath && isExecutable(viaShell)) return viaShell;
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let cached;
|
|
83
|
+
/** findNode for this process, looked up once. */
|
|
84
|
+
export function nodeForCli() {
|
|
85
|
+
if (cached === undefined) cached = findNode();
|
|
86
|
+
return cached;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const NO_NODE_ERROR =
|
|
90
|
+
'Muhkoo\'s tools need Node.js 20 or newer on this computer, and none was found. Install it from https://nodejs.org, or in Claude go to Settings → Extensions → Advanced settings and turn off "Use built-in Node.js for MCP".';
|
package/src/mcp/run.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run one CLI command for the MCP server and turn what it prints into a result.
|
|
3
|
+
*
|
|
4
|
+
* Commands run in a child process, never in this one: they print as they go
|
|
5
|
+
* and call `process.exit` when they fail, which would take the server down.
|
|
6
|
+
* The child is this package's own `bin/muhkoo.js` under Node (see `node.js`), so the
|
|
7
|
+
* tools always run the CLI they shipped with, not whatever is on PATH.
|
|
8
|
+
*
|
|
9
|
+
* Nothing in the child may wait on a terminal: stdin is closed and
|
|
10
|
+
* MUHKOO_NONINTERACTIVE makes a prompt fail at once (see `ui.js`).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { spawn } from "node:child_process";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
import { nodeForCli, NO_NODE_ERROR } from "./node.js";
|
|
16
|
+
|
|
17
|
+
const DEFAULT_BIN = fileURLToPath(new URL("../../bin/muhkoo.js", import.meta.url));
|
|
18
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
19
|
+
/** The most text a tool hands back; a 50 MB `vfs cat` would swamp the conversation. */
|
|
20
|
+
export const MAX_TEXT_BYTES = 1024 * 1024;
|
|
21
|
+
const STDERR_TAIL = 2048;
|
|
22
|
+
const SIGN_IN = /\b401\b|not signed in|session/i;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {string[]} argv the command, e.g. ["vfs", "ls", "/apps"]; `--json` is appended
|
|
26
|
+
* @param {{ cwd?: string, timeoutMs?: number, bin?: string, onStderr?: (line: string) => void }} [opts]
|
|
27
|
+
* @returns {Promise<{ ok: true, data: unknown } | { ok: false, error: string }>}
|
|
28
|
+
*/
|
|
29
|
+
export function runCli(argv, { cwd, timeoutMs = DEFAULT_TIMEOUT_MS, bin = DEFAULT_BIN, onStderr, node = nodeForCli() } = {}) {
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
if (!node) return resolve({ ok: false, error: NO_NODE_ERROR });
|
|
32
|
+
const child = spawn(node, [bin, ...argv, "--json"], {
|
|
33
|
+
cwd,
|
|
34
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
35
|
+
// Its own process group, so a timeout can kill what it started too
|
|
36
|
+
// (deploy runs `vfs import` as a grandchild).
|
|
37
|
+
detached: true,
|
|
38
|
+
env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0", MUHKOO_NONINTERACTIVE: "1" },
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const out = [];
|
|
42
|
+
let outBytes = 0;
|
|
43
|
+
let err = "";
|
|
44
|
+
let partial = "";
|
|
45
|
+
let timedOut = false;
|
|
46
|
+
|
|
47
|
+
child.stdout.on("data", (chunk) => {
|
|
48
|
+
outBytes += chunk.length;
|
|
49
|
+
// Keep a little past the cap: enough to know it was exceeded.
|
|
50
|
+
if (outBytes - chunk.length <= MAX_TEXT_BYTES) out.push(chunk);
|
|
51
|
+
});
|
|
52
|
+
child.stderr.on("data", (chunk) => {
|
|
53
|
+
const text = chunk.toString("utf8");
|
|
54
|
+
err = (err + text).slice(-STDERR_TAIL * 4);
|
|
55
|
+
if (!onStderr) return;
|
|
56
|
+
const parts = (partial + text).split("\n");
|
|
57
|
+
partial = parts.pop();
|
|
58
|
+
for (const line of parts) if (line.trim()) onStderr(line);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const timer = setTimeout(() => {
|
|
62
|
+
timedOut = true;
|
|
63
|
+
killGroup(child.pid);
|
|
64
|
+
}, timeoutMs);
|
|
65
|
+
|
|
66
|
+
child.on("error", (e) => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
resolve({ ok: false, error: `could not start the muhkoo CLI: ${e.message}` });
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
child.on("close", (code) => {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
if (onStderr && partial.trim()) onStderr(partial);
|
|
74
|
+
if (timedOut) return resolve({ ok: false, error: `timed out after ${timeoutMs / 1000}s` });
|
|
75
|
+
|
|
76
|
+
const stdout = Buffer.concat(out);
|
|
77
|
+
const parsed = parseJson(stdout);
|
|
78
|
+
if (code === 0) {
|
|
79
|
+
if (parsed !== undefined) return resolve({ ok: true, data: parsed });
|
|
80
|
+
// Commands without a JSON result print their answer as progress
|
|
81
|
+
// lines (stderr under --json): that is the answer, not noise.
|
|
82
|
+
if (outBytes === 0) return resolve({ ok: true, data: { text: lastLines(err) } });
|
|
83
|
+
return resolve({ ok: true, data: asText(stdout, outBytes) });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
let message = typeof parsed?.error === "string" ? parsed.error : lastLines(err) || `muhkoo exited with code ${code}`;
|
|
87
|
+
if (SIGN_IN.test(message) && !/login tool/.test(message)) message += " — use the login tool to sign in.";
|
|
88
|
+
resolve({ ok: false, error: message });
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function killGroup(pid) {
|
|
94
|
+
try {
|
|
95
|
+
process.kill(-pid, "SIGKILL");
|
|
96
|
+
} catch {
|
|
97
|
+
try {
|
|
98
|
+
process.kill(pid, "SIGKILL");
|
|
99
|
+
} catch {
|
|
100
|
+
// already gone
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function parseJson(buf) {
|
|
106
|
+
const text = buf.toString("utf8").trim();
|
|
107
|
+
if (!text.startsWith("{") && !text.startsWith("[")) return undefined;
|
|
108
|
+
try {
|
|
109
|
+
return JSON.parse(text);
|
|
110
|
+
} catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function asText(buf, totalBytes) {
|
|
116
|
+
if (buf.includes(0)) return { text: "binary output; use vfs_get to save it to a file" };
|
|
117
|
+
if (totalBytes > MAX_TEXT_BYTES) {
|
|
118
|
+
return { text: `${buf.subarray(0, MAX_TEXT_BYTES).toString("utf8")}\n…[truncated: ${totalBytes} bytes]` };
|
|
119
|
+
}
|
|
120
|
+
return { text: buf.toString("utf8") };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function lastLines(stderr) {
|
|
124
|
+
return stderr.trim().slice(-STDERR_TAIL).replace(/^✗\s*/gm, "").trim();
|
|
125
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep secrets out of tool results.
|
|
3
|
+
*
|
|
4
|
+
* A tool result goes into a conversation and from there to a model, so an sk
|
|
5
|
+
* key, an access token or a session token in one is a leak. Tools that create
|
|
6
|
+
* a secret (apps create, provision, keys rotate, tokens create) save it to an
|
|
7
|
+
* owner-only file, and the result says where, with a masked prefix. pk keys
|
|
8
|
+
* are publishable and are returned: Claude needs them to write client code.
|
|
9
|
+
*
|
|
10
|
+
* `scrub` is the backstop over every result. It masks secret-shaped keys, the
|
|
11
|
+
* credentials this machine holds, and fields named like credentials. It does
|
|
12
|
+
* NOT mask long hex strings in general: commit ids and content hashes are
|
|
13
|
+
* exactly that shape, and the vcs/vfs tools exist to show them.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { mkdir, chmod, readFile, writeFile } from "node:fs/promises";
|
|
19
|
+
|
|
20
|
+
/** Secret key shapes. pk keys are not secrets and are deliberately absent. */
|
|
21
|
+
export const SECRET_PATTERNS = [/mk_[a-z0-9]+_sk_[A-Za-z0-9_-]{6,}/i, /mk_[a-z0-9]+_at_[A-Za-z0-9_-]{6,}/i];
|
|
22
|
+
const SECRET_GLOBAL = SECRET_PATTERNS.map((re) => new RegExp(re.source, "gi"));
|
|
23
|
+
const CREDENTIAL_FIELDS = new Set(["token", "sessionToken", "deviceKey", "seed", "password"]);
|
|
24
|
+
const REDACTED = "[redacted]";
|
|
25
|
+
|
|
26
|
+
const mask = (secret) => `${secret.slice(0, 11)}…`;
|
|
27
|
+
|
|
28
|
+
/** Where secrets go when there is no project record: `~/.muhkoo/secrets` (or $MUHKOO_SECRETS_DIR). */
|
|
29
|
+
export function defaultSecretsDir() {
|
|
30
|
+
return process.env.MUHKOO_SECRETS_DIR || join(homedir(), ".muhkoo", "secrets");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function writePrivate(path, text) {
|
|
34
|
+
await writeFile(path, text, { mode: 0o600 });
|
|
35
|
+
await chmod(path, 0o600); // tighten a file that already existed
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function privateDir(dir) {
|
|
39
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
40
|
+
await chmod(dir, 0o700);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function readRecord(path) {
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const isSecretKey = (k) => k && typeof k === "object" && typeof k.plaintext === "string" && k.type !== "pk";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Save the secrets in a tool's result and return the result without them.
|
|
55
|
+
*
|
|
56
|
+
* @param {string} tool the tool name
|
|
57
|
+
* @param {unknown} data the CLI's parsed result
|
|
58
|
+
* @param {{ projectDir?: string, secretsDir?: string }} [ctx]
|
|
59
|
+
*/
|
|
60
|
+
export async function sealSecrets(tool, data, { projectDir, secretsDir = defaultSecretsDir() } = {}) {
|
|
61
|
+
if (!data || typeof data !== "object") return data;
|
|
62
|
+
|
|
63
|
+
// A new access token: the whole result is the token.
|
|
64
|
+
if (tool === "tokens_create" && typeof data.plaintext === "string") {
|
|
65
|
+
await privateDir(secretsDir);
|
|
66
|
+
const path = join(secretsDir, `token-${safeName(data.keyId ?? "new")}.txt`);
|
|
67
|
+
await writePrivate(path, data.plaintext + "\n");
|
|
68
|
+
const { plaintext, ...rest } = data;
|
|
69
|
+
return { ...rest, masked: mask(plaintext), savedTo: path };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const keys = Array.isArray(data.keys) ? data.keys : null;
|
|
73
|
+
if (!keys || !keys.some(isSecretKey)) return data;
|
|
74
|
+
|
|
75
|
+
const savedTo = await saveKeys(tool, data, keys, { projectDir, secretsDir });
|
|
76
|
+
return {
|
|
77
|
+
...data,
|
|
78
|
+
keys: keys.map((k) => {
|
|
79
|
+
if (!isSecretKey(k)) return k;
|
|
80
|
+
const { plaintext, ...rest } = k;
|
|
81
|
+
return { ...rest, masked: mask(plaintext), savedTo };
|
|
82
|
+
}),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Write the keys somewhere owner-only and return the path. */
|
|
87
|
+
async function saveKeys(tool, data, keys, { projectDir, secretsDir }) {
|
|
88
|
+
// provision has already written them, owner-only, into its record.
|
|
89
|
+
if (tool === "provision" && typeof data.recordPath === "string") return data.recordPath;
|
|
90
|
+
|
|
91
|
+
if (projectDir) {
|
|
92
|
+
const recordPath = join(projectDir, ".muhkoo-app.json");
|
|
93
|
+
const record = await readRecord(recordPath);
|
|
94
|
+
if (record && (!record.appId || !data.appId || record.appId === data.appId)) {
|
|
95
|
+
await writePrivate(recordPath, JSON.stringify({ ...record, keys }, null, 2) + "\n");
|
|
96
|
+
return recordPath;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
await privateDir(secretsDir);
|
|
101
|
+
const path = join(secretsDir, `${safeName(data.appId ?? "app")}-keys.json`);
|
|
102
|
+
await writePrivate(path, JSON.stringify({ appId: data.appId, slug: data.slug, keys }, null, 2) + "\n");
|
|
103
|
+
return path;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const safeName = (s) => String(s).replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Mask every secret left anywhere in `data`.
|
|
110
|
+
*
|
|
111
|
+
* @param {unknown} data
|
|
112
|
+
* @param {{ known?: string[] }} [opts] exact credential values to mask (the stored session token, device key)
|
|
113
|
+
*/
|
|
114
|
+
export function scrub(data, { known = [] } = {}) {
|
|
115
|
+
const exact = known.filter((v) => typeof v === "string" && v.length >= 16);
|
|
116
|
+
const text = (s) => {
|
|
117
|
+
let out = s;
|
|
118
|
+
for (const re of SECRET_GLOBAL) out = out.replace(re, (m) => mask(m));
|
|
119
|
+
for (const v of exact) out = out.split(v).join(REDACTED);
|
|
120
|
+
return out;
|
|
121
|
+
};
|
|
122
|
+
const walk = (v, key) => {
|
|
123
|
+
if (key !== undefined && CREDENTIAL_FIELDS.has(key) && v != null && v !== "") return REDACTED;
|
|
124
|
+
if (typeof v === "string") return text(v);
|
|
125
|
+
if (Array.isArray(v)) return v.map((x) => walk(x));
|
|
126
|
+
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x, k)]));
|
|
127
|
+
return v;
|
|
128
|
+
};
|
|
129
|
+
return walk(data);
|
|
130
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Muhkoo MCP server: every CLI action as a tool Claude can call.
|
|
3
|
+
*
|
|
4
|
+
* Each call runs the CLI underneath (`run.js`), saves any secret the result
|
|
5
|
+
* carries to a private file (`secrets.js`), masks anything secret-shaped that
|
|
6
|
+
* is left, and returns the rest. Which tools exist, and how they are marked,
|
|
7
|
+
* is `tools.js`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFile } from "node:fs/promises";
|
|
11
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
12
|
+
import { TOOLS, flagLikeArgument } from "./tools.js";
|
|
13
|
+
import { runCli } from "./run.js";
|
|
14
|
+
import { sealSecrets, scrub } from "./secrets.js";
|
|
15
|
+
import { loadConfig } from "../lib/config.js";
|
|
16
|
+
import { resolveBaseUrl, platformFor } from "../lib/bases.js";
|
|
17
|
+
|
|
18
|
+
const INSTRUCTIONS = `Muhkoo tools for building and running apps on Muhkoo.
|
|
19
|
+
Start with whoami to see who is signed in and which platform the tools act on; if nobody is, call login.
|
|
20
|
+
deploy publishes a built client to the app's TEST environment and returns its address; promote is the only way to put it into PRODUCTION.
|
|
21
|
+
Secret keys and access tokens are never shown: tools that create them save them to a private file and return its path.
|
|
22
|
+
Local paths must be absolute. Filesystem (vfs_*) paths are absolute paths in the user's Muhkoo filesystem, where projects live under /apps.`;
|
|
23
|
+
|
|
24
|
+
async function version() {
|
|
25
|
+
const pkg = JSON.parse(await readFile(new URL("../../package.json", import.meta.url), "utf8"));
|
|
26
|
+
return pkg.version;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {{ run?: typeof runCli, version?: string }} [opts]
|
|
31
|
+
* @returns {McpServer}
|
|
32
|
+
*/
|
|
33
|
+
export function createServer({ run = runCli, version: v = "0.0.0" } = {}) {
|
|
34
|
+
const server = new McpServer(
|
|
35
|
+
{ name: "muhkoo", title: "Muhkoo", version: v },
|
|
36
|
+
{ capabilities: { logging: {} }, instructions: INSTRUCTIONS },
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
for (const tool of TOOLS) {
|
|
40
|
+
server.registerTool(
|
|
41
|
+
tool.name,
|
|
42
|
+
{ title: tool.title, description: tool.description, inputSchema: tool.input, annotations: tool.annotations },
|
|
43
|
+
async (args) => {
|
|
44
|
+
const flagLike = flagLikeArgument(args);
|
|
45
|
+
if (flagLike) {
|
|
46
|
+
return { isError: true, content: [{ type: "text", text: `${flagLike} can't start with "-"` }] };
|
|
47
|
+
}
|
|
48
|
+
// Login prints the sign-in link while it waits; pass progress on so
|
|
49
|
+
// the developer can open it if the browser didn't.
|
|
50
|
+
const onStderr =
|
|
51
|
+
tool.name === "login"
|
|
52
|
+
? (line) => server.sendLoggingMessage({ level: "info", logger: "muhkoo", data: line }).catch(() => {})
|
|
53
|
+
: undefined;
|
|
54
|
+
|
|
55
|
+
const r = await run(tool.argv(args), {
|
|
56
|
+
cwd: tool.cwd?.(args),
|
|
57
|
+
timeoutMs: tool.timeoutMs ?? 60_000,
|
|
58
|
+
onStderr,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const cfg = await loadConfig();
|
|
62
|
+
const known = [cfg.token, cfg.deviceKey, cfg.seed];
|
|
63
|
+
if (!r.ok) return { isError: true, content: [{ type: "text", text: scrub(r.error, { known }) }] };
|
|
64
|
+
|
|
65
|
+
let data = await sealSecrets(tool.name, r.data, { projectDir: args.projectDir });
|
|
66
|
+
data = scrub(data, { known });
|
|
67
|
+
let result = Array.isArray(data) || data === null || typeof data !== "object" ? { items: data } : data;
|
|
68
|
+
// Every change says where it happened (production or staging).
|
|
69
|
+
if (!tool.annotations.readOnlyHint && result.base === undefined) {
|
|
70
|
+
result = { ...result, base: resolveBaseUrl(cfg.base) };
|
|
71
|
+
}
|
|
72
|
+
// A URL alone doesn't tell a model which one is production.
|
|
73
|
+
if (typeof result.base === "string") result = { ...result, platform: platformFor(result.base) };
|
|
74
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], structuredContent: result };
|
|
75
|
+
},
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return server;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Start the server on stdio (what `muhkoo mcp` does). */
|
|
82
|
+
export async function serveStdio() {
|
|
83
|
+
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
|
84
|
+
const server = createServer({ version: await version() });
|
|
85
|
+
await server.connect(new StdioServerTransport());
|
|
86
|
+
return server;
|
|
87
|
+
}
|