premanmcp 0.5.0 → 0.7.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/bin/connect.js CHANGED
@@ -15,12 +15,14 @@ import { chmodSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "n
15
15
  import os from "node:os";
16
16
  import path from "node:path";
17
17
 
18
+ import { callTool as callPremanTool, printTestSummary } from "./api_tools.js";
18
19
  import {
19
20
  assertOk,
20
21
  authenticateTerminal,
21
22
  backendUrl,
22
23
  buildServerConfig,
23
24
  callBackendJson,
25
+ frontendUrl,
24
26
  hasKeyAvailable,
25
27
  makeArgs,
26
28
  promptSecret,
@@ -49,18 +51,24 @@ const AGENTS = [
49
51
  label: "Cursor",
50
52
  aliases: ["cursor"],
51
53
  dispatch: { credential: "Cursor API key", needsRoutine: false },
54
+ snippetHint: "merge into ~/.cursor/mcp.json",
55
+ restartHint: 'Fully quit and reopen Cursor, then Settings → MCP → toggle "preman" off and on.',
52
56
  },
53
57
  {
54
58
  id: "claude_code",
55
59
  label: "Claude Code",
56
60
  aliases: ["claude", "claude-code", "claude_code", "claudecode"],
57
61
  dispatch: { credential: "Claude Code routine token", needsRoutine: true },
62
+ snippetHint: "run:",
63
+ restartHint: 'Start a new Claude Code session and run `claude mcp list` — "preman" should be listed.',
58
64
  },
59
65
  {
60
66
  id: "codex",
61
67
  label: "Codex",
62
68
  aliases: ["codex", "openai-codex", "openai_codex"],
63
69
  dispatch: null, // No public fire API; stays on the copy-paste path.
70
+ snippetHint: "append to ~/.codex/config.toml",
71
+ restartHint: "Restart Codex so it re-reads its config.toml.",
64
72
  },
65
73
  ];
66
74
 
@@ -125,6 +133,22 @@ export function writeCursorConfig({ serverName, serverConfig, projectInstall })
125
133
  return { path: configPath, how: "wrote" };
126
134
  }
127
135
 
136
+ /** The `claude mcp add` invocation, shared by the writer and the printed fallback. */
137
+ export function claudeMcpAddArgs(serverName, serverConfig, projectInstall) {
138
+ const envArgs = Object.entries(serverConfig.env).flatMap(([k, v]) => ["--env", `${k}=${v}`]);
139
+ return [
140
+ "mcp",
141
+ "add",
142
+ serverName,
143
+ "--scope",
144
+ projectInstall ? "project" : "user",
145
+ ...envArgs,
146
+ "--",
147
+ serverConfig.command,
148
+ ...serverConfig.args,
149
+ ];
150
+ }
151
+
128
152
  /**
129
153
  * Claude Code owns ~/.claude.json, so prefer its own CLI. Fall back to writing
130
154
  * the config directly when `claude` is not installed — a user can connect before
@@ -132,18 +156,7 @@ export function writeCursorConfig({ serverName, serverConfig, projectInstall })
132
156
  */
