Skip to content

Commit 918219b

Browse files
fix(server): thread reads preview linked PRs and list_thread_pull_requests pages
t3_thread_read and t3_thread_list returned every open linked PR, and list_thread_pull_requests returned every link. A thread with hundreds of linked PRs pushed each result past MCP clients' output limit. Thread results now preview up to 5 open PRs, watched first, then newest, with openPullRequestCount. list_thread_pull_requests takes states, cursor and limit (max 50) and returns nextCursor and total; chains cover the stacks on the page. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2755a95 commit 918219b

9 files changed

Lines changed: 110 additions & 32 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.activity.test.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov
130130
number,
131131
url: `https://github.com/acme/web/pull/${number}`,
132132
source: "agent",
133-
linkedAt: "2026-08-04T11:00:00.000Z",
133+
linkedAt: `2026-08-04T11:0${number}:00.000Z`,
134134
snapshot: { state },
135135
stack: null,
136136
...(watched
@@ -157,7 +157,11 @@ it("readThread preserves caller access errors and prefers activity-run status ov
157157
instanceId: parentInstanceId,
158158
model: "gpt-5.4",
159159
}),
160-
pullRequests: [pullRequestLink(1, "merged", false), pullRequestLink(2, "open", true)],
160+
pullRequests: [
161+
pullRequestLink(1, "merged", false),
162+
pullRequestLink(2, "open", true),
163+
...[3, 4, 5, 6, 7, 8].map((number) => pullRequestLink(number, "open", false)),
164+
],
161165
},
162166
runs: [
163167
makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
@@ -243,8 +247,10 @@ it("readThread preserves caller access errors and prefers activity-run status ov
243247
{ taskId: "task-subagent", kind: "subagent", childThreadId },
244248
]);
245249
// Every page read must not repeat each linked PR, and an open PR shows whether it is watched.
250+
// A thread with many open PRs previews a few, watched first, then newest.
246251
const listed = result.thread.pullRequests ?? [];
247-
expect(listed.map((link) => link.number)).not.toContain(1);
252+
expect(listed.map((link) => link.number)).toEqual([2, 8, 7, 6, 5]);
253+
expect(result.thread.openPullRequestCount).toBe(7);
248254
expect(listed.find((link) => link.number === 2)).toMatchObject({
249255
watching: true,
250256
watchStartedAt: "2026-08-04T11:30:00.000Z",
@@ -254,7 +260,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov
254260
afterPosition: 0,
255261
});
256262
expect(laterPage.thread.pullRequests).toBeUndefined();
257-
expect(laterPage.thread.pullRequestCount).toBe(2);
263+
expect(laterPage.thread.pullRequestCount).toBe(8);
258264

