Skip to content

Commit 44f977f

Browse files
maria-rcksjuliusmarmingeclaude
authored
feat(server): let MCP agents inspect thread diffs and respond to approvals (#15464)
Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 5b15a64 commit 44f977f

20 files changed

Lines changed: 685 additions & 61 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1745,6 +1745,21 @@ describe("orchestrator MCP toolkit", () => {
17451745
result: delegatedResult,
17461746
});
17471747
const child = yield* orchestrator.getThreadProjection(delegated.childThreadId);
1748+
const organizeChild = (action: string) =>
1749+
invoke("t3_thread_organize", { threadId: delegated.childThreadId, action });
1750+
expect((yield* organizeChild("mark_unread")).isError).toBe(false);
1751+
const unread = yield* orchestrator.getThreadShell(delegated.childThreadId);
1752+
expect(unread?.lastVisitedAt).toEqual(
1753+
DateTime.subtract(child.runs.at(-1)!.completedAt!, { milliseconds: 1 }),
1754+
);
1755+
expect((yield* organizeChild("mark_read")).isError).toBe(false);
1756+
expect(
1757+
(yield* orchestrator.getThreadShell(delegated.childThreadId))?.lastVisitedAt,
1758+
).toEqual(unread?.updatedAt);
1759+
expect((yield* organizeChild("mark_unread")).isError).toBe(false);
1760+
expect(
1761+
(yield* orchestrator.getThreadShell(delegated.childThreadId))?.lastVisitedAt,
1762+
).toEqual(unread?.lastVisitedAt);
17481763
expect(child.thread.lineage).toEqual({
17491764
parentThreadId,
17501765
relationshipToParent: "subagent",

‎apps/server/src/mcp/WorktreeMcpService.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
3131
import * as ProjectService from "../project/ProjectService.ts";
3232
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
33+
import * as ReviewService from "../review/ReviewService.ts";
3334
import * as ServerSettings from "../serverSettings.ts";
3435
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
3536
import type * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -291,6 +292,7 @@ const makeHarness = (options: HarnessOptions = {}) => {
291292
const layer = WorktreeMcpService.layer.pipe(
292293
Layer.provide(
293294
Layer.mergeAll(
295+
Layer.mock(ReviewService.ReviewService)({}),
294296
Layer.mock(ThreadManagementService.ThreadManagementService)({
295297
dispatch,
296298
getThreadRecords,

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

Lines changed: 103 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import {
22
CommandId,
33
MessageId,
44
type ProjectId,
5+
OrchestratorMcpFailure,
6+
type ReviewDiffFileStat,
7+
type ReviewDiffPreviewSourceKind,
8+
type ThreadId,
59
WorktreeMcpFailure,
610
type WorktreeMcpContinuationStatus,
711
type WorktreeMcpHandoffInput,
@@ -20,19 +24,46 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts";
2024
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
2125
import * as ProjectService from "../project/ProjectService.ts";
2226
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
27+
import * as ReviewService from "../review/ReviewService.ts";
2328
import * as ServerSettings from "../serverSettings.ts";
2429
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
25-
import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
30+
import * as McpInvocationContext from "./McpInvocationContext.ts";
31+
import { readThread, unavailable } from "./threadAccess.ts";
32+
33+
const MAX_DIFF_FILES = 500;
2634

2735
export class WorktreeMcpService extends Context.Service<
2836
WorktreeMcpService,
2937
{
38+
readonly getThreadDiff: (
39+
scope: McpInvocationContext.McpInvocationScope,
40+
input: {
41+
readonly threadId?: ThreadId | undefined;
42+
readonly baseRef?: string | undefined;
43+
readonly source?: ReviewDiffPreviewSourceKind | undefined;
44+
readonly maxCharacters?: number | undefined;
45+
},
46+
) => Effect.Effect<
47+
{
48+
readonly threadId: ThreadId;
49+
readonly cwd: string;
50+
readonly sources: ReadonlyArray<{
51+
readonly kind: ReviewDiffPreviewSourceKind;
52+
readonly baseRef: string | null;
53+
readonly headRef: string | null;
54+
readonly files: ReadonlyArray<ReviewDiffFileStat> | null;
55+
readonly diff: string;
56+
readonly truncated: boolean;
57+
}>;
58+
},
59+
OrchestratorMcpFailure
60+
>;
3061
readonly handoff: (
31-
scope: McpInvocationScope,
62+
scope: McpInvocationContext.McpInvocationScope,
3263
input: WorktreeMcpHandoffInput,
3364
) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
3465
readonly status: (
35-
scope: McpInvocationScope,
66+
scope: McpInvocationContext.McpInvocationScope,
3667
) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
3768
}
3869
>()("t3/mcp/WorktreeMcpService") {}
@@ -56,36 +87,93 @@ const asOperationFailed = (prefix: string) =>
5687

5788
const make = Effect.gen(function* () {
5889
const crypto = yield* Crypto.Crypto;
90+
const review = yield* ReviewService.ReviewService;
5991
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
6092
const projects = yield* ProjectService.ProjectService;
6193
const serverSettings = yield* ServerSettings.ServerSettingsService;
6294
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
6395
const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
6496
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
6597

98+
const getThreadDiff: WorktreeMcpService["Service"]["getThreadDiff"] = Effect.fn(
99+
"WorktreeMcpService.getThreadDiff",
100+
)(function* (scope, input) {
101+
const {
102+
projection: { thread },
103+
} = yield* readThread(input.threadId).pipe(
104+
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
105+
Effect.provideService(ThreadManagementService.ThreadManagementService, threadManagement),
106+
);
107+
const project = yield* projects.getById(thread.projectId).pipe(Effect.mapError(unavailable));
108+
if (Option.isNone(project))
109+
return yield* new OrchestratorMcpFailure({
110+
code: "invalid_request",
111+
message: "The project was not found.",
112+
});
113+
const preview = yield* review
114+
.getDiffPreview({
115+
cwd: thread.worktreePath ?? project.value.workspaceRoot,
116+
...(input.baseRef === undefined ? {} : { baseRef: input.baseRef }),
117+
...(input.source === undefined ? {} : { sourceKind: input.source }),
118+
})
119+
.pipe(
120+
Effect.mapError((error) =>
121+
error._tag === "VcsRepositoryDetectionError" ||
122+
error._tag === "VcsUnsupportedOperationError" ||
123+
(error._tag === "GitCommandError" &&
124+
input.baseRef !== undefined &&
125+
error.operation === "GitVcsDriver.resolveReviewMergeBase" &&
126+
error.exitCode !== undefined)
127+
? new OrchestratorMcpFailure({ code: "invalid_request", message: error.detail })
128+
: unavailable(),
129+
),
130+
);
131+
if (preview.sources.length === 0)
132+
return yield* new OrchestratorMcpFailure({
133+
code: "invalid_request",
134+
message: "The thread's checkout is not a repository.",
135+
});
136+
const maxCharacters = input.maxCharacters ?? 20_000;
137+
return {
138+
threadId: thread.id,
139+
cwd: preview.cwd,
140+
sources: preview.sources.map((source) => ({
141+
kind: source.kind,
142+
baseRef: source.baseRef,
143+
headRef: source.headRef,
144+
files: source.files?.slice(0, MAX_DIFF_FILES) ?? null,
145+
diff: source.diff.slice(0, maxCharacters),
146+
truncated:
147+
source.truncated ||
148+
source.diff.length > maxCharacters ||
149+
(source.files?.length ?? 0) > MAX_DIFF_FILES,
150+
})),
151+
};
152+
});
153+
66154
// Serializes handoffs per thread: two concurrent calls could otherwise both
67155
// pass the worktreePath === null check and each create a worktree, leaving
68156
// one untracked on disk.
69157
const handoffThreadsInFlight = new Set<string>();
70158

71-
const requireThreadScope = (scope: McpInvocationScope) =>
159+
const requireThreadScope = (scope: McpInvocationContext.McpInvocationScope) =>
72160
scope.thread === undefined
73161
? Effect.fail(
74162
failure(
75163
"thread_credential_required",
76164
"Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
77165
),
78166
)
79-
: Effect.succeed(scope as McpThreadInvocationScope);
167+
: Effect.succeed(scope as McpInvocationContext.McpThreadInvocationScope);
80168

81-
const requireCapability = (scope: McpInvocationScope) =>
169+
const requireCapability = (scope: McpInvocationContext.McpInvocationScope) =>
82170
scope.capabilities.has("worktree")
83171
? Effect.void
84172
: Effect.fail(
85173
failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
86174
);
87175

88-
const loadThread = (scope: McpThreadInvocationScope) =>
176+
const loadThread = (scope: McpInvocationContext.McpThreadInvocationScope) =>
89177
threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
90178
Effect.mapError((error) =>
91179
error._tag === "OrchestratorProjectionError"
@@ -101,7 +189,10 @@ const make = Effect.gen(function* () {
101189
),
102190
);
103191

104-
const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
192+
const loadProject = (
193+
scope: McpInvocationContext.McpThreadInvocationScope,
194+
projectId: ProjectId,
195+
) =>
105196
projects.getById(projectId).pipe(
106197
asOperationFailed(`Unable to read project ${projectId}`),
107198
Effect.flatMap(
@@ -123,7 +214,7 @@ const make = Effect.gen(function* () {
123214
asOperationFailed("Unable to read server settings"),
124215
);
125216

126-
const handoffIds = (scope: McpThreadInvocationScope) =>
217+
const handoffIds = (scope: McpInvocationContext.McpThreadInvocationScope) =>
127218
crypto.randomUUIDv4().pipe(
128219
Effect.map((uuid) => {
129220
const part = (kind: string, operation: string) =>
@@ -140,7 +231,7 @@ const make = Effect.gen(function* () {
140231
);
141232

142233
const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
143-
scope: McpThreadInvocationScope,
234+
scope: McpInvocationContext.McpThreadInvocationScope,
144235
input: WorktreeMcpHandoffInput,
145236
) {
146237
const alreadyInWorktree = (worktreePath: string) =>
@@ -447,13 +538,14 @@ const make = Effect.gen(function* () {
447538
},
448539
);
449540

450-
return WorktreeMcpService.of({ handoff, status });
541+
return WorktreeMcpService.of({ getThreadDiff, handoff, status });
451542
});
452543

453544
export const layer: Layer.Layer<
454545
WorktreeMcpService,
455546
never,
456547
| Crypto.Crypto
548+
| ReviewService.ReviewService
457549
| ThreadManagementService.ThreadManagementService
458550
| ProjectService.ProjectService
459551
| ServerSettings.ServerSettingsService

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ export const readThread = Effect.fn("mcp.readThread")(function* <
163163
}
164164
const projection = yield* context.threads
165165
.getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
166-
turnItemTypes: ["user_input_request"],
166+
turnItemTypes: ["user_input_request", "approval_request"],
167167
})
168168
.pipe(
169169
Effect.mapError((error) =>

0 commit comments

Comments
 (0)