Skip to content

Commit 7d3463d

Browse files
committed
fix(server): preserve parent-child lifecycle and delegation ownership
Backport upstream pingdotgg#22846, pingdotgg#23542, and pingdotgg#24808. Require authoritative lineage before credential rotation, preserve restricted credentials on lookup failure, and verify Stop races and child watch-tool denial.
1 parent 8099c47 commit 7d3463d

15 files changed

Lines changed: 944 additions & 39 deletions

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

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,3 +970,119 @@ it.effect("admits provider and OAuth client credentials and points only clients
970970
}),
971971
).pipe(Effect.provide(NodeHttpServer.layerTest)),
972972
);
973+
974+
it.effect("keeps PR watch tools available to parents and rejects delegated child calls", () =>
975+
Effect.scoped(
976+
Effect.gen(function* () {
977+
const scopeFor = (
978+
token: string,
979+
subagent: boolean,
980+
): McpInvocationContext.McpThreadInvocationScope => ({
981+
environmentId,
982+
requestNamespace: token,
983+
thread: {
984+
threadId: ThreadId.make(`thread-${token}`),
985+
providerSessionId: token,
986+
providerInstanceId: ProviderInstanceId.make("codex"),
987+
subagent,
988+
},
989+
client: undefined,
990+
capabilities: new Set(["pull-requests"]),
991+
issuedAt: 1,
992+
});
993+
const scopes = new Map([
994+
["parentToken", scopeFor("parentToken", false)],
995+
["childToken", scopeFor("childToken", true)],
996+
]);
997+
const serverLayer = McpHttpServer.layerPullRequestsToolkit.pipe(
998+
Layer.provideMerge(McpHttpServer.layerMcpTransport),
999+
Layer.provide(
1000+
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1001+
resolve: (token) => Effect.succeed(scopes.get(token)),
1002+
}),
1003+
),
1004+
Layer.provide(
1005+
Layer.mergeAll(
1006+
McpToolAccessTestkit.liveThreadsLayer,
1007+
Layer.mock(ProjectService.ProjectService)({}),
1008+
Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
1009+
Layer.mock(Orchestrator.OrchestratorV2)({}),
1010+
Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
1011+
NodeServices.layer,
1012+
),
1013+
),
1014+
);
1015+
yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1016+
Layer.build,
1017+
);
1018+
const httpClient = yield* HttpClient.HttpClient;
1019+
const listedTools = (token: string) =>
1020+
Effect.gen(function* () {
1021+
const headers = {
1022+
accept: "application/json, text/event-stream",
1023+
authorization: `Bearer ${token}`,
1024+
};
1025+
const initialize = yield* httpClient.post("/mcp", {
1026+
headers,
1027+
body: HttpBody.text(
1028+
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1029+
"application/json",
1030+
),
1031+
});
1032+
const listed = yield* httpClient.post("/mcp", {
1033+
headers: {
1034+
...headers,
1035+
"mcp-session-id": initialize.headers["mcp-session-id"]!,
1036+
"mcp-protocol-version": "2025-06-18",
1037+
},
1038+
body: HttpBody.text(
1039+
`{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
1040+
"application/json",
1041+
),
1042+
});
1043+
const body = (yield* listed.json) as {
1044+
readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
1045+
};
1046+
if (token === "childToken") {
1047+
for (const name of ["watch_pull_request", "unwatch_pull_request"]) {
1048+
const denied = yield* httpClient.post("/mcp", {
1049+
headers: {
1050+
...headers,
1051+
"mcp-session-id": initialize.headers["mcp-session-id"]!,
1052+
"mcp-protocol-version": "2025-06-18",
1053+
},
1054+
body: HttpBody.text(
1055+
JSON.stringify({
1056+
jsonrpc: "2.0",
1057+
id: 3,
1058+
method: "tools/call",
1059+
params: {
1060+
name,
1061+
arguments: {
1062+
url: "https://github.com/unlockdigital/synthetic/pull/1",
1063+
threadId: "thread-parentToken",
1064+
},
1065+
},
1066+
}),
1067+
"application/json",
1068+
),
1069+
});
1070+
expect(yield* denied.json).toMatchObject({
1071+
error: { message: `Tool '${name}' not found` },
1072+
});
1073+
}
1074+
}
1075+
return body.result.tools.map((tool) => tool.name);
1076+
});
1077+
1078+
const parentTools = yield* listedTools("parentToken");
1079+
const childTools = yield* listedTools("childToken");
1080+
expect(parentTools).toEqual(
1081+
expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]),
1082+
);
1083+
expect(childTools).toContain("link_pull_request");
1084+
expect(childTools).not.toContain("watch_pull_request");
1085+
expect(childTools).not.toContain("unwatch_pull_request");
1086+
}),
1087+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
1088+
);

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
} from "@t3tools/contracts";
1111
import * as Context from "effect/Context";
1212
import * as Effect from "effect/Effect";
13+
import * as Fiber from "effect/Fiber";
1314

1415
const ALL_MCP_CAPABILITIES = [
1516
"preview",
@@ -24,6 +25,8 @@ export interface McpThreadCaller {
2425
readonly threadId: ThreadId;
2526
readonly providerSessionId: string;
2627
readonly providerInstanceId: ProviderInstanceId;
28+
/** A delegated child task; its parent owns the work it hands back. */
29+
readonly subagent?: boolean;
2730
}
2831

2932
export interface McpClientCaller {
@@ -58,6 +61,16 @@ export class McpInvocationContext extends Context.Service<
5861
McpInvocationScope
5962
>()("t3/mcp/McpInvocationContext") {}
6063

64+
/**
65+
* `McpSchema.EnabledWhen` for tools a delegated child must not see or call.
66+
* EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber.
67+
*/
68+
export const hiddenFromSubagents = (): boolean => {
69+
const fiber = Fiber.getCurrent();
70+
const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
71+
return scope?.thread?.subagent !== true;
72+
};
73+
6174
export type McpCapabilityError<C extends McpCapability> = C extends "preview"
6275
? PreviewAutomationUnavailableError
6376
: McpCapabilityUnavailableError;

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export interface McpCredentialRequest {
2222
*/
2323
readonly browserToolsAvailable?: boolean;
2424
readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
25+
readonly subagent?: boolean;
2526
}
2627

2728
export interface McpIssuedCredential {
@@ -109,6 +110,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
109110
threadId: ThreadId.make(request.threadId),
110111
providerSessionId,
111112
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
113+
subagent: request.subagent === true,
112114
},
113115
client: undefined,
114116
capabilities: new Set<McpInvocationContext.McpCapability>([

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
ThreadId,
1111
} from "@t3tools/contracts";
1212
import * as Schema from "effect/Schema";
13+
import * as McpSchema from "effect/ai/McpSchema";
1314
import * as Tool from "effect/ai/Tool";
1415
import * as Toolkit from "effect/ai/Toolkit";
1516

@@ -316,7 +317,7 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
316317

317318
const WatchPullRequestTool = Tool.make("watch_pull_request", {
318319
description:
319-
"Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every two minutes and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles or is archived, when T3 Code fails to read it 8 times in a row (a host rate limit only delays it), when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch. A subagent cannot watch: its parent thread owns the pull request.",
320+
"Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every two minutes and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles or is archived, when T3 Code fails to read it 8 times in a row (a host rate limit only delays it), when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch.",
320321
parameters: PullRequestTargetInput,
321322
success: WatchPullRequestResult,
322323
failure: PullRequestToolError,
@@ -326,7 +327,8 @@ const WatchPullRequestTool = Tool.make("watch_pull_request", {
326327
.annotate(Tool.Readonly, false)
327328
.annotate(Tool.Destructive, false)
328329
.annotate(Tool.Idempotent, true)
329-
.annotate(Tool.OpenWorld, false);
330+
.annotate(Tool.OpenWorld, false)
331+
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents);
330332

331333
const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
332334
description:
@@ -340,7 +342,8 @@ const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
340342
.annotate(Tool.Readonly, false)
341343
.annotate(Tool.Destructive, false)
342344
.annotate(Tool.Idempotent, true)
343-
.annotate(Tool.OpenWorld, false);
345+
.annotate(Tool.OpenWorld, false)
346+
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents);
344347

345348
const GuideTarget = Schema.Struct({
346349
url: PullRequestTargetInput.fields.url,

0 commit comments

Comments
 (0)