259265
callerUnavailable = true;
260266
const denied = yield* service

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3too
7070
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
7171
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
7272
import { formatThreadLink } from "@t3tools/shared/threadLinks";
73+
import { threadPullRequestUpdatedAtMs } from "@t3tools/shared/threadPullRequests";
7374
import {
7475
normalizeThreadPullRequestKey,
7576
visibleThreadPullRequests,
@@ -146,6 +147,7 @@ const DEFAULT_THREAD_LIST_LIMIT = 10;
146147
const DEFAULT_THREAD_READ_LIMIT = 10;
147148
const DEFAULT_THREAD_RUN_LIMIT = 10;
148149
const DEFAULT_THREAD_ITEM_MAX_CHARS = 500;
150+
const THREAD_PULL_REQUEST_PREVIEW_LIMIT = 5;
149151
// Claude Code saves MCP results over ~25k tokens to a file instead of showing them. Thread JSON
150152
// runs about 2 chars per token, so a read stops adding items here and reports the rest as more.
151153
const THREAD_READ_BUDGET_CHARS = 30_000;
@@ -833,12 +835,23 @@ function threadBackgroundWork(
833835
function threadPullRequests(
834836
links: OrchestrationV2ThreadShell["pullRequests"],
835837
includeLinks = true,
836-
): Pick<OrchestratorMcpThreadListItem, "pullRequests" | "pullRequestCount"> {
838+
): Pick<
839+
OrchestratorMcpThreadListItem,
840+
"pullRequests" | "pullRequestCount" | "openPullRequestCount"
841+
> {
837842
const visible = visibleThreadPullRequests(links ?? []);
838843
if (!includeLinks) return { pullRequestCount: visible.length };
844+
const open = visible.filter(
845+
(link) => link.snapshot?.state !== "merged" && link.snapshot?.state !== "closed",
846+
);
839847
return {
840-
pullRequests: visible
841-
.filter((link) => link.snapshot?.state !== "merged" && link.snapshot?.state !== "closed")
848+
pullRequests: open
849+
.toSorted(
850+
(left, right) =>
851+
Number(right.watch !== undefined) - Number(left.watch !== undefined) ||
852+
threadPullRequestUpdatedAtMs(right) - threadPullRequestUpdatedAtMs(left),
853+
)
854+
.slice(0, THREAD_PULL_REQUEST_PREVIEW_LIMIT)
842855
.map((link) => ({
843856
host: normalizeThreadPullRequestKey(link).host,
844857
repository: link.repository,
@@ -850,6 +863,7 @@ function threadPullRequests(
850863
watchStartedAt: link.watch?.startedAt ?? null,
851864
})),
852865
pullRequestCount: visible.length,
866+
openPullRequestCount: open.length,
853867
};
854868
}
855869

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,29 @@ describe("listThreadPullRequests", () => {
608608
]);
609609
expect(result.chains).toEqual([{ kind: "derived", numbers: [1, 2, 3] }]);
610610
});
611+
612+
it("pages the links in the requested states, with each page's stacks whole", () => {
613+
const merged = makeLink(5, { headBranch: "feat-e" });
614+
const thread = {
615+
pullRequests: [
616+
makeLink(1, { headBranch: "feat-a" }),
617+
makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a" }),
618+
makeLink(4),
619+
{ ...merged, snapshot: { ...merged.snapshot!, state: "merged" as const } },
620+
makeLink(6, { headBranch: "feat-f", baseBranch: "feat-b" }),
621+
],
622+
};
623+
const first = listThreadPullRequests(thread, { states: ["open"], limit: 1 });
624+
expect(first.pullRequests.map((entry) => entry.number)).toEqual([1]);
625+
expect(first.chains).toEqual([{ kind: "derived", numbers: [1, 2, 6] }]);
626+
expect([first.nextCursor, first.total]).toEqual([1, 3]);
627+
const last = listThreadPullRequests(thread, { states: ["open"], cursor: 1, limit: 5 });
628+
expect(last.pullRequests.map((entry) => entry.number)).toEqual([2, 6]);
629+
expect(last.nextCursor).toBeNull();
630+
expect(listThreadPullRequests(thread, { states: ["merged"] }).chains).toEqual([
631+
{ kind: "derived", numbers: [5] },
632+
]);
633+
});
611634
});
612635

