co-maintainer 0.7.10-beta.1 → 0.7.11-beta.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "co-maintainer",
3
- "version": "0.7.10-beta.1",
3
+ "version": "0.7.11-beta.1",
4
4
  "description": "An imitator of yours, A PR review tool like co-maintainer.",
5
5
  "keywords": [
6
6
  "ai",
@@ -935,6 +935,17 @@ export const COMMANDS = [
935
935
  default: "3",
936
936
  description: "The most lines search-non-code returns around a match. Needs --repo. 0 or -1 means no limit.",
937
937
  },
938
+ {
939
+ name: "mcp-config",
940
+ value: "PATH",
941
+ description: "Read the repository's MCP servers from this JSON file and store them. Reviews offer their listed read-only tools to the model. Needs --repo. Refused when CM_MCP_DISABLED=1.",
942
+ },
943
+ {
944
+ name: "mcp-allow-forks",
945
+ value: "true|false",
946
+ default: "false",
947
+ description: "Offer MCP tools in serve reviews of pull requests from forks. Needs --repo.",
948
+ },
938
949
  {
939
950
  name: "guide-full-every",
940
951
  value: "N",
@@ -990,6 +1001,7 @@ export const COMMANDS = [
990
1001
  "co-maintainer set --remote-host=https://review.example.com --remote-token=...",
991
1002
  "co-maintainer set --repo=owner/repo --review-system-prompt='Focus on the parser.'",
992
1003
  "co-maintainer set --repo=owner/repo --diagram-runtime=plantuml-server",
1004
+ "co-maintainer set --repo=owner/repo --mcp-config=./mcp.json",
993
1005
  "co-maintainer set --unset=token",
994
1006
  ],
995
1007
  },
@@ -122,6 +122,7 @@ async function runReviewPr(options, cli) {
122
122
  catchesUp: true,
123
123
  extensions,
124
124
  intent: intent !== null,
125
+ showReferences: readConfig().repos?.[options.repo]?.reviewReferences === true,
125
126
  });
126
127
  }
