Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
443 lines (393 loc) · 15.5 KB
/
Copy pathcli.js
File metadata and controls
443 lines (393 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { pathToFileURL } from "node:url";
import stripJsonComments from "strip-json-comments";
const HOME = os.homedir();
function expandHome(input) {
if (input === "~") return HOME;
if (input.startsWith("~/")) return path.resolve(HOME, input.slice(2));
return path.resolve(input);
}
function readPiConfig() {
const dir = process.env.PI_PACKAGE_DIR?.trim();
if (!dir) return undefined;
try {
return JSON.parse(fs.readFileSync(path.join(path.resolve(dir), "package.json"), "utf8")).piConfig;
} catch {
return undefined;
}
}
function getConfigDirName() {
const configDir = readPiConfig()?.configDir;
return typeof configDir === "string" && configDir.trim() ? configDir.trim() : ".pi";
}
function getAgentDir() {
const piConfig = readPiConfig();
const appName = typeof piConfig?.name === "string" && piConfig.name.trim() ? piConfig.name.trim() : "pi";
const configured = process.env[`${appName.toUpperCase()}_CODING_AGENT_DIR`]?.trim();
if (configured) return expandHome(configured);
return path.join(HOME, getConfigDirName(), "agent");
}
const AGENT_DIR = getAgentDir();
const PI_CONFIG_PATH = path.join(AGENT_DIR, "mcp.json");
const GENERIC_GLOBAL_CONFIG_PATH = path.join(HOME, ".config", "mcp", "mcp.json");
const AGENTS_GLOBAL_CONFIG_PATH = path.join(HOME, ".agents", "mcp.json");
const AGENTS_NESTED_GLOBAL_CONFIG_PATH = path.join(HOME, ".agents", "mcp", "mcp.json");
const PROJECT_CONFIG_PATH = path.resolve(process.cwd(), ".mcp.json");
const PROJECT_PI_CONFIG_PATH = path.resolve(process.cwd(), getConfigDirName(), "mcp.json");
const IMPORT_PATHS = {
cursor: [path.join(HOME, ".cursor", "mcp.json")],
"claude-code": [
path.join(HOME, ".claude", "mcp.json"),
path.join(HOME, ".claude.json"),
path.join(HOME, ".claude", "claude_desktop_config.json"),
],
"claude-desktop": [path.join(HOME, "Library", "Application Support", "Claude", "claude_desktop_config.json")],
codex: [
path.join(HOME, ".codex", "config.toml"),
path.join(HOME, ".codex", "config.json"),
],
opencode: [
path.join(HOME, ".config", "opencode", "opencode.json"),
path.resolve(process.cwd(), "opencode.json"),
],
windsurf: [path.join(HOME, ".windsurf", "mcp.json")],
vscode: [path.resolve(process.cwd(), ".vscode", "mcp.json")],
};
function printHelp(log = console.log) {
log("pi-mcp-adapter helper\n");
log("Install the package with:");
log(" pi install npm:pi-mcp-adapter\n");
log("Then optionally run:");
log(" pi-mcp-adapter init Detect host configs and scaffold Pi imports");
log(" pi-mcp-adapter init --dry-run");
log(" pi-mcp-adapter init --discover-host-configs Opt in to host config fallback discovery");
log("");
log("Bearer token storage (servers configured with auth: \"bearer\" and bearerTokenStore: true):");
log(" pi-mcp-adapter token set <server> Store a token read from stdin (masked prompt or pipe; never argv)");
log(" pi-mcp-adapter token status <server> Report whether a stored token matches the configured URL");
log(" pi-mcp-adapter token remove <server> Remove the stored token");
log("");
log("TypeSafe API key storage:");
log(" pi-mcp-adapter key set typesafe Store a key read from stdin (masked prompt or pipe; never argv)");
log(" pi-mcp-adapter key status typesafe Report the effective credential source without revealing it");
log(" pi-mcp-adapter key remove typesafe Remove the stored key");
}
function readJsonFile(filePath) {
return JSON.parse(stripJsonComments(fs.readFileSync(filePath, "utf-8"), { trailingCommas: true }));
}
function loadPiConfig() {
if (!fs.existsSync(PI_CONFIG_PATH)) {
return { mcpServers: {} };
}
const raw = readJsonFile(PI_CONFIG_PATH);
const mcpServers = raw.mcpServers ?? raw["mcp-servers"] ?? {};
if (!mcpServers || typeof mcpServers !== "object" || Array.isArray(mcpServers)) {
throw new Error(`Invalid MCP config at ${PI_CONFIG_PATH}: expected \"mcpServers\" to be an object`);
}
const normalized = { ...raw };
delete normalized["mcp-servers"];
const imports = Array.isArray(raw.imports) ? raw.imports.filter((value) => typeof value === "string") : undefined;
return {
...normalized,
mcpServers,
imports,
};
}
function findAvailableImports() {
const found = [];
for (const [kind, candidates] of Object.entries(IMPORT_PATHS)) {
const existing = candidates.find((candidate) => fs.existsSync(candidate));
if (existing) {
found.push({ kind, path: existing });
}
}
return found;
}
function printDiscovery(log, imports) {
log("Config discovery:\n");
const paths = [
["User-global standard MCP", GENERIC_GLOBAL_CONFIG_PATH],
["User-global .agents MCP", AGENTS_GLOBAL_CONFIG_PATH],
["User-global .agents nested MCP", AGENTS_NESTED_GLOBAL_CONFIG_PATH],
["Pi global override", PI_CONFIG_PATH],
["Project standard MCP", PROJECT_CONFIG_PATH],
["Project Pi override", PROJECT_PI_CONFIG_PATH],
];
for (const [label, filePath] of paths) {
const prefix = fs.existsSync(filePath) ? "✓" : "-";
log(`${prefix} ${label}: ${filePath}`);
}
log("\nCompatibility imports:\n");
if (imports.length === 0) {
log("- No host-specific MCP configs detected");
return;
}
for (const entry of imports) {
log(`✓ ${entry.kind}: ${entry.path}`);
}
}
function writePiConfig(config) {
fs.mkdirSync(path.dirname(PI_CONFIG_PATH), { recursive: true });
fs.writeFileSync(PI_CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`, "utf-8");
}
async function runInit(argv, log = console.log) {
const dryRun = argv.includes("--dry-run");
const discoverHostConfigs = argv.includes("--discover-host-configs");
const foundImports = findAvailableImports();
const existingConfig = loadPiConfig();
const existingImports = new Set(existingConfig.imports ?? []);
const importsToAdd = foundImports
.map((entry) => entry.kind)
.filter((kind) => !existingImports.has(kind));
printDiscovery(log, foundImports);
const discoverySettingChanged = discoverHostConfigs && existingConfig.settings?.hostConfigDiscovery !== "on";
if (importsToAdd.length === 0 && !discoverySettingChanged) {
log("\nNo Pi config changes needed.");
log("Standard MCP configs are discovered automatically, and host-specific imports are already configured or unavailable.");
return 0;
}
const nextConfig = {
...existingConfig,
...(discoverySettingChanged ? { settings: { ...existingConfig.settings, hostConfigDiscovery: "on" } } : {}),
...(importsToAdd.length > 0 ? { imports: [...existingImports, ...importsToAdd] } : {}),
mcpServers: existingConfig.mcpServers ?? {},
};
if (importsToAdd.length > 0) {
log(`\nDetected host configs to import into Pi: ${importsToAdd.join(", ")}`);
}
if (discoverySettingChanged) {
log("Opting in to host-specific fallback discovery (standard and Pi-owned configs still take precedence).");
}
if (dryRun) {
log(`Dry run: would update ${PI_CONFIG_PATH}`);
return 0;
}
writePiConfig(nextConfig);
log(`Updated ${PI_CONFIG_PATH}`);
log("Pi will now keep reading standard MCP configs automatically, while these imports cover host-specific config formats.");
if (discoverySettingChanged) {
log("Host config discovery is explicit and does not write to or execute commands from external host files.");
}
return 0;
}
async function importTokenModules(error) {
try {
const [store, config, utils] = await Promise.all([
import("./dist/mcp-bearer-store.js"),
import("./dist/config.js"),
import("./dist/utils.js"),
]);
return { store, config, utils };
} catch (err) {
error("Unable to load token command modules.");
error(`Import failed: ${err instanceof Error ? err.message : String(err)}`);
return undefined;
}
}
function readSecretFromStdin(stdin, prompt = "Enter bearer token (input hidden): ") {
if (stdin.isTTY) return readSecretMasked(stdin, prompt);
return new Promise((resolve, reject) => {
let data = "";
stdin.setEncoding("utf8");
stdin.on("data", (chunk) => {
data += chunk;
});
stdin.on("end", () => resolve(data.replace(/[\r\n]+$/, "")));
stdin.on("error", reject);
});
}
// Raw-mode masked prompt: the token never echoes to the terminal.
function readSecretMasked(stdin, prompt) {
return new Promise((resolve, reject) => {
process.stderr.write(prompt);
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding("utf8");
let token = "";
const onData = (chunk) => {
for (const char of chunk) {
if (char === "\u0003") {
cleanup();
reject(new Error("Token entry cancelled"));
return;
}
if (char === "\r" || char === "\n") {
cleanup();
resolve(token);
return;
}
if (char === "\u007f" || char === "\b") {
token = token.slice(0, -1);
continue;
}
token += char;
}
};
const cleanup = () => {
stdin.setRawMode(false);
stdin.pause();
stdin.off("data", onData);
process.stderr.write("\n");
};
stdin.on("data", onData);
});
}
async function runToken(argv, log, error, stdin) {
const [action, serverName, ...extra] = argv;
if (!["set", "status", "remove"].includes(action) || !serverName) {
error("Usage: pi-mcp-adapter token <set|status|remove> <server>");
error("`token set` reads the token from stdin only. Never pass the token as an argument.");
return 1;
}
if (extra.length > 0) {
error("Unexpected extra arguments. The token must not be passed on the command line; pipe it on stdin or use the interactive prompt.");
return 1;
}
const modules = await importTokenModules(error);
if (!modules) return 1;
// Argv-derived text is sanitized before terminal output, and the resolved
// URL is never printed: it can embed userinfo or interpolated secrets.
const safeName = modules.utils.sanitizeTerminalText(serverName);
const definition = modules.config.loadMcpConfig(undefined, process.cwd()).mcpServers[serverName];
if (!definition) {
error(`Server "${safeName}" not found in the effective MCP config.`);
return 1;
}
if (definition.auth !== "bearer" || definition.bearerTokenStore !== true) {
error(`Server "${safeName}" is not configured for bearerTokenStore. Set "auth": "bearer" and "bearerTokenStore": true.`);
return 1;
}
// resolveServerUrl embeds the interpolated URL in its exceptions, so catch
// and redact: the URL can carry userinfo or interpolated secrets.
let serverUrl;
try {
serverUrl = modules.utils.resolveServerUrl(definition);
} catch {
error(`Server "${safeName}" has an invalid or unresolvable URL. Fix the server's url in the MCP config and retry.`);
return 1;
}
if (!serverUrl) {
error(`Server "${safeName}" has no URL configured.`);
return 1;
}
if (action === "set") {
const token = await readSecretFromStdin(stdin);
if (!token) {
error("No token provided on stdin.");
return 1;
}
try {
modules.store.saveBearerTokenForUrl(serverName, token, serverUrl);
} catch (err) {
error(modules.utils.sanitizeTerminalText(err instanceof Error ? err.message : String(err)));
return 1;
}
log(`Bearer token stored for "${safeName}" and bound to the configured server URL.`);
if (definition.bearerToken !== undefined || definition.bearerTokenEnv !== undefined) {
log("Note: this server also configures bearerToken or bearerTokenEnv, which take precedence over the stored token.");
}
return 0;
}
if (action === "status") {
const status = modules.store.inspectBearerTokenForUrl(serverName, serverUrl);
if (status.status === "present") {
log(`Bearer token is stored for "${safeName}".`);
return 0;
}
if (status.status === "url-mismatch") {
log(`Bearer token is stored for "${safeName}", but its URL does not match the current server URL. Run \`pi-mcp-adapter token set ${safeName}\` to rebind it.`);
return 1;
}
if (status.status === "unavailable") {
error(status.message);
return 1;
}
log(`No bearer token is stored for "${safeName}".`);
return 1;
}
try {
modules.store.removeBearerToken(serverName);
} catch (err) {
error(modules.utils.sanitizeTerminalText(err instanceof Error ? err.message : String(err)));
return 1;
}
log(`Bearer token removed for "${safeName}".`);
return 0;
}
async function runKey(argv, log, error, stdin) {
const [action, provider, ...extra] = argv;
if (!["set", "status", "remove"].includes(action) || provider !== "typesafe") {
error("Usage: pi-mcp-adapter key <set|status|remove> typesafe");
error("`key set` reads the API key from stdin only. Never pass the key as an argument.");
return 1;
}
if (extra.length > 0) {
error("Unexpected extra arguments. The API key must not be passed on the command line; pipe it on stdin or use the interactive prompt.");
return 1;
}
let store;
try { store = await import("./dist/jev-key-store.js"); }
catch (err) {
error("Unable to load TypeSafe key command module.");
error(`Import failed: ${err instanceof Error ? err.message : String(err)}`);
return 1;
}
if (action === "set") {
const apiKey = await readSecretFromStdin(stdin, "Enter TypeSafe API key (input hidden): ");
if (!apiKey) { error("No API key provided on stdin."); return 1; }
try { store.saveJevApiKey(apiKey); }
catch (err) { error(err instanceof Error ? err.message : "TypeSafe API key could not be stored."); return 1; }
log("TypeSafe API key stored in the OS secure credential store.");
if (Object.hasOwn(process.env, "TYPESAFE_API_KEY")) log("Note: TYPESAFE_API_KEY is present and overrides the stored key.");
return 0;
}
if (action === "status") {
const status = store.resolveJevCredential();
if (status.status === "present") { log(`source=${status.source}`); return 0; }
if (status.status === "unavailable") { error(`unavailable: ${status.message}`); return 1; }
log("missing");
return 1;
}
try { store.removeJevApiKey(); }
catch (err) { error(err instanceof Error ? err.message : "TypeSafe API key could not be removed."); return 1; }
log("TypeSafe API key removed from the OS secure credential store.");
if (Object.hasOwn(process.env, "TYPESAFE_API_KEY")) log("TYPESAFE_API_KEY is still present and overrides the stored key.");
return 0;
}
export async function main(argv = process.argv.slice(2), log = console.log, error = console.error, stdin = process.stdin) {
const [command, ...rest] = argv;
if (!command || command === "help" || command === "--help" || command === "-h") {
printHelp(log);
return 0;
}
if (command === "token") {
return runToken(rest, log, error, stdin);
}
if (command === "key") {
return runKey(rest, log, error, stdin);
}
if (command === "install") {
error("The custom downloader has been retired.");
error("Use `pi install npm:pi-mcp-adapter` instead, then optionally run `pi-mcp-adapter init`.");
return 1;
}
if (command === "init") {
return runInit(rest, log);
}
error(`Unknown command: ${command}`);
printHelp(log);
return 1;
}
const resolvedEntrypoint = process.argv[1] ? fs.realpathSync(process.argv[1]) : undefined;
const isEntrypoint = resolvedEntrypoint && import.meta.url === pathToFileURL(resolvedEntrypoint).href;
if (isEntrypoint) {
main().then((code) => {
process.exitCode = code;
}).catch((err) => {
console.error(`\nHelper failed: ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
});
}