613636
describe("pull request guide tools", () => {

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

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";
2929
import * as McpToolAccess from "../../McpToolAccess.ts";
3030
import { threadNotFound } from "../../threadAccess.ts";
3131
import {
32+
type ListThreadPullRequestsInput,
3233
type ListThreadPullRequestsResult,
3334
PullRequestLinkFailedError,
3435
PullRequestUnlinkFailedError,
@@ -72,18 +73,32 @@ function entryOf(
7273
};
7374
}
7475

76+
const DEFAULT_PULL_REQUEST_LIST_LIMIT = 50;
77+
7578
export function listThreadPullRequests(
7679
thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
80+
input: Pick<ListThreadPullRequestsInput, "states" | "cursor" | "limit"> = {},
7781
): ListThreadPullRequestsResult {
7882
const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
83+
const states = input.states === undefined ? undefined : new Set(input.states);
84+
const matching = visibleThreadPullRequests(thread.pullRequests ?? []).filter(
85+
(link) =>
86+
states === undefined ||
87+
(link.snapshot?.state !== undefined && states.has(link.snapshot.state)),
88+
);
89+
const cursor = input.cursor ?? 0;
90+
const page = matching.slice(cursor, cursor + (input.limit ?? DEFAULT_PULL_REQUEST_LIST_LIMIT));
91+
const pageKeys = new Set(page.map(threadPullRequestKeyOf));
7992
return {
80-
pullRequests: visibleThreadPullRequests(thread.pullRequests ?? []).map((link) =>
81-
entryOf(link, chains),
82-
),
83-
chains: chains.map((chain) => ({
84-
kind: chain.kind,
85-
numbers: chain.layers.map((layer) => layer.number),
86-
})),
93+
pullRequests: page.map((link) => entryOf(link, chains)),
94+
chains: chains
95+
.filter((chain) => chain.layers.some((layer) => pageKeys.has(threadPullRequestKeyOf(layer))))
96+
.map((chain) => ({
97+
kind: chain.kind,
98+
numbers: chain.layers.map((layer) => layer.number),
99+
})),
100+
nextCursor: cursor + page.length < matching.length ? cursor + page.length : null,
101+
total: matching.length,
87102
};
88103
}
89104

@@ -407,7 +422,7 @@ const make = Effect.gen(function* () {
407422
),
408423
list_thread_pull_requests: McpToolAccess.reads((input) =>
409424
requireThread(PullRequestListFailedError, input.threadId).pipe(
410-
Effect.map(listThreadPullRequests),
425+
Effect.map((thread) => listThreadPullRequests(thread, input)),
411426
),
412427
),
413428
watch_pull_request: writesThread((input) => setWatching(input, true)),

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

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import {
2+
clampedPositiveInt,
23
McpCapabilityUnavailableError,
4+
NonNegativeInt,
35
OrchestratorMcpEnvironmentTarget,
46
OrchestratorMcpFailure,
57
PositiveInt,
@@ -227,15 +229,28 @@ export const ThreadPullRequestEntry = Schema.Struct({
227229
});
228230
export type ThreadPullRequestEntry = typeof ThreadPullRequestEntry.Type;
229231

232+
export const ListThreadPullRequestsInput = Schema.Struct({
233+
environmentId: OrchestratorMcpEnvironmentTarget,
234+
threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
235+
states: Schema.optional(Schema.Array(PullRequestState).check(Schema.isMinLength(1))),
236+
cursor: Schema.optional(NonNegativeInt),
237+
limit: Schema.optional(clampedPositiveInt(50)).annotate({ description: "Max 50." }),
238+
});
239+
export type ListThreadPullRequestsInput = typeof ListThreadPullRequestsInput.Type;
240+
230241
export const ListThreadPullRequestsResult = Schema.Struct({
231242
pullRequests: Schema.Array(ThreadPullRequestEntry),
243+
/** Stacks with a pull request on this page, whole. */
232244
chains: Schema.Array(
233245
Schema.Struct({
234246
kind: Schema.Literals(["native", "derived"]),
235247
/** Bottom to top; each pull request comes before the ones built on it. */
236248
numbers: Schema.Array(Schema.Int),
237249
}),
238250
),
251+
nextCursor: Schema.NullOr(NonNegativeInt),
252+
/** Pull requests matching `states`, across all pages. */
253+
total: NonNegativeInt,
239254
});
240255
export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type;
241256

@@ -305,11 +320,8 @@ const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", {
305320

306321
const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
307322
description:
308-
"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.",
309-
parameters: Schema.Struct({
310-
environmentId: OrchestratorMcpEnvironmentTarget,
311-
threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
312-
}),
323+
"List PRs linked to a thread, with last known state and stack order (bottom to top). Page with `cursor=nextCursor`. Call only when you need that list. Never as an end-of-work check.",
324+
parameters: ListThreadPullRequestsInput,
313325
success: ListThreadPullRequestsResult,
314326
failure: PullRequestToolError,
315327
dependencies,
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"claudeSystemAppendBytes": 5597,
33
"codexAdditionalContextBytes": 7327,
4-
"mcpToolListJsonBytes": 48099
4+
"mcpToolListJsonBytes": 48332
55
}

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1302,15 +1302,21 @@ export const t3Default = (
13021302
return { ...pr(), watching: true, wasWatching: false };
13031303
case "unwatch_pull_request":
13041304
return { ...pr(), watching: false, wasWatching: true };
1305-
case "list_thread_pull_requests":
1305+
case "list_thread_pull_requests": {
1306+
const states = Array.isArray(input.states) ? input.states : undefined;
1307+
const matching = [...sample.linked]
1308+
.map((url) => ({ ...linkedEntry(sample, url), source: "agent", watching: false }))
1309+
.filter((entry) => states === undefined || states.includes(entry.state));
1310+
const cursor = typeof input.cursor === "number" ? input.cursor : 0;
1311+
const limit = Math.min(typeof input.limit === "number" ? input.limit : 50, 50);
1312+
const page = matching.slice(cursor, cursor + limit);
13061313
return {
1307-
pullRequests: [...sample.linked].map((url) => ({
1308-
...linkedEntry(sample, url),
1309-
source: "agent",
1310-
watching: false,
1311-
})),
1314+
pullRequests: page,
13121315
chains: [],
1316+
nextCursor: cursor + page.length < matching.length ? cursor + page.length : null,
1317+
total: matching.length,
13131318
};
1319+
}
13141320
case "t3_thread_read": {
13151321
const threadId = valueText(input.threadId);
13161322
const launched = sample.threads.get(threadId);

‎packages/contracts/src/orchestratorMcp.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -387,9 +387,10 @@ export const OrchestratorMcpThreadListItem = Schema.Struct({
387387
runtimeMode: RuntimeMode,
388388
interactionMode: ProviderInteractionMode,
389389
linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest),
390-
/** Linked pull requests not yet merged or closed; list_thread_pull_requests has all of them. */
390+
/** Up to 5 open linked pull requests, watched first; list_thread_pull_requests pages all of them. */
391391
pullRequests: Schema.optional(Schema.Array(OrchestratorMcpThreadPullRequest)),
392392
pullRequestCount: Schema.optional(NonNegativeInt),
393+
openPullRequestCount: Schema.optional(NonNegativeInt),
393394
settled: Schema.Boolean,
394395
settledAt: Schema.NullOr(IsoDateTime),
395396
snoozed: Schema.Boolean,
@@ -419,7 +420,7 @@ export type OrchestratorMcpThreadListResult = typeof OrchestratorMcpThreadListRe
419420
// Codex hides `minimum` and `maximum` from the model, so a value above the maximum clamps on
420421
// decode instead of failing the call; pagination returns the rest. Values below 1 still fail:
421422
// 0 asks for nothing, and answering it with one item would be a different request.
422-
const clampedPositiveInt = (maximum: number) =>
423+
export const clampedPositiveInt = (maximum: number) =>
423424
PositiveInt.pipe(
424425
Schema.decodeTo(
425426
PositiveInt.check(Schema.isLessThanOrEqualTo(maximum)),
@@ -461,9 +462,10 @@ export const OrchestratorMcpThreadDetail = Schema.Struct({
461462
runtimeMode: RuntimeMode,
462463
interactionMode: ProviderInteractionMode,
463464
linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest),
464-
/** Open linked pull requests, on the first page only; list_thread_pull_requests has all of them. */
465+
/** Up to 5 open linked pull requests, watched first, on the first page only; list_thread_pull_requests pages all of them. */
465466
pullRequests: Schema.optional(Schema.Array(OrchestratorMcpThreadPullRequest)),
466467
pullRequestCount: Schema.optional(NonNegativeInt),
468+
openPullRequestCount: Schema.optional(NonNegativeInt),
467469
titleRegeneration: Schema.NullOr(ThreadTitleRegeneration),
468470
lastTitleRegeneration: Schema.optional(Schema.NullOr(LastThreadTitleRegeneration)),
469471
branch: Schema.NullOr(Schema.String),

‎packages/shared/src/threadPullRequests.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ export function visibleThreadPullRequests(
77
return links.filter((link) => link.source !== "stack-dismissed");
88
}
99

10-
function latestUpdatedAt(link: ThreadPullRequestLink): number {
10+
export function threadPullRequestUpdatedAtMs(link: ThreadPullRequestLink): number {
1111
const value = link.snapshot?.updatedAt ?? link.linkedAt;
1212
const ms = Date.parse(value);
1313
return Number.isNaN(ms) ? 0 : ms;
@@ -41,7 +41,7 @@ export function threadSearchPullRequests(thread: {
4141
// Every pull request matches by number and link, but only the newest few
4242
// by title: a triage thread linked to dozens would match almost any word.
4343
const newestFirst = [...visibleThreadPullRequests(thread.pullRequests)].sort(
44-
(left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
44+
(left, right) => threadPullRequestUpdatedAtMs(right) - threadPullRequestUpdatedAtMs(left),
4545
);
4646
return branch.concat(
4747
newestFirst.map((link, index) =>

0 commit comments

Comments
 (0)