127
128
  else {
@@ -10,6 +10,7 @@ import { verifyOpenCode } from "../../ai/opencode.js";
10
10
  import { die } from "../error.js";
11
11
  import { parsePolicy } from "../../services/review_policy.js";
12
12
  import { isCodegraphVersion } from "../../tools/codegraph.js";
13
+ import { MCP_DISABLED_MESSAGE, McpConfigError, mcpDisabled, mcpServersSummary, parseMcpConfig, } from "../../tools/mcp_config.js";
13
14
  import { AI_PROVIDERS, rejectRetiredProvider } from "../../ai/provider.js";
14
15
  import { MAX_CONCURRENCY, MIN_CONCURRENCY, } from "../../services/concurrency.js";
15
16
  import { renderCommandHelp, renderGlobalHelp } from "./registry.js";
@@ -86,6 +87,8 @@ export async function runSet(args) {
86
87
  ...DIAGRAM_FLAGS,
87
88
  "review-read-diff-max-chars",
88
89
  ...TOOL_LIMIT_FLAGS.map(([flag]) => flag),
90
+ "mcp-config",
91
+ "mcp-allow-forks",
89
92
  "guide-full-every",
90
93
  "password",
91
94
  "extension-rerun-on-restart",
@@ -107,7 +110,12 @@ export async function runSet(args) {
107
110
  await runSetRepo(repoArg, args);
108
111
  return;
109
112
  }
110
- for (const name of [...DIAGRAM_FLAGS, "review-references"]) {
113
+ for (const name of [
114
+ ...DIAGRAM_FLAGS,
115
+ "review-references",
116
+ "mcp-config",
117
+ "mcp-allow-forks",
118
+ ]) {
111
119
  if (text(args, name) !== undefined)
112
120
  die(`--${name} needs --repo`);
113
121
  }
@@ -410,6 +418,8 @@ const REPO_SCOPED_FLAGS = new Set([
410
418
  ...DIAGRAM_FLAGS,
411
419
  "review-read-diff-max-chars",
412
420
  ...TOOL_LIMIT_FLAGS.map(([flag]) => flag),
421
+ "mcp-config",
422
+ "mcp-allow-forks",
413
423
  "guide-full-every",
414
424
  "review-references",
415
425
  "gh-concurrent",
@@ -430,6 +440,10 @@ const REPO_SCOPED_UNSET = new Set([
430
440
  "review-read-diff-max-chars",
431
441
  "reviewReadDiffMaxChars",
432
442
  ...TOOL_LIMIT_FLAGS.flat(),
443
+ "mcp-config",
444
+ "mcpServers",
445
+ "mcp-allow-forks",
446
+ "mcpAllowForks",
433
447
  "guide-full-every",
434
448
  "guideFullEvery",
435
449
  "gh-concurrent",
@@ -439,7 +453,7 @@ const REPO_SCOPED_UNSET = new Set([
439
453
  "review-references",
440
454
  "reviewReferences",
441
455
  ]);
442
- /** `set --repo=owner/repo [--review-system-prompt=... | --review-system-prompt-max-chars=N | --review-read-diff-max-chars=N | --review-tool-result-max-chars=N | --review-tool-budget-chars=N | --review-search-max-context-lines=N | --unset=name]`
456
+ /** `set --repo=owner/repo [--review-system-prompt=... | --review-system-prompt-max-chars=N | --review-read-diff-max-chars=N | --review-tool-result-max-chars=N | --review-tool-budget-chars=N | --review-search-max-context-lines=N | --mcp-config=PATH | --mcp-allow-forks=true|false | --unset=name]`
443
457
  * writes the repository-scoped settings to `repos[owner/repo]` in config.json
444
458
  * instead of the global config. */
445
459
  async function runSetRepo(typed, args) {
@@ -554,6 +568,42 @@ async function runSetRepo(typed, args) {
554
568
  }
555
569
  patch[field] = value;
556
570
  }
571
+ if (unset.has("mcp-config") || unset.has("mcpServers")) {
572
+ patch.mcpServers = undefined;
573
+ }
574
+ const mcpFile = text(args, "mcp-config");
575
+ if (mcpFile !== undefined) {
576
+ // The cloud sets the switch from outside the container, so a stored
577
+ // config can never turn MCP back on there.
578
+ if (mcpDisabled())
579
+ die(MCP_DISABLED_MESSAGE);
580
+ let raw;
581
+ try {
582
+ raw = await readTextFile(mcpFile);
583
+ }
584
+ catch (error) {
585
+ die(`Could not read the MCP config ${mcpFile}: ${String(error)}`);
586
+ }
587
+ try {
588
+ patch.mcpServers = parseMcpConfig(raw);
589
+ }
590
+ catch (error) {
591
+ if (error instanceof McpConfigError) {
592
+ die(`--mcp-config: ${error.message}`);
593
+ }
594
+ throw error;
595
+ }
596
+ }
597
+ if (unset.has("mcp-allow-forks") || unset.has("mcpAllowForks")) {
598
+ patch.mcpAllowForks = undefined;
599
+ }
600
+ const allowForks = text(args, "mcp-allow-forks");
601
+ if (allowForks !== undefined) {
602
+ if (!["true", "false"].includes(allowForks)) {
603
+ die("--mcp-allow-forks must be true or false");
604
+ }
605
+ patch.mcpAllowForks = allowForks === "true";
606
+ }
557
607
  if (unset.has("guide-full-every") || unset.has("guideFullEvery")) {
558
608
  patch.guideFullEvery = undefined;
559
609
  }
@@ -588,7 +638,7 @@ async function runSetRepo(typed, args) {
588
638
  patch.reviewSystemPrompt = prompt.trim() === "" ? undefined : prompt;
589
639
  }
590
640
  if (Object.keys(patch).length === 0) {
591
- die("Nothing to set. Pass --review-system-prompt=, --review-system-prompt-max-chars=N, --diagram-runtime=, --plantuml-server=, --plantuml-output-format=, --review-read-diff-max-chars=N, --review-tool-result-max-chars=N, --review-tool-budget-chars=N, --review-search-max-context-lines=N, --guide-full-every=N, --review-references=on|off, or --unset=name with --repo.");
641
+ die("Nothing to set. Pass --review-system-prompt=, --review-system-prompt-max-chars=N, --diagram-runtime=, --plantuml-server=, --plantuml-output-format=, --review-read-diff-max-chars=N, --review-tool-result-max-chars=N, --review-tool-budget-chars=N, --review-search-max-context-lines=N, --mcp-config=PATH, --mcp-allow-forks=true|false, --guide-full-every=N, --review-references=on|off, or --unset=name with --repo.");
592
642
  }
593
643
  // The values after this write are the ones given here, or the stored ones.
594
644
  // Lowering the cap re-checks the stored prompt too, so it cannot end up over
@@ -605,7 +655,13 @@ async function runSetRepo(typed, args) {
605
655
  die(`--review-system-prompt: ${problem}`);
606
656
  }
607
657
  await writeRepoConfig(repo, patch);
608
- const summary = Object.entries(patch).map(([key, value]) => value === undefined ? `${key} (unset)` : `${key}=${value}`);
658
+ // MCP servers print by name and tool: their command and env may hold
659
+ // secrets.
660
+ const summary = Object.entries(patch).map(([key, value]) => value === undefined
661
+ ? `${key} (unset)`
662
+ : key === "mcpServers"
663
+ ? `${key}=${mcpServersSummary(patch.mcpServers)}`
664
+ : `${key}=${value}`);
609
665
  console.log(`[set] updated ${repo}: ${summary.join(", ")}`);
610
666
  console.log(`Saved to ${configPath()}`);
611
667
  }
@@ -13,7 +13,10 @@ export declare function escapeProperty(value: string): string;
13
13
  /** One workflow command per finding still standing, errors first. A finding
14
14
  * that was closed since the last review needs no annotation. The dropped
15
15
  * files warning takes one of the warning slots. */
16
- export declare function githubAnnotations(findings: HumanFinding[], coverage?: Coverage): string[];
16
+ export declare function githubAnnotations(findings: HumanFinding[], coverage?: Coverage,
17
+ /** Name each finding's rules, only when the repository turned references
18
+ * on, as the terminal output does. */
19
+ showReferences?: boolean): string[];
17
20
  export type GithubSummaryInput = {
18
21
  /** What was reviewed, for the line under the heading. */
19
22
  title: string;
@@ -30,6 +33,9 @@ export type GithubSummaryInput = {
30
33
  /** The extensions' results. Their findings join the table, and their
31
34
  * `markdown` follows the AI part. */
32
35
  extensions?: ExtensionReport;
36
+ /** Name each finding's rules in its annotation. On only when the
37
+ * repository turned references on. */
38
+ showReferences?: boolean;
33
39
  /** An intent file was given. The summary says so and never shows the text. */
34
40
  intent?: boolean;
35
41
  };
@@ -27,7 +27,17 @@ export function escapeData(value) {
27
27
  export function escapeProperty(value) {
28
28
  return escapeData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
29
29
  }
30
- function annotation(row) {
30
+ /** ` (rule R3)` or ` (rules R3, I1)`: the guide and instruction rules a
31
+ * finding rests on, so a CI annotation names them as the terminal does. */
32
+ function rulesNote(row) {
33
+ const ids = (row.references ?? []).flatMap((reference) => reference.kind === "rule" || reference.kind === "instruction"
34
+ ? [reference.id]
35
+ : []);
36
+ if (ids.length === 0)
37
+ return "";
38
+ return ` (${ids.length === 1 ? "rule" : "rules"} ${ids.join(", ")})`;
39
+ }
40
+ function annotation(row, showReferences = false) {
31
41
  const properties = [];
32
42
  if (row.path) {
33
43
  properties.push(`file=${escapeProperty(row.path)}`);
@@ -46,7 +56,8 @@ function annotation(row) {
46
56
  ? `${row.severity}: ${short}`
47
57
  : `${row.severity} finding`)}`);
48
58
  const level = row.blocking ? "error" : "warning";
49
- return `::${level} ${properties.join(",")}::${escapeData(row.body || row.title)}`;
59
+ const note = showReferences ? rulesNote(row) : "";
60
+ return `::${level} ${properties.join(",")}::${escapeData(`${row.body || row.title}${note}`)}`;
50
61
  }
51
62
  function active(findings) {
52
63
  return sortHumanFindings(findings).filter((row) => row.state !== "closed");
@@ -63,7 +74,10 @@ function droppedAnnotation(coverage) {
63
74
  /** One workflow command per finding still standing, errors first. A finding
64
75
  * that was closed since the last review needs no annotation. The dropped
65
76
  * files warning takes one of the warning slots. */
66
- export function githubAnnotations(findings, coverage) {
77
+ export function githubAnnotations(findings, coverage,
78
+ /** Name each finding's rules, only when the repository turned references
79
+ * on, as the terminal output does. */
80
+ showReferences = false) {
67
81
  const rows = active(findings);
68
82
  const errors = rows.filter((row) => row.blocking);
69
83
  const warnings = rows.filter((row) => !row.blocking);
@@ -72,7 +86,7 @@ export function githubAnnotations(findings, coverage) {
72
86
  ...errors.slice(0, MAX_ANNOTATIONS_PER_LEVEL),
73
87
  ...warnings.slice(0, MAX_ANNOTATIONS_PER_LEVEL - (dropped ? 1 : 0)),
74
88
  ];
75
- const lines = shown.map(annotation);
89
+ const lines = shown.map((row) => annotation(row, showReferences));
76
90
  if (dropped)
77
91
  lines.push(dropped);
78
92
  const left = rows.length - shown.length;
@@ -150,7 +164,7 @@ export function emitGithubOutput(input) {
150
164
  // Only an extension finding with a location is annotated. The job summary
151
165
  // lists the rest.
152
166
  const located = extensionHumanFindings(input.extensions).filter((row) => row.path);
153
- for (const line of githubAnnotations([...input.findings, ...located], input.coverage)) {
167
+ for (const line of githubAnnotations([...input.findings, ...located], input.coverage, input.showReferences)) {
154
168
  console.log(line);
155
169
  }
156
170
  appendStepSummary(githubSummary(input));
@@ -1,5 +1,6 @@
1
1
  import { type Platform } from "./util/runtime.ts";
2
2
  import type { ExtensionRegistration } from "./extensions/registry.ts";
3
+ import type { McpServerConfig } from "./tools/mcp_config.ts";
3
4
  /** Everything init/remake resolved for one repo, except secrets, an API
4
5
  * token is never written to config.json, only ever taken from --token or
5
6
  * an env file. Remembering this lets `remake owner/repo` run with no
@@ -75,6 +76,12 @@ export type RepoConfig = {
75
76
  /** Most context lines `search-non-code` returns around a match. Unset means
76
77
  * the default, `0` or a negative number means no limit. */
77
78
  reviewSearchMaxContextLines?: number;
79
+ /** The repository's MCP servers, read from the file `set --mcp-config`
80
+ * names. Their `env` values are never printed. */
81
+ mcpServers?: Record<string, McpServerConfig>;
82
+ /** `serve` offers MCP tools to a pull request from a fork only when this
83
+ * is true. */
84
+ mcpAllowForks?: boolean;
78
85
  /** Every N-th `sync` whose guide input changed rewrites the review guide
79
86
  * in full, the others edit it. Unset means 10, `1` always rewrites, `0`
80
87
  * never rewrites after `init`. */
@@ -213,8 +213,14 @@ export async function runLocalReview(cli) {
213
213
  // model call. The handler has released the lock.
214
214
  if (interrupted())
215
215
  return;
216
- // Search and codegraph read the working tree at the git root.
217
- extras.tools = { kind: "tree", root, codegraph: codegraphPrep.tools };
216
+ // Search and codegraph read the working tree at the git root. The
217
+ // repository's MCP servers run here too.
218
+ extras.tools = {
219
+ kind: "tree",
220
+ root,
221
+ codegraph: codegraphPrep.tools,
222
+ mcp: true,
223
+ };
218
224
  const stopHeartbeat = startHeartbeat("reviewing local changes");
219
225
  const started = performance.now();
220
226
  const aiMetrics = emptyAiMetrics();
@@ -314,6 +320,7 @@ export async function runLocalReview(cli) {
314
320
  catchesUp: true,
315
321
  extensions,
316
322
  intent: Boolean(intentLoad.intent),
323
+ showReferences: readConfig().repos?.[options.repo]?.reviewReferences === true,
317
324
  });
318
325
  }
319
326
  else {
@@ -24,4 +24,9 @@ export declare function ensureClone(repo: string, run: Run): Promise<string>;
24
24
  * branch has moved on or the PR was squash-merged, so no local or
25
25
  * remote-tracking ref points at it any more. */
26
26
  export declare function ensureCommit(clone: string, revision: string, run: Run): Promise<string>;
27
+ /** `run` for git commands inside `clone` that may reach GitHub. The clone is
28
+ * blobless, so a worktree, a checkout or a `git show` downloads file contents
29
+ * on demand, and on a private repository that needs the App's token as much
30
+ * as the clone did. */
31
+ export declare function withGitAuth(run: Run, clone: string): Run;
27
32
  export declare function ensureWorktree(repo: string, pr: number, commit: string, run: Run): Promise<string>;
@@ -136,21 +136,32 @@ export async function ensureCommit(clone, revision, run) {
136
136
  }
137
137
  return sha;
138
138
  }
139
+ /** `run` for git commands inside `clone` that may reach GitHub. The clone is
140
+ * blobless, so a worktree, a checkout or a `git show` downloads file contents
141
+ * on demand, and on a private repository that needs the App's token as much
142
+ * as the clone did. */
143
+ export function withGitAuth(run, clone) {
144
+ return async (command, args, cwd, env) => {
145
+ const auth = await gitAuthEnv(clone);
146
+ return run(command, args, cwd, auth || env ? { ...auth, ...env } : undefined);
147
+ };
148
+ }
139
149
  export async function ensureWorktree(repo, pr, commit, run) {
140
150
  return withCloneLock(repo, async () => {
141
151
  const clone = await ensureCloneUnlocked(repo, run);
142
152
  const sha = await ensureCommit(clone, commit, run);
143
153
  const dir = worktreeDir(repo, pr);
154
+ const git = withGitAuth(run, clone);
144
155
  if (await pathExists(`${dir}/.git`)) {
145
156
  log("checkout", `reusing worktree ${dir}`);
146
- const reset = await run("git", ["checkout", "-q", "--detach", sha], dir);
157
+ const reset = await git("git", ["checkout", "-q", "--detach", sha], dir);
147
158
  if (reset.code !== 0) {
148
159
  throw new Error(`checkout ${sha} failed: ${reset.stderr.trim()}`);
149
160
  }
150
161
  return dir;
151
162
  }
152
163
  log("checkout", `creating worktree ${dir} at ${sha.slice(0, 10)}`);
153
- const added = await run("git", ["worktree", "add", "-q", "--detach", dir, sha], clone);
164
+ const added = await git("git", ["worktree", "add", "-q", "--detach", dir, sha], clone);
154
165
  if (added.code !== 0) {
155
166
  throw new Error(`git worktree add failed: ${added.stderr.trim()}`);
156
167
  }
@@ -1,9 +1,11 @@
1
1
  /** The tools a review offers the model, prepared in one place for every mode
2
2
  * (issue 79): codegraph when it is on, `search-non-code` where a checkout is
3
- * there to search, and `read-full-diff` from the diff plan. A later kind of
4
- * tool, such as a repository's MCP servers, joins the list here. */
3
+ * there to search, `read-full-diff` from the diff plan, and the tools of the
4
+ * repository's MCP servers where the mode runs them. */
5
5
  import type { ToolHandler } from "../ai/mermaid_loop.ts";
6
- import type { Options } from "../types.ts";
6
+ import type { Json, Options } from "../types.ts";
7
+ import { type McpServerConfig } from "../tools/mcp_config.ts";
8
+ import { type McpSession } from "../tools/mcp_tools.ts";
7
9
  import { type Run } from "./checkout.ts";
8
10
  import { type SearchOptions } from "../tools/search_non_code.ts";
9
11
  /** Where a review's tools run. */
@@ -17,6 +19,8 @@ export type ReviewToolSource =
17
19
  commit: string;
18
20
  search: boolean;
19
21
  allowInstall?: boolean;
22
+ /** Start the repository's MCP servers. */
23
+ mcp?: boolean;
20
24
  }
21
25
  /** A tree already on disk with its codegraph tools ready: local review at
22
26
  * the git root. */
@@ -24,18 +28,24 @@ export type ReviewToolSource =
24
28
  kind: "tree";
25
29
  root: string;
26
30
  codegraph: ToolHandler[];
31
+ mcp?: boolean;
27
32
  }
28
33
  /** Tools another process runs: a remote review, where the client runs
29
- * codegraph and search in its own checkout. */
34
+ * codegraph and search in its own checkout. The server runs the MCP
35
+ * servers it has for the repository itself. */
30
36
  | {
31
37
  kind: "bridge";
32
38
  tools: ToolHandler[];
39
+ mcp?: boolean;
33
40
  };
34
41
  export type ReviewTools = {
35
42
  /** Every tool to offer, codegraph first. */
36
43
  tools: ToolHandler[];
37
44
  /** The codegraph tools alone, which decide `codegraphState`. */
38
45
  codegraph: ToolHandler[];
46
+ /** The review's MCP servers, empty when it runs none. The review stops
47
+ * them however it ends. */
48
+ mcp: McpSession;
39
49
  };
40
50
  export type ReviewToolsDeps = {
41
51
  run?: Run;
@@ -43,6 +53,8 @@ export type ReviewToolsDeps = {
43
53
  codegraph?: (worktree: () => Promise<string>) => Promise<ToolHandler[]>;
44
54
  /** Overrides the repository's search settings, for tests. */
45
55
  search?: SearchOptions;
56
+ /** Overrides the MCP start, for tests. */
57
+ mcp?: (servers: Record<string, McpServerConfig>) => Promise<McpSession>;
46
58
  };
47
59
  export declare function isCodegraphTool(name: string): boolean;
48
60
  /** The review's tools. `diffTools` is the diff plan's own tools
@@ -50,6 +62,16 @@ export declare function isCodegraphTool(name: string): boolean;
50
62
  * prepared at the same time. A setup that fails leaves its tools out and the
51
63
  * review goes on with the rest. */
52
64
  export declare function prepareReviewTools(source: ReviewToolSource, options: Pick<Options, "repo" | "useCodegraph">, diffTools: ToolHandler[] | Promise<ToolHandler[]>, deps?: ReviewToolsDeps): Promise<ReviewTools>;
65
+ /** The repository's MCP servers, started when this mode runs them, none is
66
+ * turned off by `CM_MCP_DISABLED=1`, and the repository has some. */
67
+ export declare function startMcp(source: ReviewToolSource, repo: string, deps?: Pick<ReviewToolsDeps, "mcp">): Promise<McpSession>;
68
+ /** True when the pull request's head lives in another repository, or in
69
+ * none because the fork was deleted. The same rule as the review policy's
70
+ * `fork`. */
71
+ export declare function pullFromFork(pr: Json, repo: string): boolean;
72
+ /** Whether a `serve` review of this pull request may start the repository's
73
+ * MCP servers: a pull request from a fork only with `--mcp-allow-forks=true`. */
74
+ export declare function mcpAllowedForPull(pr: Json, repo: string): boolean;
53
75
  /** `codegraphState` from the codegraph tools alone, never from the length of
54
76
  * the whole tool list. */
55
77
  export declare function codegraphState(useCodegraph: boolean | undefined, codegraph: ToolHandler[]): "used" | "disabled" | "unavailable";
@@ -1,4 +1,7 @@
1
1
  import { log } from "../util/log.js";
2
+ import { readConfig } from "../config.js";
3
+ import { mcpDisabled } from "../tools/mcp_config.js";
4
+ import { emptyMcpSession, startMcpSession, } from "../tools/mcp_tools.js";
2
5
  import { ensureWorktree, runCommand } from "./checkout.js";
3
6
  import { prepareCodegraphTools } from "./codegraph_tools.js";
4
7
  import { searchNonCodeTool, searchOptionsFor, } from "../tools/search_non_code.js";
@@ -10,11 +13,32 @@ export function isCodegraphTool(name) {
10
13
  * prepared at the same time. A setup that fails leaves its tools out and the
11
14
  * review goes on with the rest. */
12
15
  export async function prepareReviewTools(source, options, diffTools, deps = {}) {
13
- const [own, diff] = await Promise.all([
14
- prepareOwnTools(source, options, deps),
15
- diffTools,
16
- ]);
17
- return { ...own, tools: [...own.tools, ...diff] };
16
+ const starting = startMcp(source, options.repo, deps);
17
+ try {
18
+ const [own, diff, mcp] = await Promise.all([
19
+ prepareOwnTools(source, options, deps),
20
+ diffTools,
21
+ starting,
22
+ ]);
23
+ return { ...own, tools: [...own.tools, ...diff, ...mcp.tools], mcp };
24
+ }
25
+ catch (error) {
26
+ // Servers that started while another part failed are stopped here, as
27
+ // the review that would stop them never gets them.
28
+ void starting.then((mcp) => mcp.stop(), () => { });
29
+ throw error;
30
+ }
31
+ }
32
+ /** The repository's MCP servers, started when this mode runs them, none is
33
+ * turned off by `CM_MCP_DISABLED=1`, and the repository has some. */
34
+ export async function startMcp(source, repo, deps = {}) {
35
+ if (!source.mcp || mcpDisabled())
36
+ return emptyMcpSession();
37
+ const servers = readConfig().repos?.[repo]?.mcpServers;
38
+ if (!servers || Object.keys(servers).length === 0) {
39
+ return emptyMcpSession();
40
+ }
41
+ return (deps.mcp ?? startMcpSession)(servers);
18
42
  }
19
43
  async function prepareOwnTools(source, options, deps) {
20
44
  const search = (root) => searchNonCodeTool(root, deps.search ?? searchOptionsFor(options.repo));
@@ -60,6 +84,22 @@ async function prepareOwnTools(source, options, deps) {
60
84
  codegraph,
61
85
  };
62
86
  }
87
+ /** True when the pull request's head lives in another repository, or in
88
+ * none because the fork was deleted. The same rule as the review policy's
89
+ * `fork`. */
90
+ export function pullFromFork(pr, repo) {
91
+ const head = pr.head;
92
+ const headRepo = head?.repo?.full_name;
93
+ return (typeof headRepo !== "string" ||
94
+ headRepo.toLowerCase() !== repo.toLowerCase());
95
+ }
96
+ /** Whether a `serve` review of this pull request may start the repository's
97
+ * MCP servers: a pull request from a fork only with `--mcp-allow-forks=true`. */
98
+ export function mcpAllowedForPull(pr, repo) {
99
+ if (!pullFromFork(pr, repo))
100
+ return true;
101
+ return readConfig().repos?.[repo]?.mcpAllowForks === true;
102
+ }
63
103
  /** `codegraphState` from the codegraph tools alone, never from the length of
64
104
  * the whole tool list. */
65
105
  export function codegraphState(useCodegraph, codegraph) {
@@ -40,6 +40,9 @@ export type ReviewExtras = {
40
40
  /** Stop from the dashboard. An AI call that already started finishes, and
41
41
  * no new one starts: no further tool round, retry or improvement pass. */
42
42
  signal?: AbortSignal;
43
+ /** True in `serve`: a pull request from a fork gets no MCP tools unless
44
+ * the repository sets `mcpAllowForks`. */
45
+ mcpForkRule?: boolean;
43
46
  };
44
47
  /** What a review run returns to every flow. */
45
48
  export type ReviewOutcome = AiResponse & {
@@ -53,11 +56,13 @@ export type ReviewOutcome = AiResponse & {
53
56
  referenceContext: ReferenceContext;
54
57
  codegraphState: "used" | "disabled" | "unavailable";
55
58
  coverage: Coverage;
56
- /** `diff_dropped`, `diff_withheld`, `summary_failed` and
57
- * `tool_budget_spent`. */
59
+ /** `diff_dropped`, `diff_withheld`, `summary_failed`,
60
+ * `tool_budget_spent`, the MCP warnings and `private_text_removed`. */
58
61
  warnings: CoverageWarning[];
59
62
  /** What the review's tools did, for `usage.tools`. */
60
63
  tools: ToolUsage;
64
+ /** The MCP servers that started for this review, by name. */
65
+ mcpServers: string[];
61
66
  /** Every changed file of the subject, for the result's `revision` block. */
62
67
  diffStats: {
63
68
  files: number;