133
157
  export function writeClaudeConfig({ serverName, serverConfig, projectInstall }) {
134
158
  if (onPath("claude")) {
135
- const envArgs = Object.entries(serverConfig.env).flatMap(([k, v]) => ["--env", `${k}=${v}`]);
136
- const args = [
137
- "mcp",
138
- "add",
139
- serverName,
140
- "--scope",
141
- projectInstall ? "project" : "user",
142
- ...envArgs,
143
- "--",
144
- serverConfig.command,
145
- ...serverConfig.args,
146
- ];
159
+ const args = claudeMcpAddArgs(serverName, serverConfig, projectInstall);
147
160
  try {
148
161
  execFileSync("claude", args, { stdio: "pipe" });
149
162
  return { path: projectInstall ? ".mcp.json" : "Claude Code user config", how: "registered via claude mcp add" };
@@ -233,6 +246,104 @@ const WRITERS = {
233
246
  codex: writeCodexConfig,
234
247
  };
235
248
 
249
+ // ── Copy-paste fallbacks ────────────────────────────────────────────────
250
+
251
+ /** Quote only what a shell would otherwise mangle, so the line stays readable. */
252
+ function shellQuote(value) {
253
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${String(value).replace(/'/g, `'\\''`)}'`;
254
+ }
255
+
256
+ /** What a user would paste by hand to get exactly what the writer would have written. */
257
+ export function renderAgentSnippet(agentId, serverName, serverConfig, { projectInstall = false } = {}) {
258
+ if (agentId === "codex") return renderCodexToml(serverName, serverConfig);
259
+ if (agentId === "claude_code") {
260
+ const args = claudeMcpAddArgs(serverName, serverConfig, projectInstall);
261
+ return `claude ${args.map(shellQuote).join(" ")}\n`;
262
+ }
263
+ return `${JSON.stringify({ mcpServers: { [serverName]: serverConfig } }, null, 2)}\n`;
264
+ }
265
+
266
+ /** Every agent's snippet, for when we could not pick one for the user. */
267
+ export function renderAllAgentSnippets(args, serverName, { projectInstall = false } = {}) {
268
+ // Build config WITHOUT resolved API key to avoid leaking secrets in CI logs.
269
+ // Users must supply --api-key or set PREMAN_API_KEY separately.
270
+ const env = {
271
+ PREMAN_BACKEND: backendUrl(args),
272
+ PREMAN_FRONTEND: frontendUrl(args),
273
+ };
274
+ const serverConfig = { command: "npx", args: ["-y", "premanmcp@latest"], env };
275
+
276
+ return AGENTS.map((agent) => {
277
+ // Adjust hint based on projectInstall, matching verifyWrittenConfig logic
278
+ let hint = agent.snippetHint;
279
+ if (agent.id === "cursor" && projectInstall) {
280
+ hint = "merge into .cursor/mcp.json";
281
+ } else if (agent.id === "claude_code") {
282
+ hint = projectInstall ? "run (with --scope project):" : "run:";
283
+ }
284
+ return `# ${agent.label} — ${hint}\n` + renderAgentSnippet(agent.id, serverName, serverConfig, { projectInstall });
285
+ }).join("\n");
286
+ }
287
+
288
+ // ── Post-write validation ───────────────────────────────────────────────
289
+
290
+ /** The lines belonging to our `[mcp_servers.<name>]` block, or null if absent. */
291
+ function codexBlockLines(text, serverName) {
292
+ const lines = text.split("\n");
293
+ const start = lines.findIndex((line) => line.trim() === `[mcp_servers.${serverName}]`);
294
+ if (start === -1) return null;
295
+ const block = [];
296
+ for (let i = start + 1; i < lines.length; i += 1) {
297
+ const line = lines[i];
298
+ if (/^\[/.test(line) && !line.startsWith(`[mcp_servers.${serverName}.`)) break;
299
+ block.push(line);
300
+ }
301
+ return block;
302
+ }
303
+
304
+ /**
305
+ * Read back what we just wrote, so a silently-failed write is not reported as a
306
+ * success. Proves the entry is on disk (or that Claude Code knows about it) —
307
+ * whether the agent has actually loaded it is only ever proven by a check-in.
308
+ *
309
+ * Never throws: a verification that cannot run must not fail the connect. An
310
+ * unreadable state reports "unknown" and stays quiet, because a wrong warning
311
+ * costs more trust than a missing one.
312
+ */
313
+ export function verifyWrittenConfig(agent, { serverName, written }) {
314
+ try {
315
+ if (agent.id === "codex") {
316
+ const text = written.path && existsSync(written.path) ? readFileSync(written.path, "utf8") : "";
317
+ const block = codexBlockLines(text, serverName);
318
+ if (!block) {
319
+ return { status: "mismatch", detail: `no [mcp_servers.${serverName}] block in ${written.path}` };
320
+ }
321
+ if (!block.some((line) => line.trim() === 'command = "npx"')) {
322
+ return { status: "mismatch", detail: `${written.path} does not launch npx` };
323
+ }
324
+ return { status: "verified" };
325
+ }
326
+
327
+ // Claude Code registered the server itself — ask its CLI what it ended up with.
328
+ if (agent.id === "claude_code" && written.how !== "wrote") {
329
+ const probe = spawnSync("claude", ["mcp", "get", serverName], { stdio: "ignore" });
330
+ if (probe.error) return { status: "unknown", detail: "could not run claude" };
331
+ return probe.status === 0
332
+ ? { status: "verified" }
333
+ : { status: "mismatch", detail: `claude mcp get ${serverName} did not find the server` };
334
+ }
335
+
336
+ const entry = readJsonFile(written.path).mcpServers?.[serverName];
337
+ if (!entry) return { status: "mismatch", detail: `${serverName} is missing from ${written.path}` };
338
+ if (entry.command !== "npx") {
339
+ return { status: "mismatch", detail: `${written.path} does not launch npx` };
340
+ }
341
+ return { status: "verified" };
342
+ } catch (error) {
343
+ return { status: "unknown", detail: error.message };
344
+ }
345
+ }
346
+
236
347
  // ── Pairing ─────────────────────────────────────────────────────────────
237
348
 
238
349
  async function startPairing(args, agent, apiKey) {
@@ -250,7 +361,14 @@ async function startPairing(args, agent, apiKey) {
250
361
  return String(result.pair_code || "");
251
362
  }
252
363
 
253
- async function waitForConnection(args, apiKey, { intervalMs = 3000, timeoutMs = 300000 } = {}) {
364
+ export async function waitForConnection(
365
+ args,
366
+ apiKey,
367
+ {
368
+ intervalMs = Number(process.env.PREMAN_CONNECT_POLL_MS) || 3000,
369
+ timeoutMs = Number(process.env.PREMAN_CONNECT_WAIT_MS) || 300000,
370
+ } = {}
371
+ ) {
254
372
  const deadline = Date.now() + timeoutMs;
255
373
  let interrupted = false;
256
374
  const onInterrupt = () => {
@@ -323,6 +441,135 @@ export function extractRoutineId(value) {
323
441
  return match ? match[0] : raw;
324
442
  }
325
443
 
444
+ // ── Guided first run ────────────────────────────────────────────────────
445
+
446
+ const MANUAL_STEPS =
447
+ " preman endpoints discover # brief for your agent → endpoints.json\n" +
448
+ " preman endpoints setup --file endpoints.json # register runnable requests\n" +
449
+ " preman test <request-id> # generate + run your first scenarios\n";
450
+
451
+ function nextStepsBlock(agent) {
452
+ return (
453
+ "\nNext steps:\n" +
454
+ ` 1. Restart ${agent.label}, then ask it: "run preman_status" to finish linking.\n` +
455
+ " 2. preman endpoints discover # brief for your agent → endpoints.json\n" +
456
+ " 3. preman endpoints setup --file endpoints.json # register runnable requests\n" +
457
+ " 4. preman test <request-id> # generate + run your first scenarios\n"
458
+ );
459
+ }
460
+
461
+ async function confirm(question) {
462
+ const answer = (await promptText(`${question} [Y/n]: `)).toLowerCase();
463
+ return answer === "" || answer.startsWith("y");
464
+ }
465
+
466
+ /**
467
+ * Carry a freshly linked agent to its first passing test.
468
+ *
469
+ * Discovery itself belongs to the coding agent — the backend hands back a brief
470
+ * for it to execute — so this either runs a test against what the account
471
+ * already has, or prints that brief and the two commands that follow it.
472
+ *
473
+ * Never throws: onboarding help must not turn a successful connect into a failure.
474
+ */
475
+ async function guidedFirstRun(args, agent) {
476
+ try {
477
+ const inventory = await callPremanTool(args, "get_endpoints", {
478
+ include_workbench: true,
479
+ limit: 50,
480
+ });
481
+ const runnable = (inventory.workbench_requests || [])[0];
482
+ const registered = (inventory.endpoints || []).length;
483
+
484
+ if (runnable) {
485
+ const label = `${runnable.method || "GET"} ${runnable.url || ""}`.trim();
486
+ if (!(await confirm(`\nRun a first test against ${label}?`))) {
487
+ process.stdout.write(`Whenever you are ready: preman test ${runnable.id}\n`);
488
+ return;
489
+ }
490
+ process.stdout.write("Generating scenarios…\n");
491
+ const result = await callPremanTool(args, "generate_endpoint_tests", {
492
+ target: runnable.id,
493
+ run: true,
494
+ allow_writes: false,
495
+ max_cases: 10,
496
+ });
497
+ printTestSummary(result);
498
+ process.stdout.write(`\nAdd your own: preman test ${runnable.id} --scenario "..."\n`);
499
+ return;
500
+ }
501
+
502
+ if (registered) {
503
+ process.stdout.write(
504
+ `\nYou have ${registered} registered endpoint(s), but none are runnable yet:\n` +
505
+ " preman endpoints setup --ids <id1,id2> # make them runnable\n" +
506
+ " preman test <request-id> # generate + run your first scenarios\n"
507
+ );
508
+ return;
509
+ }
510
+
511
+ if (!(await confirm("\nNo endpoints in PreMan yet. Print the discovery brief for your agent?"))) {
512
+ process.stdout.write(`\nWhen you are ready:\n${MANUAL_STEPS}`);
513
+ return;
514
+ }
515
+
516
+ const brief = await callPremanTool(args, "discover_endpoints_from_codebase", { base_path: "." });
517
+ for (const line of brief.instructions || []) process.stdout.write(`${line}\n`);
518
+ process.stdout.write(
519
+ `\nHand this brief to ${agent.label}, then run:\n` +
520
+ " preman endpoints setup --file endpoints.json\n" +
521
+ " preman test <request-id>\n"
522
+ );
523
+ } catch (error) {
524
+ process.stdout.write(
525
+ `Note: ${error.message}. Run \`preman endpoints list\` when you are ready.\n`
526
+ );
527
+ }
528
+ }
529
+
530
+ // ── Preflight ───────────────────────────────────────────────────────────
531
+
532
+ const MIN_NODE_MAJOR = 18;
533
+
534
+ /**
535
+ * Verify the machine can actually run the config we are about to write.
536
+ * Hard-fails only on a Node that cannot run the server; everything else is a
537
+ * warning — connect must keep working offline and behind odd shells.
538
+ */
539
+ export async function preflight(args) {
540
+ const problems = [];
541
+ const notes = [];
542
+
543
+ const major = Number(process.versions.node.split(".")[0]);
544
+ if (Number.isFinite(major) && major < MIN_NODE_MAJOR) {
545
+ problems.push(
546
+ `Node ${process.versions.node} is too old — the PreMan MCP server needs Node ${MIN_NODE_MAJOR}+.`
547
+ );
548
+ }
549
+
550
+ if (!onPath("npx")) {
551
+ notes.push(
552
+ "npx was not found on PATH; the written config launches PreMan via npx, so make sure your agent's environment has it."
553
+ );
554
+ }
555
+
556
+ try {
557
+ const resp = await fetch(new URL("health", `${backendUrl(args)}/`), {
558
+ signal: AbortSignal.timeout(4000),
559
+ });
560
+ if (!resp.ok) {
561
+ notes.push(`PreMan backend ${backendUrl(args)} answered ${resp.status}; connect will continue but calls may fail.`);
562
+ }
563
+ } catch {
564
+ notes.push(`Could not reach ${backendUrl(args)}; connect will continue but pairing and logins need it.`);
565
+ }
566
+
567
+ for (const note of notes) process.stdout.write(`Note: ${note}\n`);
568
+ if (problems.length) {
569
+ throw new ConnectError(problems.join("\n"), EXIT_USAGE);
570
+ }
571
+ }
572
+
326
573
  // ── Command ─────────────────────────────────────────────────────────────
327
574
 
328
575
  export const CONNECT_HELP = `
@@ -340,6 +587,7 @@ Connect options:
340
587
  --skip-login Write config without interactive terminal auth
341
588
  --no-pair Do not mint a pair code
342
589
  --no-wait Do not wait for the agent to check in
590
+ --no-guide Skip the guided first run after connecting
343
591
  --print Print the config instead of writing it
344
592
  `;
345
593
 
@@ -360,15 +608,28 @@ export async function connectCommand(commandArgs) {
360
608
 
361
609
  if (!agent) {
362
610
  if (!interactive) {
611
+ // Nothing to prompt on, so leave behind everything a CI log needs to
612
+ // finish the setup by hand rather than just the reason it stopped.
613
+ process.stdout.write(
614
+ `preman connect needs a terminal to pick an agent. Copy-paste setup instead:\n\n${renderAllAgentSnippets(args, serverName, { projectInstall })}\n` +
615
+ 'Then restart your agent and ask it: "run preman_status".\n' +
616
+ "Or rerun: preman connect --agent <cursor|claude-code|codex> --api-key pm_live_…\n"
617
+ );
363
618
  throw new ConnectError(
364
619
  "preman connect needs a terminal. In CI pass --agent <cursor|claude-code|codex> " +
365
- "and --api-key pm_live_… (or --print).",
620
+ "and --api-key pm_live_… (or --print), or use one of the snippets above.",
366
621
  EXIT_USAGE
367
622
  );
368
623
  }
369
624
  agent = await promptAgentChoice(detectAgents());
370
625
  }
371
626
 
627
+ if (!printOnly) {
628
+ // Verify the machine can run what we are about to write — before any
629
+ // config edits or logins, so failures leave nothing half-done.
630
+ await preflight(args);
631
+ }
632
+
372
633
  if (printOnly) {
373
634
  const serverConfig = buildServerConfig(args);
374
635
  if (agent.id === "codex") {
@@ -407,14 +668,28 @@ export async function connectCommand(commandArgs) {
407
668
  `Backend: ${serverConfig.env.PREMAN_BACKEND}\n`
408
669
  );
409
670
 
671
+ const verification = verifyWrittenConfig(agent, { serverName, written });
672
+ if (verification.status === "mismatch") {
673
+ // Generate hint that matches the actual install location
674
+ let hint = agent.snippetHint;
675
+ if (agent.id === "cursor" && projectInstall) {
676
+ hint = "merge into .cursor/mcp.json";
677
+ } else if (agent.id === "claude_code") {
678
+ hint = projectInstall ? "run (with --scope project):" : "run:";
679
+ }
680
+ process.stdout.write(
681
+ `\nWarning: could not confirm the ${agent.label} config (${verification.detail}).\n` +
682
+ `Apply it by hand — ${hint}\n\n` +
683
+ renderAgentSnippet(agent.id, serverName, serverConfig, { projectInstall })
684
+ );
685
+ }
686
+
410
687
  // Not gated on TTY: --dispatch-credential is the non-interactive path, and the
411
688
  // prompt inside only runs when there is a terminal to prompt on.
412
689
  await captureDispatchCredential(args, agent, apiKey);
413
690
 
414
691
  if (!pairCode || args.has("--no-wait") || !interactive) {
415
- process.stdout.write(
416
- `\nRestart ${agent.label}, then ask it: "run preman_status" to finish linking.\n`
417
- );
692
+ process.stdout.write(nextStepsBlock(agent));
418
693
  return;
419
694
  }
420
695
 
@@ -422,11 +697,19 @@ export async function connectCommand(commandArgs) {
422
697
  `\nRestart ${agent.label} and ask it: "run preman_status"\n` +
423
698
  "Waiting for your agent to check in… (Ctrl+C to stop waiting)\n"
424
699
  );
425
- const connected = await waitForConnection(args, apiKey);
426
- process.stdout.write(
427
- connected
428
- ? `Connected as ${agent.label}.\n`
429
- : `No check-in yet. Open ${agent.label} and ask it to "run preman_status" — ` +
430
- "it will link on its first PreMan call.\n"
431
- );
700
+
701
+ if (!(await waitForConnection(args, apiKey))) {
702
+ process.stdout.write(
703
+ "No check-in yet. Troubleshooting:\n" +
704
+ ` - ${agent.restartHint}\n` +
705
+ ` - Config written to: ${written.path}\n` +
706
+ ` - Then ask ${agent.label} to "run preman_status" — it links on its first PreMan call.\n`
707
+ );
708
+ return;
709
+ }
710
+
711
+ process.stdout.write(`Connected as ${agent.label}.\n`);
712
+ if (!args.has("--no-guide")) {
713
+ await guidedFirstRun(args, agent);
714
+ }
432
715
  }