Skip to content

Commit 78aa0d5

Browse files
authored
feat(mcp): unlink every PR in given states with one call (#27925)
Co-authored-by: maria-rcks <[email protected]>
1 parent 8f1e61c commit 78aa0d5

12 files changed

Lines changed: 198 additions & 11 deletions

File tree

‎apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,39 @@ describe("pull request toolkit handlers", () => {
517517
}),
518518
);
519519

520+
it.effect("unlinks every visible pull request in the given states in one call", () =>
521+
Effect.gen(function* () {
522+
const withState = (number: number, state: "open" | "closed" | "merged") => {
523+
const link = makeLink(number, { headBranch: `branch-${number}` });
524+
return { ...link, snapshot: { ...link.snapshot!, state } };
525+
};
526+
const harness = yield* makeHarness({
527+
thread: makeThread([
528+
withState(1, "merged"),
529+
withState(2, "open"),
530+
withState(3, "closed"),
531+
makeLink(4),
532+
{ ...withState(5, "merged"), source: "stack-dismissed" },
533+
]),
534+
});
535+
const result = yield* harness.call("unlink_pull_requests", {
536+
states: ["closed", "merged"],
537+
});
538+
expect(result).toEqual({
539+
unlinked: [
540+
{ host: "github.com", repository: "t3tools/t3code", state: "merged", numbers: [1] },
541+
{ host: "github.com", repository: "t3tools/t3code", state: "closed", numbers: [3] },
542+
],
543+
unlinkedCount: 2,
544+
remaining: 2,
545+
});
546+
expect(yield* Ref.get(harness.commands)).toMatchObject([
547+
{ type: "thread.pull-request.unlink", number: 1 },
548+
{ type: "thread.pull-request.unlink", number: 3 },
549+
]);
550+
}),
551+
);
552+
520553
it("reports an older Forgejo link's HTTP port when listing thread links", () => {
521554
const result = listThreadPullRequests(
522555
makeThread([

‎apps/server/src/mcp/toolkits/pullRequests/handlers.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,42 @@ const make = Effect.gen(function* () {
426426
};
427427
}),
428428
),
429+
unlink_pull_requests: writesThread((input) =>
430+
Effect.gen(function* () {
431+
const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
432+
const visible = visibleThreadPullRequests(threadPullRequestsOf(thread));
433+
const matching = visible.flatMap((link) => {
434+
const state = link.snapshot?.state;
435+
return state !== undefined && input.states.includes(state)
436+
? [{ ...normalizeThreadPullRequestKey(link), state }]
437+
: [];
438+
});
439+
yield* Effect.forEach(matching, ({ host, repository, number }) =>
440+
Effect.gen(function* () {
441+
yield* engine.dispatch({
442+
type: "thread.pull-request.unlink",
443+
commandId: yield* commandId("mcp-pr-unlink", thread.id),
444+
threadId: thread.id,
445+
host,
446+
repository,
447+
number,
448+
});
449+
}).pipe(Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError))),
450+
);
451+
// Numbers grouped by repository and state keep a large batch's result small.
452+
const groups = Map.groupBy(matching, (pr) => `${pr.host}/${pr.repository}/${pr.state}`);
453+
return {
454+
unlinked: [...groups.values()].map((prs) => ({
455+
host: prs[0]!.host,
456+
repository: prs[0]!.repository,
457+
state: prs[0]!.state,
458+
numbers: prs.map((pr) => pr.number),
459+
})),
460+
unlinkedCount: matching.length,
461+
remaining: visible.length - matching.length,
462+
};
463+
}),
464+
),
429465
list_thread_pull_requests: McpToolAccess.reads((input) =>
430466
requireThread(PullRequestListFailedError, input.threadId).pipe(
431467
Effect.map(listThreadPullRequests),

‎apps/server/src/mcp/toolkits/pullRequests/tools.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,20 @@ export const UnlinkPullRequestResult = Schema.Struct({
231231
});
232232
export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type;
233233

234+
export const UnlinkPullRequestsResult = Schema.Struct({
235+
unlinked: Schema.Array(
236+
Schema.Struct({
237+
host: Schema.String,
238+
repository: Schema.String,
239+
state: PullRequestState,
240+
numbers: Schema.Array(Schema.Int),
241+
}),
242+
),
243+
unlinkedCount: Schema.Int,
244+
remaining: Schema.Int,
245+
});
246+
export type UnlinkPullRequestsResult = typeof UnlinkPullRequestsResult.Type;
247+
234248
export const WatchPullRequestResult = Schema.Struct({
235249
...PullRequestIdentity,
236250
watching: Schema.Boolean,
@@ -297,6 +311,24 @@ const UnlinkPullRequestTool = Tool.make("unlink_pull_request", {
297311
.annotate(Tool.Idempotent, true)
298312
.annotate(Tool.OpenWorld, false);
299313

314+
const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", {
315+
description:
316+
"Unlink every PR on a thread whose last known state (as `list_thread_pull_requests` shows) is in `states`, in one call. Use it instead of one `unlink_pull_request` per PR. PRs with no known state stay linked.",
317+
parameters: Schema.Struct({
318+
environmentId: OrchestratorMcpEnvironmentTarget,
319+
threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
320+
states: Schema.Array(PullRequestState).check(Schema.isMinLength(1)),
321+
}),
322+
success: UnlinkPullRequestsResult,
323+
failure: PullRequestToolError,
324+
dependencies,
325+
})
326+
.annotate(Tool.Title, "Unlink pull requests by state")
327+
.annotate(Tool.Readonly, false)
328+
.annotate(Tool.Destructive, true)
329+
.annotate(Tool.Idempotent, true)
330+
.annotate(Tool.OpenWorld, false);
331+
300332
const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
301333
description:
302334
"List PRs linked to a thread, with last known state and stack order (bottom to top). Call only when you need that list. Never as an end-of-work check.",
@@ -411,6 +443,7 @@ const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", {
411443
export const PullRequestsToolkit = Toolkit.make(
412444
LinkPullRequestTool,
413445
UnlinkPullRequestTool,
446+
UnlinkPullRequestsTool,
414447
ListThreadPullRequestsTool,
415448
WatchPullRequestTool,
416449
UnwatchPullRequestTool,
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"claudeSystemAppendBytes": 5129,
33
"codexAdditionalContextBytes": 6859,
4-
"mcpToolListJsonBytes": 46109
4+
"mcpToolListJsonBytes": 46596
55
}

‎evals/mcp-tool-use/cases/pull-requests.ndjson‎

Lines changed: 4 additions & 0 deletions
Large diffs are not rendered by default.

‎evals/mcp-tool-use/run.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ it("passes a good run and names every rule a bad run breaks", () => {
116116
textMust: ["t3-thread://v2/"],
117117
textMustNot: ["Paste .*token"],
118118
linked: ["~/pull/124"],
119+
linkedNumbers: [124],
119120
};
120121
const good: SampleRun = {
121122
calls: [
@@ -158,6 +159,7 @@ it("passes a good run and names every rule a bad run breaks", () => {
158159
"textMust /t3-thread://v2//",
159160
"textMustNot /Paste .*token/",
160161
"linked ~/pull/124",
162+
"linkedNumbers",
161163
]);
162164
});
163165

‎evals/mcp-tool-use/run.ts‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,12 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
3535
import { taskPrompt } from "../../apps/server/src/mcp/delegatedTaskModes.ts";
3636
import * as McpInvocationContext from "../../apps/server/src/mcp/McpInvocationContext.ts";
3737
import { advertisedJsonSchema } from "../../apps/server/src/mcp/advertisedJsonSchema.ts";
38-
import { EnvironmentId, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, ThreadId } from "@t3tools/contracts";
38+
import {
39+
EnvironmentId,
40+
ORCHESTRATOR_MCP_RUNNING_TASK_NEXT,
41+
PullRequestState,
42+
ThreadId,
43+
} from "@t3tools/contracts";
3944
import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
4045
import { formatThreadLink } from "@t3tools/shared/threadLinks";
4146
import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts";
@@ -166,6 +171,8 @@ const McpToolUseExpect = Schema.Struct({
166171
textMustNot: Schema.optional(Schema.Array(Schema.String)),
167172
/** Each entry matches a PR URL linked at the end, as `args` values match. */
168173
linked: Schema.optional(Schema.Array(Schema.String)),
174+
/** The PR numbers linked at the end, exactly. */
175+
linkedNumbers: Schema.optional(Schema.Array(Schema.Number)),
169176
/** Device manager checks: child briefs, simulator UI over the shell, failures, recordings. */
170177
device: Schema.optional(DeviceExpect),
171178
});
@@ -210,6 +217,12 @@ const McpToolUseWorld = Schema.StructWithRest(
210217
deviceInvalidCapture: Schema.optional(Schema.Boolean),
211218
/** Devices another thread's agent-device session holds, by device id: that thread's id. */
212219
deviceOwners: Schema.optional(Schema.Record(Schema.String, Schema.String)),
220+
/** PRs already linked to the thread, with the state T3 last saw. */
221+
linkedPullRequests: Schema.optional(
222+
Schema.Array(
223+
Schema.Struct({ number: Schema.Number, state: PullRequestState, title: Schema.String }),
224+
),
225+
),
213226
}),
214227
Rest,
215228
);
@@ -731,11 +744,16 @@ export const makeSample = (testCase: McpToolUseCase, base: Base): Sample => {
731744
const prior = testCase.setup.priorTurns ?? [];
732745
const priorCalls = prior.flatMap((turn) => turn.toolCalls ?? []);
733746
const repo = testCase.setup.world?.repo ?? "acme/app";
734-
const urls = priorCalls.flatMap((call) =>
735-
["link_pull_request", "watch_pull_request"].includes(call.tool) && isRecord(call.input)
736-
? [pullRequest(repo, call.input).url]
737-
: [],
738-
);
747+
const urls = [
748+
...(testCase.setup.world?.linkedPullRequests ?? []).map(
749+
({ number }) => pullRequest(repo, { number }).url,
750+
),
751+
...priorCalls.flatMap((call) =>
752+
["link_pull_request", "watch_pull_request"].includes(call.tool) && isRecord(call.input)
753+
? [pullRequest(repo, call.input).url]
754+
: [],
755+
),
756+
];
739757
const taskNumbers = [...valueText(prior).matchAll(/task-(\d+)/g)].map((match) =>
740758
Number(match[1]),
741759
);
@@ -952,6 +970,15 @@ const pullRequest = (repo: string, input: Readonly<Record<string, unknown>>) =>
952970
};
953971
};
954972

973+
/** A linked PR as `list_thread_pull_requests` shows it. Links made in the sample are open. */
974+
const linkedEntry = (sample: Sample, url: string) => {
975+
const pr = pullRequest(sample.repo, { url });
976+
const seeded = sample.testCase.setup.world?.linkedPullRequests?.find(
977+
({ number }) => number === pr.number && pr.repository === sample.repo,
978+
);
979+
return { ...pr, state: seeded?.state ?? "open", title: seeded?.title ?? null };
980+
};
981+
955982
/** A believable T3 result for a tool the case does not mock. */
956983
const t3Default = (sample: Sample, name: string, input: Readonly<Record<string, unknown>>) => {
957984
const pr = () => pullRequest(sample.repo, input);
@@ -1006,6 +1033,24 @@ const t3Default = (sample: Sample, name: string, input: Readonly<Record<string,
10061033
}
10071034
case "unlink_pull_request":
10081035
return { ...pr(), wasLinked: sample.linked.delete(pr().url) };
1036+
case "unlink_pull_requests": {
1037+
const states = Array.isArray(input.states) ? input.states : [];
1038+
const unlinked = [...sample.linked]
1039+
.map((url) => linkedEntry(sample, url))
1040+
.filter((entry) => states.includes(entry.state));
1041+
for (const { url } of unlinked) sample.linked.delete(url);
1042+
const groups = Map.groupBy(unlinked, (entry) => `${entry.repository}/${entry.state}`);
1043+
return {
1044+
unlinked: [...groups.values()].map((entries) => ({
1045+
host: "github.com",
1046+
repository: entries[0]!.repository,
1047+
state: entries[0]!.state,
1048+
numbers: entries.map((entry) => entry.number),
1049+
})),
1050+
unlinkedCount: unlinked.length,
1051+
remaining: sample.linked.size,
1052+
};
1053+
}
10091054
case "watch_pull_request":
10101055
sample.linked.add(pr().url);
10111056
return { ...pr(), watching: true, wasWatching: false };
@@ -1014,10 +1059,9 @@ const t3Default = (sample: Sample, name: string, input: Readonly<Record<string,
10141059
case "list_thread_pull_requests":
10151060
return {
10161061
pullRequests: [...sample.linked].map((url) => ({
1017-
...pullRequest(sample.repo, { url }),
1062+
...linkedEntry(sample, url),
10181063
source: "agent",
10191064
watching: false,
1020-
state: "open",
10211065
})),
10221066
chains: [],
10231067
};
@@ -1403,6 +1447,11 @@ export const gradeSample = (expect: McpToolUseCase["expect"], run: SampleRun) =>
14031447
for (const p of expect.textMustNot ?? []) add(`textMustNot /${p}/`, !test(p, run.text));
14041448
const isLinked = (url: string) => (run.linked ?? []).some((at) => matches(url, at));
14051449
for (const url of expect.linked ?? []) add(`linked ${url}`, isLinked(url));
1450+
if (expect.linkedNumbers !== undefined) {
1451+
const numbers = (run.linked ?? []).map((url) => Number(/(\d+)\/?$/.exec(url)?.[1]));
1452+
const exact = valueText(numbers.toSorted((a, b) => a - b));
1453+
add("linkedNumbers", exact === valueText(expect.linkedNumbers.toSorted((a, b) => a - b)));
1454+
}
14061455
checks.push(...gradeDevice(expect.device, run));
14071456
return checks;
14081457
};

‎packages/client-runtime/src/t3ToolSummary.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ describe("summarizeT3ToolCalls", () => {
3535
).toBe("Sent 2 messages to 1 thread");
3636
});
3737

38+
it("counts the pull requests a batch unlink removed", () => {
39+
const batch = completed({ states: ["merged"] }, { unlinkedCount: 2 });
40+
expect(summarizeT3ToolCalls("unlink-pr", [batch, completed({ number: 3 })]).label).toBe(
41+
"Unlinked 3 pull requests",
42+
);
43+
const uncounted = completed({ states: ["merged"] }, { isError: false });
44+
expect(summarizeT3ToolCalls("unlink-pr", [uncounted]).label).toBe("Unlinked pull requests");
45+
});
46+
3847
it("excludes failed and unfinished sends even if the provider reports completed", () => {
3948
const calls: T3ToolSummaryCall[] = [
4049
completed({ threadId: "success" }, { messageId: "ok", threadId: "success" }),

‎packages/client-runtime/src/t3ToolSummary.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -391,9 +391,19 @@ export function summarizeT3ToolCalls(
391391
case "link-pr":
392392
label = phrase("Linked", "link", quantity(selected.length, "pull request"));
393393
break;
394-
case "unlink-pr":
395-
label = phrase("Unlinked", "unlink", quantity(selected.length, "pull request"));
394+
case "unlink-pr": {
395+
let count = 0;
396+
let countKnown = true;
397+
for (const call of selected) {
398+
if (typeof call.output?.unlinkedCount === "number") count += call.output.unlinkedCount;
399+
// A batch result too large to compact loses its count, so the label drops the number.
400+
else if (Array.isArray(call.input?.states)) countKnown = false;
401+
else count += 1;
402+
}
403+
const object = countKnown ? quantity(count, "pull request") : "pull requests";
404+
label = phrase("Unlinked", "unlink", object);
396405
break;
406+
}
397407
case "watch-pr":
398408
label = phrase("Watching", "watch", quantity(selected.length, "pull request"));
399409
break;

‎packages/shared/src/t3McpToolPresentation.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
9999
"unlink-pr",
100100
"pull-request",
101101
),
102+
unlink_pull_requests: tool(
103+
["Unlink", "Unlinking", "Unlinked", "pull requests by state"],
104+
"unlink-pr",
105+
"pull-request",
106+
),
102107
list_thread_pull_requests: tool(
103108
["Check", "Checking", "Checked", "linked pull requests"],
104109
"list-prs",

0 commit comments

Comments
 (0)