launch-doctor 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/mcp.js CHANGED
@@ -1,24 +1,30 @@
1
- import { existsSync, statSync } from 'node:fs';
2
- import { resolve } from 'node:path';
3
1
  import { createInterface } from 'node:readline';
4
2
  import { shortWhere } from './checks/common.js';
5
- import { DEFAULT_HISTORY_DEPTH } from './history.js';
6
- import { CHECKS, runDoctor } from './index.js';
3
+ import { CoreError, coverageNotes, findFinding, findingDetails, gradeHistory, normalizeRelative, projectRoot, promptNumber, rescan, scan, } from './core.js';
4
+ import { orderedFindings } from './fixes.js';
5
+ import { describeEntry } from './grades.js';
6
+ import { CHECKS } from './index.js';
7
7
  import { runLiveScan } from './live.js';
8
- import { BYTE_LIMIT_NOTE, nestedReposNote } from './report.js';
8
+ import { nestedReposNote } from './report.js';
9
+ import { stripControl } from './sanitize.js';
9
10
  import { plural } from './util.js';
10
11
  import { version } from './version.js';
11
12
  /**
12
13
  * A Model Context Protocol server over stdio, so AI coding tools (Claude Code, Cursor, ...)
13
14
  * can run Launch Doctor themselves. One JSON-RPC 2.0 message per line on stdin and stdout.
14
15
  * Nothing else may be written to stdout: it is the protocol channel.
16
+ *
17
+ * Every tool goes through the shared core (src/core.ts), like the CLI. The server only reads the project: it
18
+ * writes nothing, and it makes no network request except for scan_url, with the address the caller gives.
15
19
  */
16
20
  /** Protocol versions this server speaks, newest first. */
17
21
  export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
18
22
  /** Offered when a client asks for a version this server doesn't know. */
19
23
  const DEFAULT_PROTOCOL = '2025-06-18';
