The best way to control Claude Code, Codex and more from any computer or phone
feat(server): let MCP agents inspect thread diffs and respond to approvals (#15464)
Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
maria committed
Oct 20, 2026 at 05:36 UTC
44f977f4e819c2355cb2f8c75b93547fb9815fec
20 files changed
+685
-61
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+15
@@ -1745,6 +1745,21 @@ describe("orchestrator MCP toolkit", () => {
1745
result: delegatedResult,
1746
});
1747
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);
1763
expect(child.thread.lineage).toEqual({
1764
parentThreadId,
1765
relationshipToParent: "subagent",
apps/server/src/mcp/WorktreeMcpService.test.ts
+2
@@ -30,6 +30,7 @@ import {
30
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
31
import * as ProjectService from "../project/ProjectService.ts";
32
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
33
+import * as ReviewService from "../review/ReviewService.ts";
34
import * as ServerSettings from "../serverSettings.ts";
35
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
36
import type * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -291,6 +292,7 @@ const makeHarness = (options: HarnessOptions = {}) => {
292
const layer = WorktreeMcpService.layer.pipe(
293
Layer.provide(
294
Layer.mergeAll(
295
+ Layer.mock(ReviewService.ReviewService)({}),
296
Layer.mock(ThreadManagementService.ThreadManagementService)({
297
dispatch,
298
getThreadRecords,
apps/server/src/mcp/WorktreeMcpService.ts
+103
-11
@@ -2,6 +2,10 @@ import {
2
CommandId,
3
MessageId,
4
type ProjectId,
5
+ OrchestratorMcpFailure,
6
+ type ReviewDiffFileStat,
7
+ type ReviewDiffPreviewSourceKind,
8
+ type ThreadId,
9
WorktreeMcpFailure,
10
type WorktreeMcpContinuationStatus,
11
type WorktreeMcpHandoffInput,
@@ -20,19 +24,46 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts";
24
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
25
import * as ProjectService from "../project/ProjectService.ts";
26
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
27
+import * as ReviewService from "../review/ReviewService.ts";
28
import * as ServerSettings from "../serverSettings.ts";
29
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;
34
35
export class WorktreeMcpService extends Context.Service<
36
WorktreeMcpService,
37
{
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
+ >;
61
readonly handoff: (
31
- scope: McpInvocationScope,
62
+ scope: McpInvocationContext.McpInvocationScope,
63
input: WorktreeMcpHandoffInput,
64
) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
65
readonly status: (
35
- scope: McpInvocationScope,
66
+ scope: McpInvocationContext.McpInvocationScope,
67
) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
68
}
69
>()("t3/mcp/WorktreeMcpService") {}
@@ -56,6 +87,7 @@ const asOperationFailed = (prefix: string) =>
87
88
const make = Effect.gen(function* () {
89
const crypto = yield* Crypto.Crypto;
90
+ const review = yield* ReviewService.ReviewService;
91
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
92
const projects = yield* ProjectService.ProjectService;
93
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -63,12 +95,68 @@ const make = Effect.gen(function* () {
95
const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
96
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
97
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
+
154
// Serializes handoffs per thread: two concurrent calls could otherwise both
155
// pass the worktreePath === null check and each create a worktree, leaving
156
// one untracked on disk.
157
const handoffThreadsInFlight = new Set<string>();
158
71
- const requireThreadScope = (scope: McpInvocationScope) =>
159
+ const requireThreadScope = (scope: McpInvocationContext.McpInvocationScope) =>
160
scope.thread === undefined
161
? Effect.fail(
162
failure(
@@ -76,16 +164,16 @@ const make = Effect.gen(function* () {
164
"Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
165
),
166
)
79
- : Effect.succeed(scope as McpThreadInvocationScope);
167
+ : Effect.succeed(scope as McpInvocationContext.McpThreadInvocationScope);
168
81
- const requireCapability = (scope: McpInvocationScope) =>
169
+ const requireCapability = (scope: McpInvocationContext.McpInvocationScope) =>
170
scope.capabilities.has("worktree")
171
? Effect.void
172
: Effect.fail(
173
failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
174
);
175
88
- const loadThread = (scope: McpThreadInvocationScope) =>
176
+ const loadThread = (scope: McpInvocationContext.McpThreadInvocationScope) =>
177
threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
178
Effect.mapError((error) =>
179
error._tag === "OrchestratorProjectionError"
@@ -101,7 +189,10 @@ const make = Effect.gen(function* () {
189
),
190
);
191
104
- const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
192
+ const loadProject = (
193
+ scope: McpInvocationContext.McpThreadInvocationScope,
194
+ projectId: ProjectId,
195
+ ) =>
196
projects.getById(projectId).pipe(
197
asOperationFailed(`Unable to read project ${projectId}`),
198
Effect.flatMap(
@@ -123,7 +214,7 @@ const make = Effect.gen(function* () {
214
asOperationFailed("Unable to read server settings"),
215
);
216
126
- const handoffIds = (scope: McpThreadInvocationScope) =>
217
+ const handoffIds = (scope: McpInvocationContext.McpThreadInvocationScope) =>
218
crypto.randomUUIDv4().pipe(
219
Effect.map((uuid) => {
220
const part = (kind: string, operation: string) =>
@@ -140,7 +231,7 @@ const make = Effect.gen(function* () {
231
);
232
233
const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
143
- scope: McpThreadInvocationScope,
234
+ scope: McpInvocationContext.McpThreadInvocationScope,
235
input: WorktreeMcpHandoffInput,
236
) {
237
const alreadyInWorktree = (worktreePath: string) =>
@@ -447,13 +538,14 @@ const make = Effect.gen(function* () {
538
},
539
);
540
450
- return WorktreeMcpService.of({ handoff, status });
541
+ return WorktreeMcpService.of({ getThreadDiff, handoff, status });
542
});
543
544
export const layer: Layer.Layer<
545
WorktreeMcpService,
546
never,
547
| Crypto.Crypto
548
+ | ReviewService.ReviewService
549
| ThreadManagementService.ThreadManagementService
550
| ProjectService.ProjectService
551
| ServerSettings.ServerSettingsService
apps/server/src/mcp/threadAccess.ts
+1
-1
@@ -163,7 +163,7 @@ export const readThread = Effect.fn("mcp.readThread")(function* <
163
}
164
const projection = yield* context.threads
165
.getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
166
- turnItemTypes: ["user_input_request"],
166
+ turnItemTypes: ["user_input_request", "approval_request"],
167
})
168
.pipe(
169
Effect.mapError((error) =>
apps/server/src/mcp/toolkits/core.test.ts
+183
@@ -13,10 +13,13 @@ import {
13
ProviderDriverKind,
14
ProviderInstanceId,
15
RunId,
16
+ RuntimeRequestId,
17
ThreadId,
18
TurnItemId,
19
type OrchestrationV2ProjectedTurnItem,
20
type OrchestrationV2ThreadShell,
21
+ type OrchestrationV2RuntimeRequest,
22
+ type OrchestrationV2TurnItem,
23
} from "@t3tools/contracts";
24
import * as Deferred from "effect/Deferred";
25
import * as Effect from "effect/Effect";
@@ -619,6 +622,186 @@ it.effect("a client caller targets any thread within its ceiling and cannot act
622
),
623
);
624
625
+it.effect("lists, reads and resolves approvals with offered decisions and caller limits", () => {
626
+ const targetId = ThreadId.make("other-project-thread");
627
+ let target = McpToolAccessTestkit.liveThreadShell(targetId, { runtimeMode: "auto" });
628
+ const projection = {
629
+ ...McpToolAccessTestkit.idleThreadProjection(target),
630
+ runtimeRequests: [] as Array<OrchestrationV2RuntimeRequest>,
631
+ turnItems: [] as Array<OrchestrationV2TurnItem>,
632
+ };
633
+ const options = [
634
+ { decision: "accept" as const, label: "Allow" },
635
+ { decision: "decline" as const, label: "Deny" },
636
+ { decision: "cancel" as const, label: "Cancel" },
637
+ ];
638
+ for (const id of ["approve", "approve-client", "decline", "cancel", "question"]) {
639
+ const requestId = RuntimeRequestId.make(id);
640
+ projection.runtimeRequests.push({
641
+ id: requestId,
642
+ nodeId: NodeId.make("node:approval"),
643
+ providerTurnId: null,
644
+ nativeRequestRef: null,
645
+ kind: id === "question" ? "user_input" : "command",
646
+ status: "pending",
647
+ responseCapability: { type: "message" },
648
+ createdAt: target.updatedAt,
649
+ resolvedAt: null,
650
+ });
651
+ if (id !== "question") {
652
+ projection.turnItems.push({
653
+ id: TurnItemId.make(id),
654
+ threadId: targetId,
655
+ runId: null,
656
+ nodeId: null,
657
+ providerThreadId: null,
658
+ providerTurnId: null,
659
+ nativeItemRef: null,
660
+ parentItemId: null,
661
+ ordinal: projection.turnItems.length,
662
+ status: "running",
663
+ title: null,
664
+ startedAt: target.updatedAt,
665
+ completedAt: null,
666
+ updatedAt: target.updatedAt,
667
+ type: "approval_request",
668
+ requestId,
669
+ requestKind: "command",
670
+ prompt:
671
+ id === "approve-client" ? `${"🙂".repeat(3999)}🚀hidden warning` : "Run the command?",
672
+ ...(id === "approve-client" ? { appName: "Fixture app" } : {}),
673
+ options,
674
+ });
675
+ }
676
+ }
677
+ const responses: Array<string> = [];
678
+ let caller = McpToolAccessTestkit.liveThreadShell(threadId);
679
+ return Effect.gen(function* () {
680
+ const server = yield* McpServer.McpServer;
681
+ const call = (
682
+ name: string,
683
+ args: Record<string, unknown> = {},
684
+ invocation = clientScope("read-only"),
685
+ ) =>
686
+ server
687
+ .callTool({ name, arguments: { threadId: targetId, ...args } })
688
+ .pipe(
689
+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
690
+ Effect.provideService(McpSchema.McpServerClient, client),
691
+ );
692
+ expect((yield* call("t3_pending_request_list")).structuredContent).toEqual({
693
+ requestIds: ["question"],
694
+ requests: [
695
+ { requestId: "approve", kind: "command" },
696
+ { requestId: "approve-client", kind: "command" },
697
+ { requestId: "decline", kind: "command" },
698
+ { requestId: "cancel", kind: "command" },
699
+ { requestId: "question", kind: "user_input" },
700
+ ],
701
+ });
702
+ expect(
703
+ (yield* call("t3_pending_request_read", { requestId: "approve" })).structuredContent,
704
+ ).toEqual({ requestId: "approve", kind: "command", prompt: "Run the command?", options });
705
+
706
+ const clipped = (yield* call("t3_pending_request_read", { requestId: "approve-client" }))
707
+ .structuredContent;
708
+ expect(clipped).toEqual({
709
+ requestId: "approve-client",
710
+ kind: "command",
711
+ prompt: `${"🙂".repeat(3999)}🚀`,
712
+ promptTruncated: true,
713
+ appName: "Fixture app",
714
+ options,
715
+ });
716
+
717
+ const respond = (
718
+ requestId: string,
719
+ decision: string,
720
+ invocation: McpInvocationContext.McpInvocationScope,
721
+ ) => call("t3_pending_request_respond", { requestId, decision }, invocation);
722
+ expect(declaredFailure(yield* respond("approve", "accept", clientScope("auto")))).toMatchObject(
723
+ {
724
+ code: "capability_denied",
725
+ },
726
+ );
727
+ expect(
728
+ declaredFailure(yield* respond("decline", "decline", clientScope("read-only"))),
729
+ ).toMatchObject({
730
+ code: "capability_denied",
731
+ });
732
+ expect(
733
+ declaredFailure(yield* respond("approve", "acceptForSession", clientScope("full-access"))),
734
+ ).toMatchObject({
735
+ code: "invalid_request",
736
+ });
737
+ caller = { ...caller, interactionMode: "plan" };
738
+ target = { ...target, interactionMode: "plan" };
739
+ expect(declaredFailure(yield* respond("approve", "accept", scope))).toMatchObject({
740
+ code: "capability_denied",
741
+ });
742
+ target = { ...target, interactionMode: "default" };
743
+ expect(responses).toEqual([]);
744
+
745
+ expect((yield* respond("decline", "decline", clientScope("auto"))).isError).toBe(false);
746
+ expect((yield* respond("cancel", "cancel", clientScope("auto"))).isError).toBe(false);
747
+ caller = { ...caller, interactionMode: "default" };
748
+ expect((yield* respond("approve", "accept", scope)).isError).toBe(false);
749
+ expect((yield* respond("approve-client", "accept", clientScope("full-access"))).isError).toBe(
750
+ false,
751
+ );
752
+ expect(responses).toEqual(["decline", "cancel", "accept", "accept"]);
753
+ expect((yield* call("t3_pending_request_list")).structuredContent).toEqual({
754
+ requestIds: ["question"],
755
+ requests: [{ requestId: "question", kind: "user_input" }],
756
+ });
757
+ expect(
758
+ declaredFailure(yield* call("t3_pending_request_read", { requestId: "approve" })),
759
+ ).toMatchObject({
760
+ code: "invalid_request",
761
+ });
762
+ expect(
763
+ declaredFailure(yield* respond("approve", "accept", clientScope("full-access"))),
764
+ ).toMatchObject({
765
+ code: "invalid_request",
766
+ });
767
+ expect(responses).toHaveLength(4);
768
+ }).pipe(
769
+ Effect.provide(
770
+ layerThreadToolkit.pipe(
771
+ Layer.provideMerge(McpServer.McpServer.layer),
772
+ Layer.provide(NodeCrypto.layer),
773
+ Layer.provide(
774
+ Layer.mock(ThreadManagement.ThreadManagementService)({
775
+ getThreadShell: (id) => Effect.sync(() => (id === threadId ? caller : target)),
776
+ getProjectThreadRecords: (_input, _fields, query) =>
777
+ Effect.sync(() => ({
778
+ ...projection,
779
+ turnItems: projection.turnItems.filter((item) =>
780
+ query?.turnItemTypes?.includes(item.type),
781
+ ),
782
+ })),
783
+ dispatch: (command) =>
784
+ Effect.sync(() => {
785
+ if (command.type !== "runtime-request.respond" || command.decision === undefined)
786
+ throw new Error("Expected an approval response");
787
+ const request = projection.runtimeRequests.find(
788
+ (request) => request.id === command.requestId,
789
+ )!;
790
+ projection.runtimeRequests = projection.runtimeRequests.map((candidate) =>
791
+ candidate === request
792
+ ? { ...candidate, status: "resolved", decision: command.decision }
793
+ : candidate,
794
+ );
795
+ responses.push(command.decision);
796
+ return { sequence: responses.length, storedEvents: [] };
797
+ }),
798
+ }),
799
+ ),
800
+ ),
801
+ ),
802
+ );
803
+});
804
+
805
it.effect("a read-only client reads threads and is refused every write before it runs", () =>
806
Effect.gen(function* () {
807
const server = yield* McpServer.McpServer;
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+2
-2
@@ -65,7 +65,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
65
66
export const DelegateTaskTool = Tool.make("delegate_task", {
67
description:
68
- "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority; decisions remain with the child's existing approval holder, and pending request tools answer questions only. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
68
+ "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority. Use t3_pending_request_read to read the fresh request and t3_pending_request_respond with decision to respond; accepting needs a full-access/default caller, while declining or cancelling does not. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
69
parameters: OrchestratorMcpDelegateTaskInput,
70
success: OrchestratorMcpDelegateTaskResult,
71
failure: OrchestratorMcpFailure,
@@ -78,7 +78,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", {
78
79
const TaskStatusTool = Tool.make("task_status", {
80
description:
81
- "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Decisions remain with the child's existing approval holder. Reading a terminal result acknowledges its automatic parent delivery.",
81
+ "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Use t3_pending_request_read to read the fresh request and t3_pending_request_respond with decision to respond; accepting needs a full-access/default caller, while declining or cancelling does not. Reading a terminal result acknowledges its automatic parent delivery.",
82
parameters: OrchestratorMcpTaskStatusInput,
83
success: OrchestratorMcpDelegateTaskResult,
84
failure: OrchestratorMcpFailure,
apps/server/src/mcp/toolkits/thread/handlers.ts
+86
-15
@@ -6,13 +6,19 @@ import {
6
type RunId,
7
OrchestratorMcpFailure,
8
type OrchestrationV2Command,
9
+ type ProviderApprovalDecision,
10
+ ProviderRequestKind,
11
} from "@t3tools/contracts";
12
+import * as DateTime from "effect/DateTime";
13
import * as Effect from "effect/Effect";
14
+import * as Schema from "effect/Schema";
15
import { modelSelectionCommandType } from "@t3tools/shared/model";
16
17
import * as McpToolAccess from "../../McpToolAccess.ts";
18
import {
19
+ assertFullAccess,
20
dispatchFailure,
21
+ loadCaller,
22
newCommandId,
23
readCaller,
24
readThread,
@@ -49,24 +55,36 @@ const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
55
return { sequence: result.sequence };
56
});
57
52
-const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: {
58
+const isApprovalKind = Schema.is(ProviderRequestKind);
59
+const isPendingRequest = (request: OrchestrationV2ThreadProjection["runtimeRequests"][number]) =>
60
+ request.status === "pending" && (request.kind === "user_input" || isApprovalKind(request.kind));
61
+const DEFAULT_APPROVAL_DECISIONS: ReadonlyArray<ProviderApprovalDecision> = [
62
+ "cancel",
63
+ "decline",
64
+ "acceptForSession",
65
+ "accept",
66
+];
67
+
68
+const readPendingRequest = Effect.fn("mcp.readPendingRequest")(function* (input: {
69
threadId?: ThreadId | undefined;
70
requestId: RuntimeRequestId;
71
}) {
72
const context = yield* readThread(input.threadId, ["runtimeRequests", "turnItems"]);
73
const request = context.projection.runtimeRequests.find(
58
- (request) =>
59
- request.id === input.requestId &&
60
- request.kind === "user_input" &&
61
- request.status === "pending",
74
+ (request) => request.id === input.requestId && isPendingRequest(request),
75
);
76
const item = context.projection.turnItems.find(
64
- (item) => item.type === "user_input_request" && item.requestId === input.requestId,
77
+ (item) =>
78
+ (item.type === "user_input_request" || item.type === "approval_request") &&
79
+ item.requestId === input.requestId,
80
);
66
- if (request === undefined || item?.type !== "user_input_request")
81
+ if (
82
+ request === undefined ||
83
+ (request.kind === "user_input" && item?.type !== "user_input_request")
84
+ )
85
return yield* new OrchestratorMcpFailure({
86
code: "invalid_request",
69
- message: "The pending user-input request was not found.",
87
+ message: "The pending request was not found.",
88
});
89
return { ...context, request, item };
90
});
@@ -200,29 +218,75 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
218
t3_pending_request_list: McpToolAccess.reads((input) =>
219
Effect.gen(function* () {
220
const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
221
+ const requests = projection.runtimeRequests
222
+ .filter(isPendingRequest)
223
+ .map((request) => ({ requestId: request.id, kind: request.kind }));
224
return {
204
- requestIds: projection.runtimeRequests
205
- .filter((request) => request.kind === "user_input" && request.status === "pending")
206
- .map((request) => request.id),
225
+ requestIds: requests
226
+ .filter((request) => request.kind === "user_input")
227
+ .map((request) => request.requestId),
228
+ requests,
229
};
230
}),
231
),
232
t3_pending_request_read: McpToolAccess.reads((input) =>
233
Effect.gen(function* () {
212
- const { item } = yield* readQuestion(input);
213
- return { requestId: input.requestId, questions: item.questions };
234
+ const { request, item } = yield* readPendingRequest(input);
235
+ if (item?.type === "user_input_request")
236
+ return { requestId: input.requestId, kind: request.kind, questions: item.questions };
237
+ const approval = item?.type === "approval_request" ? item : undefined;
238
+ const prompt = approval?.prompt === undefined ? undefined : Array.from(approval.prompt);
239
+ return {
240
+ requestId: input.requestId,
241
+ kind: request.kind,
242
+ ...(prompt === undefined ? {} : { prompt: prompt.slice(0, 4000).join("") }),
243
+ ...(prompt !== undefined && prompt.length > 4000 ? { promptTruncated: true } : {}),
244
+ ...(approval?.appName === undefined ? {} : { appName: approval.appName }),
245
+ ...(approval?.options === undefined ? {} : { options: approval.options }),
246
+ };
247
}),
248
),
249
t3_pending_request_respond: writesThread((input) =>
250
Effect.gen(function* () {
218
- const { threads, projection } = yield* readQuestion(input);
251
+ const { threads, projection, request, item } = yield* readPendingRequest(input);
252
+ let response;
253
+ if (request.kind === "user_input") {
254
+ if (input.answers === undefined)
255
+ return yield* new OrchestratorMcpFailure({
256
+ code: "invalid_request",
257
+ message: "User questions need answers.",
258
+ });
259
+ response = { answers: input.answers };
260
+ } else {
261
+ const decision = input.decision;
262
+ if (decision === undefined)
263
+ return yield* new OrchestratorMcpFailure({
264
+ code: "invalid_request",
265
+ message: "Approvals need a decision.",
266
+ });
267
+ const offered =
268
+ item?.type === "approval_request"
269
+ ? item.options?.map((option) => option.decision)
270
+ : undefined;
271
+ if (!(offered ?? DEFAULT_APPROVAL_DECISIONS).includes(decision))
272
+ return yield* new OrchestratorMcpFailure({
273
+ code: "invalid_request",
274
+ message: "That decision was not offered for this approval.",
275
+ });
276
+ if (decision !== "decline" && decision !== "cancel")
277
+ yield* assertFullAccess(
278
+ yield* loadCaller(),
279
+ "Approving needs a live full-access/default thread or a full-access client.",
280
+ );
281
+ response = { decision };
282
+ }
283
const result = yield* threads
284
.dispatch({
285
type: "runtime-request.respond",
286
threadId: projection.thread.id,
287
commandId: yield* newCommandId(),
288
requestId: input.requestId,
225
- answers: input.answers,
289
+ ...response,
290
})
291
.pipe(Effect.mapError(dispatchFailure));
292
return { sequence: result.sequence };
@@ -314,6 +378,13 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
378
case "mark_unread":
379
command = { ...common, type: "thread.mark-unread" };
380
break;
381
+ case "mark_read":
382
+ command = {
383
+ ...common,
384
+ type: "thread.visit",
385
+ visitedAt: DateTime.formatIso(projection.thread.updatedAt),
386
+ };
387
+ break;
388
default:
389
command = { ...common, type: `thread.${input.action}` };
390
}
apps/server/src/mcp/toolkits/thread/tools.ts
+26
-7
@@ -11,6 +11,9 @@ import {
11
ProviderInteractionMode,
12
RuntimeRequestId,
13
ProviderUserInputAnswers,
14
+ ProviderApprovalDecision,
15
+ ProviderApprovalOption,
16
+ OrchestrationV2RuntimeRequest,
17
IsoDateTime,
18
OrchestratorMcpFailure,
19
OrchestrationV2DispatchCommandResult,
@@ -30,7 +33,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";
33
34
const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
35
description:
33
- "Pin, snooze, settle, archive, or mark a thread unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply. Settling this thread takes effect when your turn completes, returning settlesWhenTurnEnds=true; a turn that fails or is interrupted, or a queued message, leaves it active.",
36
+ "Pin, snooze, settle, archive, or mark a thread read or unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply. Settling this thread takes effect when your turn completes, returning settlesWhenTurnEnds=true; a turn that fails or is interrupted, or a queued message, leaves it active.",
37
parameters: Schema.Struct({
38
threadId: Schema.optional(ThreadId),
39
action: Schema.Literals([
@@ -42,6 +45,7 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
45
"unsettle",
46
"archive",
47
"unarchive",
48
+ "mark_read",
49
"mark_unread",
50
]),
51
snoozedUntil: Schema.optional(IsoDateTime),
@@ -144,23 +148,34 @@ const question = Schema.Struct({
148
initialAnswer: Schema.optional(Schema.String),
149
required: Schema.optional(Schema.Boolean),
150
});
151
+const pendingRequestKind = OrchestrationV2RuntimeRequest.fields.kind;
152
const pendingRequest = Schema.Struct({
153
requestId: RuntimeRequestId,
149
- questions: Schema.Array(question),
154
+ kind: pendingRequestKind,
155
+ questions: Schema.optional(Schema.Array(question)),
156
+ prompt: Schema.optional(Schema.String),
157
+ promptTruncated: Schema.optional(Schema.Boolean),
158
+ appName: Schema.optional(Schema.String),
159
+ options: Schema.optional(Schema.Array(ProviderApprovalOption)),
160
});
161
const PendingRequestListTool = Tool.make("t3_pending_request_list", {
162
...commandTool,
163
description:
154
- "List pending user questions in a thread. Omit threadId for this thread. Approval requests are not included.",
164
+ "List pending user questions and approval requests in a thread. Omit threadId for this thread. requestIds holds only the questions.",
165
parameters: Schema.Struct({ threadId: Schema.optional(ThreadId) }),
156
- success: Schema.Struct({ requestIds: Schema.Array(RuntimeRequestId) }),
166
+ success: Schema.Struct({
167
+ requestIds: Schema.Array(RuntimeRequestId),
168
+ requests: Schema.Array(
169
+ Schema.Struct({ requestId: RuntimeRequestId, kind: pendingRequestKind }),
170
+ ),
171
+ }),
172
})
173
.annotate(Tool.Readonly, true)
174
.annotate(Tool.Destructive, false);
175
const PendingRequestReadTool = Tool.make("t3_pending_request_read", {
176
...commandTool,
177
description:
163
- "Read a pending user question. Answer with t3_pending_request_respond; existing live or message response handling is used.",
178
+ "Read a pending user question or approval request. Respond with t3_pending_request_respond; existing live or message response handling is used.",
179
parameters: Schema.Struct(requestTarget),
180
success: pendingRequest,
181
})
@@ -169,8 +184,12 @@ const PendingRequestReadTool = Tool.make("t3_pending_request_read", {
184
const PendingRequestRespondTool = Tool.make("t3_pending_request_respond", {
185
...commandTool,
186
description:
172
- "Answer a pending user-input request using the existing runtime response command. This cannot approve a permission request.",
173
- parameters: Schema.Struct({ ...requestTarget, answers: ProviderUserInputAnswers }),
187
+ "Respond to a pending request using the existing runtime response command: answers for a user question, decision for an approval (one of its offered options, else cancel, decline, acceptForSession, or accept). Approving needs a full-access/default caller; declining or cancelling does not.",
188
+ parameters: Schema.Struct({
189
+ ...requestTarget,
190
+ answers: Schema.optional(ProviderUserInputAnswers),
191
+ decision: Schema.optional(ProviderApprovalDecision),
192
+ }),
193
})
194
.annotate(Tool.Destructive, true)
195
.annotate(Tool.OpenWorld, true);
apps/server/src/mcp/toolkits/worktree/handlers.ts
+7
@@ -36,6 +36,13 @@ const handlers = {
36
.pipe(Effect.mapError(unavailable));
37
}),
38
),
39
+ t3_thread_diff: McpToolAccess.reads((input) =>
40
+ Effect.gen(function* () {
41
+ const scope = yield* McpInvocationContext.McpInvocationContext;
42
+ const service = yield* WorktreeMcpService.WorktreeMcpService;
43
+ return yield* service.getThreadDiff(scope, input);
44
+ }),
45
+ ),
46
t3_worktree_handoff: McpToolAccess.actsAsCaller((input) =>
47
Effect.gen(function* () {
48
const scope = yield* McpInvocationContext.McpInvocationContext;
apps/server/src/mcp/toolkits/worktree/registration.test.ts
+182
-1
@@ -5,8 +5,11 @@ import * as ServerConfig from "../../../config.ts";
5
import { expect, it } from "@effect/vitest";
6
import { NodeHttpServer } from "@effect/platform-node";
7
import * as NodeServices from "@effect/platform-node/NodeServices";
8
-import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
8
+import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
9
import * as Effect from "effect/Effect";
10
+import * as FileSystem from "effect/FileSystem";
11
+import * as Option from "effect/Option";
12
+import * as Stream from "effect/Stream";
13
import * as Layer from "effect/Layer";
14
import * as Schema from "effect/Schema";
15
import { HttpBody, HttpClient, HttpRouter } from "effect/http";
@@ -18,6 +21,7 @@ import * as ThreadManagementService from "../../../orchestration-v2/ThreadManage
21
import * as ProjectService from "../../../project/ProjectService.ts";
22
import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
23
import * as ProjectSetupScriptRunner from "../../../project/ProjectSetupScriptRunner.ts";
24
+import * as ReviewService from "../../../review/ReviewService.ts";
25
import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
26
import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts";
27
import * as SecretRequests from "../../../secrets/SecretRequests.ts";
@@ -34,6 +38,17 @@ import * as McpHttpServer from "../../McpHttpServer.ts";
38
import * as McpSessionRegistry from "../../McpSessionRegistry.ts";
39
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
40
import * as PreviewBrowser from "../../../preview/PreviewBrowser.ts";
41
+import * as ProjectStore from "../../../orchestration-v2/ProjectStore.ts";
42
+import * as SqlitePersistence from "../../../persistence/Sqlite.ts";
43
+import * as VcsProcess from "../../../vcs/VcsProcess.ts";
44
+import * as VcsDriverRegistry from "../../../vcs/VcsDriverRegistry.ts";
45
+import * as KnownWorkspaces from "../../../workspace/KnownWorkspaces.ts";
46
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
47
+import * as McpToolAccess from "../../McpToolAccess.ts";
48
+import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
49
+import * as WorktreeMcpService from "../../WorktreeMcpService.ts";
50
+import * as WorktreeHandlers from "./handlers.ts";
51
+import { WorktreeToolkit } from "./tools.ts";
52
53
const layerStubServices = Layer.mergeAll(
54
Layer.mock(Orchestrator.OrchestratorV2)({}),
@@ -50,6 +65,7 @@ const layerStubServices = Layer.mergeAll(
65
Layer.mock(GitWorkflowService.GitWorkflowService)({}),
66
Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
67
Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}),
68
+ Layer.mock(ReviewService.ReviewService)({}),
69
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
70
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }),
71
Layer.mock(PreviewManager.PreviewManager)({}),
@@ -169,3 +185,168 @@ it.effect("production mcp layer lists worktree tools over http", () =>
185
),
186
),
187
);
188
+
189
+it.effect("reads another thread checkout with selected and bounded diff sources", () =>
190
+ Effect.gen(function* () {
191
+ const fs = yield* FileSystem.FileSystem;
192
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-diff-" });
193
+ const serverCwd = `${root}/server`;
194
+ const cwd = `${root}/project`;
195
+ const checkout = `${cwd}/checkout`;
196
+ yield* fs.makeDirectory(serverCwd);
197
+ yield* fs.makeDirectory(cwd);
198
+ const targetId = ThreadId.make("thread:diff-target");
199
+ const shell = {
200
+ ...McpToolAccessTestkit.liveThreadShell(targetId),
201
+ projectId: ProjectId.make("project:diff"),
202
+ worktreePath: checkout,
203
+ };
204
+ const config = ServerConfig.layerTest(serverCwd, `${root}/state`);
205
+ const gitLayer = GitVcsDriver.layer.pipe(
206
+ Layer.provide(config),
207
+ Layer.provide(NodeServices.layer),
208
+ );
209
+ const dependencies = Layer.mergeAll(
210
+ ReviewService.layer.pipe(
211
+ Layer.provide(KnownWorkspaces.layer),
212
+ Layer.provide(VcsDriverRegistry.layer),
213
+ Layer.provide(VcsProcess.layer),
214
+ Layer.provide(gitLayer),
215
+ Layer.provide(config),
216
+ Layer.provide(ServerSettings.layerTest()),
217
+ Layer.provide(SqlitePersistence.layerMemory),
218
+ Layer.provide(
219
+ Layer.mock(ProjectStore.ProjectStoreV2)({
220
+ listShells: () =>
221
+ Effect.succeed([
222
+ {
223
+ id: shell.projectId,
224
+ title: "Diff",
225
+ workspaceRoot: cwd,
226
+ defaultModelSelection: null,
227
+ scripts: [],
228
+ createdAt: "2026-01-01T00:00:00.000Z",
229
+ updatedAt: "2026-01-01T00:00:00.000Z",
230
+ },
231
+ ]),
232
+ }),
233
+ ),
234
+ Layer.provide(NodeServices.layer),
235
+ ),
236
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
237
+ getThreadShell: (id) =>
238
+ Effect.succeed(id === targetId ? shell : McpToolAccessTestkit.liveThreadShell(id)),
239
+ getProjectThreadRecords: () =>
240
+ Effect.succeed(McpToolAccessTestkit.idleThreadProjection(shell)),
241
+ }),
242
+ Layer.mock(ProjectService.ProjectService)({
243
+ getById: () =>
244
+ Effect.succeed(
245
+ Option.some({
246
+ id: shell.projectId,
247
+ title: "Diff",
248
+ workspaceRoot: cwd,
249
+ deletedAt: null,
250
+ defaultModelSelection: null,
251
+ scripts: [],
252
+ createdAt: "2026-01-01T00:00:00.000Z",
253
+ updatedAt: "2026-01-01T00:00:00.000Z",
254
+ }),
255
+ ),
256
+ }),
257
+ Layer.mock(GitWorkflowService.GitWorkflowService)({}),
258
+ Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
259
+ Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}),
260
+ ServerSettings.layerTest(),
261
+ Layer.succeed(McpInvocationContext.McpInvocationContext, {
262
+ environmentId: EnvironmentId.make("environment:diff"),
263
+ requestNamespace: "diff-session",
264
+ thread: {
265
+ threadId: ThreadId.make("thread:diff-caller"),
266
+ providerSessionId: "diff-session",
267
+ providerInstanceId: ProviderInstanceId.make("codex"),
268
+ },
269
+ client: undefined,
270
+ issuedAt: 0,
271
+ capabilities: new Set(["orchestration" as const, "worktree" as const]),
272
+ }),
273
+ );
274
+ const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(gitLayer));
275
+ const run = (at: string, args: ReadonlyArray<string>) =>
276
+ git.execute({ cwd: at, args, operation: "mcp-diff-test" });
277
+ yield* run(cwd, ["init", "-b", "main"]);
278
+ yield* run(cwd, ["config", "user.name", "Test"]);
279
+ yield* run(cwd, ["config", "user.email", "test@example.com"]);
280
+ yield* fs.writeFileString(`${cwd}/file.txt`, "original\n");
281
+ yield* run(cwd, ["add", "file.txt"]);
282
+ yield* run(cwd, ["commit", "-m", "base"]);
283
+ yield* run(cwd, ["worktree", "add", "-b", "feature", checkout]);
284
+ yield* fs.writeFileString(`${checkout}/file.txt`, "committed change\n");
285
+ yield* run(checkout, ["commit", "-am", "feature"]);
286
+ yield* fs.writeFileString(`${checkout}/file.txt`, "working change\n");
287
+
288
+ yield* Effect.gen(function* () {
289
+ const toolkit = yield* WorktreeToolkit;
290
+ const read = (
291
+ input: {
292
+ source?: "working-tree" | "branch-range";
293
+ baseRef?: string;
294
+ maxCharacters?: number;
295
+ } = {},
296
+ ) =>
297
+ toolkit.handle("t3_thread_diff", { threadId: targetId, baseRef: "main", ...input }).pipe(
298
+ Stream.unwrap,
299
+ Stream.runCollect,
300
+ Effect.map((chunks) => chunks.at(-1)!.result),
301
+ );
302
+ const all = yield* read();
303
+ expect(all).toMatchObject({ threadId: targetId, cwd: checkout });
304
+ if (!("sources" in all)) throw new Error("Expected a diff result");
305
+ expect(all.sources.map((source) => source.kind)).toEqual(["working-tree", "branch-range"]);
306
+ const working = all.sources[0]!;
307
+ const branch = all.sources[1]!;
308
+ expect(working.diff).toContain("+working change");
309
+ expect(working.diff).toContain("-committed change");
310
+ expect(branch.diff).toContain("+working change");
311
+ expect(branch.diff).toContain("-original");
312
+ expect(branch.diff).not.toContain("-committed change");
313
+ expect(working.files).toEqual([expect.objectContaining({ additions: 1, deletions: 1 })]);
314
+ expect(working.truncated).toBe(false);
315
+ expect(branch.truncated).toBe(false);
316
+ expect(yield* read({ source: "working-tree" })).toEqual({ ...all, sources: [working] });
317
+ expect(yield* read({ source: "working-tree", baseRef: "missing-base" })).toEqual({
318
+ ...all,
319
+ sources: [working],
320
+ });
321
+ expect(yield* read({ baseRef: "missing-base" })).toMatchObject({
322
+ code: "invalid_request",
323
+ message: "Could not find a common commit between 'missing-base' and HEAD.",
324
+ });
325
+ expect(yield* read({ source: "branch-range", baseRef: "missing-base" })).toMatchObject({
326
+ code: "invalid_request",
327
+ message: "Could not find a common commit between 'missing-base' and HEAD.",
328
+ });
329
+ expect(yield* read({ source: "branch-range" })).toEqual({ ...all, sources: [branch] });
330
+ expect(yield* read({ source: "branch-range", maxCharacters: 24 })).toEqual({
331
+ ...all,
332
+ sources: [{ ...branch, diff: branch.diff.slice(0, 24), truncated: true }],
333
+ });
334
+ yield* Effect.forEach(
335
+ Array.from({ length: 500 }, (_, index) => index),
336
+ (index) => fs.writeFileString(`${checkout}/extra-${index}.txt`, "extra\n"),
337
+ );
338
+ const capped = yield* read({ source: "working-tree", maxCharacters: 100_000 });
339
+ if (!("sources" in capped)) throw new Error("Expected a diff result");
340
+ expect(capped.sources[0]!.files).toHaveLength(500);
341
+ expect(capped.sources[0]!.diff.length).toBeLessThan(100_000);
342
+ expect(capped.sources[0]!.truncated).toBe(true);
343
+ }).pipe(
344
+ Effect.provide(
345
+ McpToolAccess.HandlersLayer.layer(WorktreeHandlers.layer).pipe(
346
+ Layer.provideMerge(WorktreeMcpService.layer.pipe(Layer.provide(dependencies))),
347
+ Layer.provideMerge(dependencies),
348
+ ),
349
+ ),
350
+ );
351
+ }).pipe(Effect.provide(NodeServices.layer)),
352
+);
apps/server/src/mcp/toolkits/worktree/tools.ts
+44
@@ -1,4 +1,8 @@
1
import {
2
+ ReviewDiffFileStat,
3
+ ReviewDiffPreviewSource,
4
+ ReviewDiffPreviewSourceKind,
5
+ TrimmedNonEmptyString,
6
WorktreeMcpFailure,
7
OrchestratorMcpFailure,
8
VcsListRefsInput,
@@ -81,8 +85,48 @@ const WorktreeListTool = Tool.make("t3_worktree_list", {
85
})
86
.annotate(Tool.Readonly, true)
87
.annotate(Tool.Destructive, false);
88
+
89
+const MAX_DIFF_CHARACTERS = 100_000;
90
+
91
+const ThreadDiffTool = Tool.make("t3_thread_diff", {
92
+ description:
93
+ "Show what a thread changed in its checkout (omit threadId for this thread), as the diff panel does. Returns working-tree (uncommitted changes vs HEAD) and branch-range (changes since the merge base with baseRef, or the detected base branch), each with stats for up to 500 files and a unified diff cut to maxCharacters (default 20,000), with truncated set when cut. Pass source to return one.",
94
+ parameters: Schema.Struct({
95
+ threadId: Schema.optional(ThreadId),
96
+ baseRef: Schema.optional(TrimmedNonEmptyString),
97
+ source: Schema.optional(ReviewDiffPreviewSourceKind),
98
+ maxCharacters: Schema.optional(
99
+ Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: MAX_DIFF_CHARACTERS })),
100
+ ),
101
+ }),
102
+ success: Schema.Struct({
103
+ threadId: ThreadId,
104
+ cwd: Schema.String,
105
+ sources: Schema.Array(
106
+ Schema.Struct({
107
+ kind: ReviewDiffPreviewSource.fields.kind,
108
+ baseRef: ReviewDiffPreviewSource.fields.baseRef,
109
+ headRef: ReviewDiffPreviewSource.fields.headRef,
110
+ // Null when there were too many untracked files to count.
111
+ files: Schema.NullOr(Schema.Array(ReviewDiffFileStat)),
112
+ diff: Schema.String,
113
+ truncated: Schema.Boolean,
114
+ }),
115
+ ),
116
+ }),
117
+ failure: OrchestratorMcpFailure,
118
+ failureMode: "return",
119
+ dependencies,
120
+})
121
+ .annotate(Tool.Title, "Show thread diff")
122
+ .annotate(Tool.Readonly, true)
123
+ .annotate(Tool.Destructive, false)
124
+ .annotate(Tool.Idempotent, true)
125
+ .annotate(Tool.OpenWorld, false);
126
+
127
export const WorktreeToolkit = Toolkit.make(
128
WorktreeHandoffTool,
129
WorktreeStatusTool,
130
WorktreeListTool,
131
+ ThreadDiffTool,
132
);
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+1
@@ -1350,6 +1350,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
1350
"mcp__t3-code__t3_thread_transfers",
1351
"mcp__t3-code__t3_worktree_status",
1352
"mcp__t3-code__t3_worktree_list",
1353
+ "mcp__t3-code__t3_thread_diff",
1354
"mcp__t3-code__t3_project_list",
1355
"mcp__t3-code__t3_project_read",
1356
"mcp__t3-code__t3_thread_search",
apps/server/src/vcs/GitVcsDriverCore.ts
+7
-3
@@ -3072,9 +3072,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3072
}
3073
3074
const cwd = repository.worktreeRoot;
3075
- const dirtyRef = input.file?.sourceKind === "branch-range" ? null : "HEAD";
3075
+ const sourceKind = input.file?.sourceKind ?? input.sourceKind;
3076
+ const dirtyRef = sourceKind === "branch-range" ? null : "HEAD";
3077
const review =
3077
- input.file?.sourceKind === "working-tree"
3078
+ sourceKind === "working-tree"
3079
? { baseRef: input.baseRef ?? null, mergeBase: null }
3080
: yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef);
3081
@@ -3197,7 +3198,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3198
return {
3199
cwd: input.cwd,
3200
generatedAt: yield* DateTime.now,
3200
- sources,
3201
+ sources:
3202
+ input.file === undefined && sourceKind !== undefined
3203
+ ? sources.filter((source) => source.kind === sourceKind)
3204
+ : sources,
3205
};
3206
});
3207
docs/orchestration-v2/orchestrator-mcp-server.md
+5
-3
@@ -266,8 +266,10 @@ If `hasPendingQuestion`, pass `threadId=childThreadId` to `t3_pending_request_li
266
the user; the task's completion still wakes this thread. A pending live approval for the
267
task's own unfinished work also ends the wait. Its identity appears in `pendingApproval`;
268
it grants no approval authority. Read the fresh full request in the child thread before
269
-responding, since the durable record can outlive its provider callback. Async questions
270
-do not end the wait.
269
+responding, since the durable record can outlive its provider callback. Read it with
270
+`t3_pending_request_read` and respond through `t3_pending_request_respond` using
271
+`decision`. Accepting requires a full-access/default caller; declining or cancelling
272
+does not. Async questions do not end the wait.
273
274
```ts
275
type DelegateTaskResult = {
@@ -474,7 +476,7 @@ a notification message telling it to answer with the pending request tools or
476
ask the user. The message says whether the child is blocked or, for a Codex
477
async question, still working. If the question is answered or dismissed before
478
the notification starts a turn, that queued turn is cancelled. Approvals are not
477
-routed, because those tools cannot answer them.
479
+routed to the parent automatically.
480
A parent still blocked in a `delegate_task` wait gets the blocking question
481
through that wait instead.
482
If the provider cuts that wait short, a still-pending live question wakes the
packages/client-runtime/src/t3ToolSummary.test.ts
+1
-1
@@ -67,7 +67,7 @@ describe("summarizeT3ToolCalls", () => {
67
completed({ requestId: "request-1" }),
68
completed({ requestId: "request-2" }),
69
]).label,
70
- ).toBe("Answered 2 pending question requests");
70
+ ).toBe("Responded to 2 pending requests");
71
});
72
73
it("counts attachments in distinct messages and falls back when attachment counts are missing", () => {
packages/client-runtime/src/t3ToolSummary.ts
+5
-5
@@ -273,20 +273,20 @@ export function summarizeT3ToolCalls(
273
);
274
break;
275
case "question-list":
276
- label = phrase("Listed", "list", `pending questions ${times}`);
276
+ label = phrase("Listed", "list", `pending requests ${times}`);
277
break;
278
case "question-read":
279
label = phrase(
280
"Read",
281
"read",
282
- quantity(countEntities(entityIds("requestId")), "pending question request"),
282
+ quantity(countEntities(entityIds("requestId")), "pending request"),
283
);
284
break;
285
case "question-respond":
286
label = phrase(
287
- "Answered",
288
- "answer",
289
- quantity(countEntities(entityIds("requestId")), "pending question request"),
287
+ "Responded to",
288
+ "respond to",
289
+ quantity(countEntities(entityIds("requestId")), "pending request"),
290
);
291
break;
292
case "secret-request":
packages/client-runtime/src/work-log/presentation.test.ts
+5
-1
@@ -357,7 +357,11 @@ describe("resolveWorkEntryToolPresentation", () => {
357
["t3_project_create", "Registering a project", "Registered a project"],
358
["t3_thread_launch", "Launching a project thread", "Launched a project thread"],
359
["t3_queue_edit", "Editing a queued message", "Edited a queued message"],
360
- ["t3_pending_request_respond", "Answering pending questions", "Answered pending questions"],
360
+ [
361
+ "t3_pending_request_respond",
362
+ "Responding to pending requests",
363
+ "Responded to pending requests",
364
+ ],
365
["t3_thread_configure", "Setting thread model", "Set thread model"],
366
["t3_thread_fork", "Forking this thread", "Requested a fork of this thread"],
367
["t3_thread_send_attachments", "Sending attachments", "Sent attachments"],
packages/contracts/src/orchestratorMcp.ts
+1
-1
@@ -225,7 +225,7 @@ export const OrchestratorMcpDelegateTaskResult = Schema.Struct({
225
Schema.Struct({ requestId: RuntimeRequestId, kind: ProviderRequestKind, runId: RunId }),
226
).annotate({
227
description:
228
- "Identity of the oldest pending live approval for this task's own unfinished work, or null. Ends mode=wait without cancelling the child; completion still wakes this thread. This grants no approval authority. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback. Decisions remain with the child's existing approval holder; pending request tools answer questions only.",
228
+ "Identity of the oldest pending live approval for this task's own unfinished work, or null. Ends mode=wait without cancelling the child; completion still wakes this thread. This grants no approval authority. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback. Use t3_pending_request_read to read the fresh request and t3_pending_request_respond with decision to respond; accepting needs a full-access/default caller, while declining or cancelling does not.",
229
}),
230
waitTimedOut: Schema.Boolean.annotate({
231
description:
packages/contracts/src/review.ts
+5
-4
@@ -3,23 +3,24 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts";
3
import { GitCommandError } from "./git.ts";
4
import { VcsError } from "./vcs.ts";
5
6
+export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
7
+export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
8
+
9
export const ReviewDiffPreviewInput = Schema.Struct({
10
cwd: TrimmedNonEmptyString,
11
baseRef: Schema.optional(TrimmedNonEmptyString),
12
+ sourceKind: Schema.optionalKey(ReviewDiffPreviewSourceKind),
13
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
14
file: Schema.optionalKey(
15
Schema.Struct({
16
path: Schema.NonEmptyString,
17
previousPath: Schema.NullOr(Schema.NonEmptyString),
14
- sourceKind: Schema.Literals(["working-tree", "branch-range"]),
18
+ sourceKind: ReviewDiffPreviewSourceKind,
19
}),
20
),
21
});
22
export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;
23
20
-export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
21
-export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
22
-
24
export const ReviewDiffFileStat = Schema.Struct({
25
path: Schema.String,
26
previousPath: Schema.NullOr(Schema.String),
packages/shared/src/t3McpToolPresentation.ts
+4
-6
@@ -279,15 +279,13 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
279
["Steer with", "Steering with", "Requested steering with", "a queued message"],
280
"queue-steer",
281
),
282
- t3_pending_request_list: tool(
283
- ["List", "Listing", "Listed", "pending questions"],
284
- "question-list",
285
- ),
286
- t3_pending_request_read: tool(["Read", "Reading", "Read", "pending questions"], "question-read"),
282
+ t3_pending_request_list: tool(["List", "Listing", "Listed", "pending requests"], "question-list"),
283
+ t3_pending_request_read: tool(["Read", "Reading", "Read", "pending requests"], "question-read"),
284
t3_pending_request_respond: tool(
288
- ["Answer", "Answering", "Answered", "pending questions"],
285
+ ["Respond to", "Responding to", "Responded to", "pending requests"],
286
"question-respond",
287
),
288
+ t3_thread_diff: tool(["Read", "Reading", "Read", "a thread diff"], "thread-read"),
289
t3_thread_configuration: tool(
290
["Read", "Reading", "Read", "thread configuration"],
291
"thread-configuration",