20
- /** Findings and checklist items listed per section in a tool result. */
21
- const MAX_LISTED = 50;
24
+ /** Findings listed in a scan result; the rest are counted. Each entry is one line, so this caps the size. */
25
+ export const MAX_LISTED = 25;
26
+ /** The most text one tool result may hold, so a big app can't flood the model's context. */
27
+ export const MAX_TEXT = 12_000;
22
28
  class RpcError extends Error {
23
29
  code;
24
30
  constructor(code, message) {
@@ -27,6 +33,15 @@ class RpcError extends Error {
27
33
  }
28
34
  }
29
35
  const UNKNOWN_METHOD = Symbol('unknown method');
36
+ const PATH_PROP = {
37
+ type: 'string',
38
+ description: 'Project folder inside the folder the server started in (the default). Paths outside it are refused.',
39
+ };
40
+ const ID_PROP = {
41
+ type: 'string',
42
+ description: 'A finding id from scan_project (8 letters and digits, like "3f9a1c2b"), or its number in that list.',
43
+ };
44
+ const READ_ONLY = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
30
45
  /** The tools this server offers, with JSON Schemas for their arguments. */
31
46
  export function mcpTools() {
32
47
  const categories = CHECKS.map((c) => c.id);
@@ -34,15 +49,12 @@ export function mcpTools() {
34
49
  {
35
50
  name: 'scan_project',
36
51
  title: 'Check a project before launch',
37
- description: 'Runs Launch Doctor on a project folder and grades it A to F on secrets and API keys, database safety, payments, AI and API costs, email delivery, error tracking, legal pages and first impressions. ' +
38
- 'Returns every problem with its file and line, why it matters, and a fix prompt that describes the change to make, plus a checklist of things to verify outside the code. It only reads files.',
52
+ description: 'Runs Launch Doctor on a project folder: Security and Launch readiness grades, counts, and a short list of the problems (critical first), each with an id, the rule, file and line. ' +
53
+ 'Use explain_finding for what a finding means and fix_prompt for the change to make, then rescan. Only reads files, and makes no network requests.',
39
54
  inputSchema: {
40
55
  type: 'object',
41
56
  properties: {
42
- path: {
43
- type: 'string',
44
- description: 'Project folder to check: absolute, or relative to the folder the server started in (the default).',
45
- },
57
+ path: PATH_PROP,
46
58
  only: {
47
59
  type: 'array',
48
60
  items: { type: 'string', enum: categories },
@@ -55,27 +67,72 @@ export function mcpTools() {
55
67
  },
56
68
  offline: {
57
69
  type: 'boolean',
58
- description: 'Skip the email DNS lookups (SPF, DKIM, DMARC). Default false.',
70
+ description: 'Accepted for compatibility: the server never makes network requests for a project scan.',
59
71
  },
60
- domain: { type: 'string', description: "Domain the app sends email from, if the code doesn't show it." },
61
72
  history: {
62
73
  type: 'boolean',
63
- description: 'Also look for API keys that are still in git history. Slower. Default false.',
74
+ description: 'Also look for API keys still in git history (local git only). Slower.',
64
75
  },
65
76
  includeBaseline: {
66
77
  type: 'boolean',
67
- description: 'Also list findings accepted in .launchdoctor-baseline.json. Default false.',
78
+ description: 'Also list findings accepted in .launchdoctor-baseline.json.',
68
79
  },
69
80
  },
70
81
  additionalProperties: false,
71
82
  },
72
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
83
+ annotations: READ_ONLY,
84
+ },
85
+ {
86
+ name: 'explain_finding',
87
+ title: 'Explain one finding',
88
+ description: 'What one finding means: why it matters (what an attacker or a surprise bill looks like), how to confirm it by hand, how to fix it, and when it is a false alarm. Secret values are never included.',
89
+ inputSchema: {
90
+ type: 'object',
91
+ properties: { id: ID_PROP, path: PATH_PROP },
92
+ required: ['id'],
93
+ additionalProperties: false,
94
+ },
95
+ annotations: READ_ONLY,
96
+ },
97
+ {
98
+ name: 'fix_prompt',
99
+ title: 'Get the fix prompt for one finding',
100
+ description: 'The step-by-step fix for one finding, written as instructions for an AI coding assistant. Apply it, then call rescan.',
101
+ inputSchema: {
102
+ type: 'object',
103
+ properties: { id: ID_PROP, path: PATH_PROP },
104
+ required: ['id'],
105
+ additionalProperties: false,
106
+ },
107
+ annotations: READ_ONLY,
108
+ },
109
+ {
110
+ name: 'rescan',
111
+ title: 'Check again after a fix',
112
+ description: 'Checks only some files again and says which of the given findings are gone: the files of the given finding ids, the given paths, or (with neither) the files changed since the last git commit. The whole project is still read so checks across files keep working.',
113
+ inputSchema: {
114
+ type: 'object',
115
+ properties: {
116
+ path: PATH_PROP,
117
+ ids: { type: 'array', items: { type: 'string' }, description: 'Finding ids from scan_project.' },
118
+ paths: { type: 'array', items: { type: 'string' }, description: 'Files inside the project, relative to it.' },
119
+ },
120
+ additionalProperties: false,
121
+ },
122
+ annotations: READ_ONLY,
123
+ },
124
+ {
125
+ name: 'grade_history',
126
+ title: 'Grade history',
127
+ description: 'The grades saved with "launch-doctor --record" (newest first): date, grade, score, counts and commit.',
128
+ inputSchema: { type: 'object', properties: { path: PATH_PROP }, additionalProperties: false },
129
+ annotations: READ_ONLY,
73
130
  },
74
131
  {
75
132
  name: 'scan_url',
76
133
  title: 'Check a deployed site',
77
134
  description: 'Checks a live website from the outside, the way an attacker would: downloadable .env, .git and backup files, public source maps, API keys in the JavaScript, Supabase tables readable with the public key, and HTTPS and security headers. ' +
78
- 'Sends ordinary GET requests only.',
135
+ 'The only tool that uses the network: it sends ordinary GET requests to the address given, and only to public sites.',
79
136
  inputSchema: {
80
137
  type: 'object',
81
138
  properties: {
@@ -95,108 +152,84 @@ export function mcpTools() {
95
152
  title: 'List the checks',
96
153
  description: 'Lists the categories and every finding and checklist id, for the only and skip options and for .launchdoctorignore.',
97
154
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
98
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
155
+ annotations: READ_ONLY,
99
156
  },
100
157
  ];
101
158
  }
102
159
  // ---------- tool results ----------
103
- function indent(text, by = ' ') {
104
- return text
105
- .split('\n')
106
- .map((l) => (l ? by + l : l))
107
- .join('\n');
160
+ /** Text for the model: control characters removed, and cut at MAX_TEXT with a note. */
161
+ export function capText(text, max = MAX_TEXT) {
162
+ const clean = stripControl(text);
163
+ if (clean.length <= max)
164
+ return clean;
165
+ return `${clean.slice(0, max)}\n...(cut at ${max} characters; ask about one finding with explain_finding)`;
108
166
  }
109
- function findingEntry(n, f) {
110
- const where = f.location ? ` (${shortWhere(f.location)})` : '';
111
- const known = f.baseline ? ' [in baseline]' : '';
112
- return [
113
- `${n}. ${f.title}${where} · id: ${f.id}${known}`,
114
- indent(`Why it matters: ${f.why}`),
115
- indent(`Fix prompt:\n${indent(f.fixPrompt, ' ')}`),
116
- ].join('\n');
167
+ function result(text, data) {
168
+ return { content: [{ type: 'text', text: capText(text) }], structuredContent: data };
117
169
  }
118
- function listSection(title, items, entry) {
119
- if (!items.length)
120
- return [];
121
- const out = ['', `${title} (${items.length})`, ''];
122
- for (const [i, item] of items.slice(0, MAX_LISTED).entries())
123
- out.push(entry(item, i + 1));
124
- if (items.length > MAX_LISTED)
125
- out.push(`...and ${items.length - MAX_LISTED} more.`);
126
- return out;
170
+ function toolError(message) {
171
+ return { content: [{ type: 'text', text: stripControl(message) }], isError: true };
127
172
  }
128
- /** Plain-text summary of a report, written for an AI assistant that will act on it. */
129
- export function reportText(report, includeBaseline = false) {
130
- const all = report.categories.flatMap((c) => c.findings);
131
- const shown = includeBaseline ? all : all.filter((f) => !f.baseline);
132
- const hiddenBaseline = all.length - shown.length;
133
- const manual = report.categories.flatMap((c) => c.manual);
134
- const unit = report.mode === 'live' ? 'request' : 'file';
173
+ /** One line per finding: no fix prompt and no long explanation, so the list stays small. */
174
+ function shortFinding(report, f) {
175
+ return {
176
+ id: f.ref ?? '',
177
+ number: promptNumber(report, f),
178
+ rule: f.id,
179
+ severity: f.severity,
180
+ title: f.display?.title ?? f.title,
181
+ ...(f.location?.file ? { file: f.location.file } : {}),
182
+ ...(f.location?.line ? { line: f.location.line } : {}),
183
+ ...(f.baseline ? { baseline: true } : {}),
184
+ };
185
+ }
186
+ const NOT_ONLINE = 'This scan made no network requests (no email DNS lookups); scan_url checks the live site.';
187
+ /** A scan as a short summary (text) and data, with at most MAX_LISTED findings. */
188
+ export function scanResult(report, includeBaseline = false, extra = []) {
189
+ const all = orderedFindings(report);
190
+ const listed = all.filter((f) => includeBaseline || !f.baseline);
191
+ const hiddenBaseline = all.length - listed.length;
192
+ const shown = listed.slice(0, MAX_LISTED).map((f) => shortFinding(report, f));
193
+ const notes = [...coverageNotes(report), ...(report.mode === 'live' ? [] : [NOT_ONLINE])];
194
+ const grades = report.grades;
135
195
  const lines = [
136
- `Launch Doctor ${report.version}: grade ${report.grade} (${report.score}/100) for ${report.projectName}. ${plural(report.filesScanned, unit)} checked.`,
137
- report.verdict,
196
+ `Launch Doctor ${report.version}: ${report.projectName}. ${report.verdict}.`,
197
+ grades
198
+ ? `Security ${grades.security.grade ?? '-'}, Launch readiness ${grades.launch.grade ?? '-'} (overall ${report.grade}, ${report.score}/100).`
199
+ : `Grade ${report.grade} (${report.score}/100).`,
200
+ `${plural(report.counts.critical, 'critical problem')}, ${plural(report.counts.warning, 'warning')}, ${report.counts.manual} to check by hand.`,
201
+ ...extra,
202
+ '',
203
+ ...(shown.length
204
+ ? shown.map((f) => `${f.number}. [${f.severity}] ${f.title}${f.file ? ` (${shortWhere({ file: f.file, line: f.line })})` : ''} · id ${f.id} · rule ${f.rule}${f.baseline ? ' · in baseline' : ''}`)
205
+ : [
206
+ hiddenBaseline
207
+ ? `No new problems found. The grade still counts the ${plural(hiddenBaseline, 'known finding')} accepted in .launchdoctor-baseline.json (set includeBaseline to list them).`
208
+ : 'No problems found.',
209
+ ]),
210
+ ...(listed.length > shown.length
211
+ ? [`...and ${listed.length - shown.length} more (fix these first, then rescan).`]
212
+ : []),
213
+ '',
214
+ 'Coverage:',
215
+ ...notes.map((n) => `- ${n}`),
216
+ ...(report.nestedRepos?.length ? [`- ${nestedReposNote(report.nestedRepos)}`] : []),
217
+ '',
218
+ 'Next: explain_finding or fix_prompt with an id, apply the fix, then rescan with that id.',
138
219
  ];
139
- if (report.nestedRepos?.length)
140
- lines.push(nestedReposNote(report.nestedRepos));
141
- if (report.truncated)
142
- lines.push('Very large project: only the first 20,000 files were checked.');
143
- if (report.byteLimitReached)
144
- lines.push(BYTE_LIMIT_NOTE);
145
- lines.push(...listSection('Critical', shown.filter((f) => f.severity === 'critical'), (f, n) => findingEntry(n, f)), ...listSection('Warnings', shown.filter((f) => f.severity === 'warning'), (f, n) => findingEntry(n, f)), ...listSection('Check by hand, outside the code', manual, (m, n) => `${n}. ${m.title} · id: ${m.id}\n${indent(m.how)}`));
146
- if (!shown.length) {
147
- lines.push('', hiddenBaseline
148
- ? `No new problems found. The grade still counts the ${plural(hiddenBaseline, 'known finding')} accepted in .launchdoctor-baseline.json.`
149
- : 'No problems found.');
150
- }
151
- lines.push('', `Scorecard: ${report.categories.map((c) => `${c.name} ${c.skipped ? 'skipped' : c.applicable ? (c.grade ?? '-') : 'not used'}`).join(' · ')}`);
152
- if (hiddenBaseline) {
153
- lines.push(`${plural(hiddenBaseline, 'known finding')} in .launchdoctor-baseline.json not listed (set includeBaseline to see them).`);
154
- }
155
- if (report.ignored) {
156
- lines.push(`${plural(report.ignored, 'item')} silenced by .launchdoctorignore or launch-doctor-ignore comments.`);
157
- }
158
- return lines.join('\n');
159
- }
160
- /** The same report as data, for clients that read structured tool output. */
161
- export function reportData(report, includeBaseline = false) {
162
- return {
220
+ return result(lines.join('\n'), {
163
221
  grade: report.grade,
164
222
  score: report.score,
223
+ ...(grades ? { grades } : {}),
165
224
  verdict: report.verdict,
166
225
  projectName: report.projectName,
167
226
  counts: report.counts,
168
- ...(report.nestedRepos?.length ? { nestedRepos: report.nestedRepos } : {}),
169
- categories: report.categories.map((c) => ({
170
- id: c.id,
171
- name: c.name,
172
- grade: c.grade,
173
- applicable: c.applicable,
174
- skipped: Boolean(c.skipped),
175
- })),
176
- findings: report.categories.flatMap((c) => c.findings
177
- .filter((f) => includeBaseline || !f.baseline)
178
- .map((f) => ({
179
- id: f.id,
180
- category: c.id,
181
- severity: f.severity,
182
- title: f.title,
183
- file: f.location?.file,
184
- line: f.location?.line,
185
- why: f.why,
186
- fixPrompt: f.fixPrompt,
187
- baseline: Boolean(f.baseline),
188
- }))),
189
- manual: report.categories.flatMap((c) => c.manual.map((m) => ({ id: m.id, category: c.id, title: m.title, how: m.how }))),
190
- };
191
- }
192
- function toolError(message) {
193
- return { content: [{ type: 'text', text: message }], isError: true };
194
- }
195
- function reportResult(report, includeBaseline) {
196
- return {
197
- content: [{ type: 'text', text: reportText(report, includeBaseline) }],
198
- structuredContent: reportData(report, includeBaseline),
199
- };
227
+ findings: shown,
228
+ listed: shown.length,
229
+ total: listed.length,
230
+ coverage: notes,
231
+ manual: report.categories.flatMap((c) => c.manual.map((m) => ({ id: m.id, category: c.id, title: m.title }))),
232
+ });
200
233
  }
201
234
  const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
202
235
  /** Checks the arguments by hand (no schema library), so a bad call gets a message the model can act on. */
@@ -214,42 +247,139 @@ function badArgs(args, shape) {
214
247
  }
215
248
  return null;
216
249
  }
250
+ /** The project folder for a call: the server's folder, or a folder inside it. Never outside. */
251
+ function rootFor(args, cwd) {
252
+ const base = projectRoot(cwd);
253
+ const path = args.path;
254
+ if (!path || path === '.')
255
+ return base;
256
+ return projectRoot(`${base}/${normalizeRelative(base, path)}`);
257
+ }
258
+ /**
259
+ * The last full scan of each folder, so explain_finding, fix_prompt and rescan can find an id without scanning again.
260
+ * Only kept for this server process; a finding whose file changed since then gets a fresh scan.
261
+ */
262
+ const lastScans = new Map();
263
+ async function fullScan(root, args = {}) {
264
+ const report = await scan({
265
+ root,
266
+ offline: true,
267
+ only: args.only,
268
+ skip: args.skip,
269
+ history: args.history === true,
270
+ });
271
+ if (!args.only && !args.skip)
272
+ lastScans.set(root, report);
273
+ return report;
274
+ }
275
+ /** A finding by id or number: from the last scan if it is there, otherwise from a fresh one. */
276
+ async function lookup(root, id) {
277
+ for (const report of [lastScans.get(root), undefined]) {
278
+ const r = report ?? (await fullScan(root));
279
+ const finding = findFinding(r, id);
280
+ if (finding)
281
+ return { report: r, finding };
282
+ if (!report)
283
+ break;
284
+ }
285
+ throw new CoreError('usage', `No finding with id ${id}. Run scan_project to get the current ids.`);
286
+ }
217
287
  async function scanProject(args, cwd) {
218
288
  const problem = badArgs(args, {
219
289
  path: 'string',
220
290
  only: 'string[]',
221
291
  skip: 'string[]',
222
292
  offline: 'boolean',
223
- domain: 'string',
224
293
  history: 'boolean',
225
294
  includeBaseline: 'boolean',
226
295
  });
227
296
  if (problem)
228
297
  return toolError(problem);
229
- const root = resolve(cwd, args.path ?? '.');
230
- if (!existsSync(root) || !statSync(root).isDirectory())
231
- return toolError(`Folder not found: ${root}`);
232
- const domain = args.domain
233
- ?.trim()
234
- .toLowerCase()
235
- .replace(/^https?:\/\//, '')
236
- .replace(/[/?#].*$/, '');
237
- let report;
238
- try {
239
- report = await runDoctor(root, {
240
- offline: args.offline === true,
241
- domain: domain || undefined,
242
- only: args.only,
243
- skip: args.skip,
244
- history: args.history === true ? { depth: DEFAULT_HISTORY_DEPTH } : undefined,
245
- });
246
- }
247
- catch (err) {
248
- return toolError(err.message);
249
- }
298
+ const root = rootFor(args, cwd);
299
+ const report = await fullScan(root, args);
250
300
  if (report.filesScanned === 0)
251
301
  return toolError(`No project files found in ${root}.`);
252
- return reportResult(report, args.includeBaseline === true);
302
+ return scanResult(report, args.includeBaseline === true);
303
+ }
304
+ async function explainFinding(args, cwd) {
305
+ const problem = badArgs(args, { id: 'string', path: 'string' });
306
+ if (problem)
307
+ return toolError(problem);
308
+ const { report, finding } = await lookup(rootFor(args, cwd), args.id);
309
+ const d = findingDetails(report, finding);
310
+ const e = d.explanation;
311
+ const where = d.file ? shortWhere({ file: d.file, line: d.line }) : 'the whole project';
312
+ const lines = [
313
+ `${d.number}. ${d.title} [${d.severity}] · id ${d.ref} · rule ${d.rule}`,
314
+ `Where: ${where}`,
315
+ `This finding: ${d.why}`,
316
+ ...(e
317
+ ? [
318
+ `Why it matters: ${e.whyItMatters}`,
319
+ `How to confirm: ${e.howToConfirm}`,
320
+ `How to fix: ${e.howToFix}`,
321
+ `False alarm? ${e.falsePositiveHint}`,
322
+ ]
323
+ : []),
324
+ ...(d.rotate ? [`Rotate the key first: ${d.rotate}`] : []),
325
+ ...(d.usage ? [`Check whether someone used it: ${d.usage}`] : []),
326
+ 'The fix prompt for this finding: fix_prompt with this id.',
327
+ ];
328
+ return result(lines.join('\n'), { ...d });
329
+ }
330
+ async function fixPrompt(args, cwd) {
331
+ const problem = badArgs(args, { id: 'string', path: 'string' });
332
+ if (problem)
333
+ return toolError(problem);
334
+ const { report, finding } = await lookup(rootFor(args, cwd), args.id);
335
+ const d = findingDetails(report, finding);
336
+ return result(`Fix prompt ${d.number} (${d.title}, id ${d.ref}):\n\n${finding.fixPrompt}\n\nThen call rescan with ids ["${d.ref}"].`, {
337
+ id: d.ref,
338
+ number: d.number,
339
+ rule: d.rule,
340
+ title: d.title,
341
+ fixPrompt: finding.fixPrompt,
342
+ });
343
+ }
344
+ async function rescanTool(args, cwd) {
345
+ const problem = badArgs(args, { path: 'string', ids: 'string[]', paths: 'string[]' });
346
+ if (problem)
347
+ return toolError(problem);
348
+ const root = rootFor(args, cwd);
349
+ const ids = args.ids ?? [];
350
+ // Numbers are positions in the last scan: turn them into ids first.
351
+ const previous = lastScans.get(root) ?? (ids.length ? await fullScan(root) : undefined);
352
+ const refs = ids.map((id) => (previous ? (findFinding(previous, id)?.ref ?? id) : id));
353
+ const { report, files, fixed } = await rescan({
354
+ root,
355
+ offline: true,
356
+ ...(refs.length ? { refs, previous } : {}),
357
+ ...(args.paths ? { paths: args.paths } : {}),
358
+ });
359
+ const extra = [
360
+ `Rescanned ${plural(files.length, 'file')}: ${files.slice(0, 10).join(', ')}${files.length > 10 ? ', ...' : ''}.`,
361
+ ...(refs.length
362
+ ? [
363
+ `Fixed: ${fixed.length ? fixed.join(', ') : 'none of the given ids'}. Still there: ${refs.filter((r) => !fixed.includes(r)).join(', ') || 'none'}.`,
364
+ ]
365
+ : []),
366
+ ];
367
+ const out = scanResult(report, false, extra);
368
+ out.structuredContent = { ...out.structuredContent, files, fixed };
369
+ return out;
370
+ }
371
+ function gradesTool(args, cwd) {
372
+ const problem = badArgs(args, { path: 'string' });
373
+ if (problem)
374
+ return toolError(problem);
375
+ const entries = gradeHistory(rootFor(args, cwd)).slice().reverse();
376
+ const text = entries.length
377
+ ? entries
378
+ .slice(0, 20)
379
+ .map((e) => `- ${describeEntry(e)}${e.commit ? ` (commit ${e.commit.slice(0, 7)})` : ''}`)
380
+ .join('\n')
381
+ : 'No grades recorded yet. Run "npx launch-doctor --record" to save one.';
382
+ return result(text, { entries: entries.slice(0, 50) });
253
383
  }
254
384
  async function scanUrl(args) {
255
385
  const problem = badArgs(args, { url: 'string', skipDatabase: 'boolean' });
@@ -257,20 +387,15 @@ async function scanUrl(args) {
257
387
  return toolError(problem);
258
388
  if (typeof args.url !== 'string' || !args.url.trim())
259
389
  return toolError('"url" is required, for example https://myapp.com.');
260
- try {
261
- // An AI tool decides what to scan here, and a prompt injection could aim it at your network, so only public
262
- // sites are allowed. The CLI (where you type the address yourself) also accepts your own dev server.
263
- const report = await runLiveScan(args.url, { skipDatabase: args.skipDatabase === true, allowPrivateTarget: false });
264
- return reportResult(report, false);
265
- }
266
- catch (err) {
267
- return toolError(err.message);
268
- }
390
+ // An AI tool decides what to scan here, and a prompt injection could aim it at your network, so only public
391
+ // sites are allowed. The CLI (where you type the address yourself) also accepts your own dev server.
392
+ const report = await runLiveScan(args.url, { skipDatabase: args.skipDatabase === true, allowPrivateTarget: false });
393
+ return scanResult(report);
269
394
  }
270
395
  function listChecks() {
271
396
  const categories = CHECKS.map((c) => ({ id: c.id, name: c.name, ids: [...c.ids] }));
272
397
  const text = categories.map((c) => `${c.id} (${c.name}): ${c.ids.join(', ')}`).join('\n');
273
- return { content: [{ type: 'text', text }], structuredContent: { categories } };
398
+ return result(text, { categories });
274
399
  }
275
400
  /** Run one tool. Unknown tool names are a protocol error; bad arguments are a tool error the model can fix. */
276
401
  export async function callTool(name, args, cwd = process.cwd()) {
@@ -278,13 +403,24 @@ export async function callTool(name, args, cwd = process.cwd()) {
278
403
  if (typeof a !== 'object' || Array.isArray(a))
279
404
  return toolError('Arguments must be an object.');
280
405
  const params = a;
281
- if (name === 'scan_project')
282
- return scanProject(params, cwd);
283
- if (name === 'scan_url')
284
- return scanUrl(params);
285
- if (name === 'list_checks')
286
- return listChecks();
287
- throw new RpcError(-32602, `Unknown tool: ${String(name)}`);
406
+ const tools = {
407
+ scan_project: () => scanProject(params, cwd),
408
+ explain_finding: () => explainFinding(params, cwd),
409
+ fix_prompt: () => fixPrompt(params, cwd),
410
+ rescan: () => rescanTool(params, cwd),
411
+ grade_history: () => gradesTool(params, cwd),
412
+ scan_url: () => scanUrl(params),
413
+ list_checks: () => listChecks(),
414
+ };
415
+ const run = typeof name === 'string' && Object.hasOwn(tools, name) ? tools[name] : undefined;
416
+ if (!run)
417
+ throw new RpcError(-32602, `Unknown tool: ${String(name)}`);
418
+ try {
419
+ return await run();
420
+ }
421
+ catch (err) {
422
+ return toolError(err.message);
423
+ }
288
424
  }
289
425
  // ---------- JSON-RPC ----------
290
426
  function negotiate(params) {
@@ -295,7 +431,8 @@ function negotiate(params) {
295
431
  capabilities: { tools: { listChanged: false } },
296
432
  serverInfo: { name: 'launch-doctor', title: 'Launch Doctor', version: version() },
297
433
  instructions: 'Use scan_project before a launch or a big release to find leaked keys, open databases, unverified payment webhooks, unprotected AI endpoints and missing legal pages. ' +
298
- 'Each finding has a fix prompt: apply fixes one at a time, critical first, then run scan_project again. Use scan_url on the deployed site after deploying.',
434
+ 'It lists findings with ids. For each one (critical first): explain_finding if unsure, fix_prompt for the change, apply it, then rescan with that id. ' +
435
+ 'Use scan_url on the deployed site after deploying (the only tool that uses the network).',
299
436
  };
300
437
  }
301
438
  async function dispatch(method, params, cwd) {
@@ -0,0 +1,14 @@
1
+ import type { Report } from './types.js';
2
+ /** Where `--report` writes, relative to the project. */
3
+ export declare const REPORT_FILE = ".launchdoctor/report.md";
4
+ export interface ReportMdOptions {
5
+ /** What to type after `npx launch-doctor prompt <n>` to reach this project: "" or " ./my-app". */
6
+ target?: string;
7
+ }
8
+ /**
9
+ * `.launchdoctor/report.md`: every finding explained, built from the same core and explanations as `explain` and the
10
+ * MCP server. Each finding points to its fix prompt (`launch-doctor prompt N`) instead of copying it, and no secret
11
+ * value is written: only the file, the line and the masked hint the finding already holds. All text from the scanned
12
+ * project goes through md() / mdCode(), like LAUNCH_FIXES.md.
13
+ */
14
+ export declare function renderReportMd(report: Report, opts?: ReportMdOptions): string;
@@ -0,0 +1,71 @@
1
+ import { shortWhere } from './checks/common.js';
2
+ import { coverageNotes, findingDetails } from './core.js';
3
+ import { orderedFindings } from './fixes.js';
4
+ import { STATE_DIR } from './grades.js';
5
+ import { md, mdCode } from './sanitize.js';
6
+ import { ISSUES_URL, plural } from './util.js';
7
+ /** Where `--report` writes, relative to the project. */
8
+ export const REPORT_FILE = `${STATE_DIR}/report.md`;
9
+ /** A link from Launch Doctor's own tables (rotate and usage pages); anything else is escaped text. */
10
+ const link = (x) => (/^https:\/\/[^\s<>]+$/.test(x) ? `<${x}>` : md(x));
11
+ /**
12
+ * `.launchdoctor/report.md`: every finding explained, built from the same core and explanations as `explain` and the
13
+ * MCP server. Each finding points to its fix prompt (`launch-doctor prompt N`) instead of copying it, and no secret
14
+ * value is written: only the file, the line and the masked hint the finding already holds. All text from the scanned
15
+ * project goes through md() / mdCode(), like LAUNCH_FIXES.md.
16
+ */
17
+ export function renderReportMd(report, opts = {}) {
18
+ const target = opts.target ?? '';
19
+ const ordered = orderedFindings(report);
20
+ const g = report.grades;
21
+ const out = [
22
+ `# Launch Doctor report for ${md(report.projectName)}`,
23
+ '',
24
+ `Launch Doctor ${report.version}, ${report.generatedAt.slice(0, 10)}. ${md(report.verdict)}.`,
25
+ '',
26
+ g
27
+ ? `**Security:** ${g.security.grade ?? '-'} · **Launch readiness:** ${g.launch.grade ?? '-'} · overall ${report.grade} (${report.score}/100)`
28
+ : `**Grade:** ${report.grade} (${report.score}/100)`,
29
+ '',
30
+ `${plural(report.counts.critical, 'critical problem')} · ${plural(report.counts.warning, 'warning')} · ${report.counts.manual} to check by hand${report.counts.baseline ? ` · ${report.counts.baseline} in the baseline` : ''}`,
31
+ '',
32
+ '## What was checked',
33
+ '',
34
+ ...coverageNotes(report).map((n) => `- ${md(n)}`),
35
+ '',
36
+ ];
37
+ for (const [heading, severity] of [
38
+ ['Critical', 'critical'],
39
+ ['Warnings', 'warning'],
40
+ ]) {
41
+ const list = ordered.filter((f) => f.severity === severity);
42
+ if (!list.length)
43
+ continue;
44
+ out.push(`## ${heading} (${list.length})`, '');
45
+ for (const f of list) {
46
+ const d = findingDetails(report, f);
47
+ const e = d.explanation;
48
+ const where = d.file ? mdCode(shortWhere({ file: d.file, line: d.line })) : 'the whole project';
49
+ out.push(`### ${d.number}. ${md(d.title)}`, '', `**Where:** ${where} · **Rule:** \`${d.rule}\` · **Id:** \`${d.ref}\`${d.baseline ? ' · in the baseline' : ''}`, '', `**This finding:** ${md(d.why, { oneLine: false })}`, '');
50
+ if (e) {
51
+ out.push(`**Why it matters:** ${md(e.whyItMatters)}`, '', `**How to confirm:** ${md(e.howToConfirm)}`, '', `**How to fix:** ${md(e.howToFix)}`, '', `**False alarm?** ${md(e.falsePositiveHint)}`, '');
52
+ }
53
+ if (d.rotate)
54
+ out.push(`**Rotate the key first:** ${link(d.rotate)}`, '');
55
+ if (d.usage)
56
+ out.push(`**Check whether someone used it:** ${link(d.usage)}`, '');
57
+ out.push(`**Fix prompt:** \`npx launch-doctor prompt ${d.number}${target} --copy\` (also number ${d.number} in LAUNCH_FIXES.md)`, '');
58
+ }
59
+ }
60
+ if (!ordered.length)
61
+ out.push('## No problems found', '', 'None of the problems Launch Doctor looks for were found.', '');
62
+ const manual = report.categories.flatMap((c) => c.manual);
63
+ if (manual.length) {
64
+ out.push(`## Check by hand (${manual.length})`, '', "Things Launch Doctor can't see from your code:", '');
65
+ for (const m of manual)
66
+ out.push(`- [ ] **${md(m.title)}** - ${md(m.how)}`);
67
+ out.push('');
68
+ }
69
+ out.push('---', '', `_Written by \`launch-doctor --report\`. It is rewritten on every run with \`--report\`; ${STATE_DIR}/ can go in .gitignore. A wrong finding or a missed problem? Please [report it](${ISSUES_URL})._`, '');
70
+ return out.join('\n');
71
+ }
@@ -4,6 +4,8 @@ export declare const TOP_FINDINGS = 3;
4
4
  export interface ShortReportOptions {
5
5
  /** Where LAUNCH_FIXES.md was written, if it was. */
6
6
  fixFile?: string;
7
+ /** Where --report wrote .launchdoctor/report.md, if it did. */
8
+ reportFile?: string;
7
9
  /** The last recorded overall grade ("B (82) on 30 Nov 2026"). */
8
10
  lastRecorded?: string;
9
11
  banner?: boolean;