Skip to content

Commit 2349103

Browse files
fix(server): MCP writes need thread control, and launches skip removed worktrees
Review found three gaps: - Uploads, scheduled tasks, projects and settings each checked the orchestration capability before the access declarations. writes and writesEnvironment now require it again, so a credential that may only use its browser cannot reach them. Tools that act for their own capability (preview, device, worktree, pull requests) still check that one instead. - git keeps a removed worktree's record, marked prunable, until it is pruned. listWorktreePaths returned those paths, so a directory later made at one passed the existing_worktree launch check. It now leaves prunable records out. - Saving a scheduled task, then failing to read its bound thread for the summary, reported the saved task as an error, so an unkeyed retry could save it twice. The summary now leaves out the webhook URL instead. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent a0af1d6 commit 2349103

7 files changed

Lines changed: 96 additions & 11 deletions

File tree

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,8 @@ const fullAccess = threadCaller(fullAccessThreadId);
193193
const ended = threadCaller(endedThreadId);
194194
const supervisedClient = clientCaller("approval-required");
195195
const fullAccessClient = clientCaller("full-access");
196+
// A live full-access thread whose credential may use its browser but not control threads.
197+
const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
196198

197199
it.effect.each([
198200
// Reads are open to every caller, even one whose turn ended.
@@ -210,6 +212,9 @@ it.effect.each([
210212
["writes", supervised, {}, "ran"],
211213
["writes", ended, {}, "parent_not_active"],
212214
["writes", supervisedClient, {}, "ran"],
215+
// Uploads, scheduled tasks, projects and settings need a credential that controls threads.
216+
["writes", previewOnly, {}, "capability_denied"],
217+
["writes_environment", previewOnly, {}, "capability_denied"],
213218

214219
// Changing a thread: only one that runs within the caller's modes.
215220
["writes_threads", supervised, {}, "ran"],

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
assertTargetWithinLimits,
1919
type Caller,
2020
loadCaller,
21+
readCaller,
2122
unavailable,
2223
} from "./threadAccess.ts";
2324

@@ -91,9 +92,16 @@ export class Declaration<out Handler> {
9192
}
9293
}
9394

94-
/** The caller of a tool that changes something. */
95+
/**
96+
* The caller of a tool that changes something. Tools that act for a
97+
* capability of their own (preview, device, worktree, pull requests) check it
98+
* themselves.
99+
*/
95100
const writingCaller = loadCaller().pipe(Effect.tap(assertLiveCaller));
96101

102+
/** The same, for tools whose only capability is controlling threads. */
103+
const orchestratingCaller = readCaller().pipe(Effect.tap(assertLiveCaller));
104+
97105
const requireThreadCaller = McpInvocationContext.McpInvocationContext.pipe(
98106
Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "This tool")),
99107
);
@@ -121,7 +129,7 @@ export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A,
121129

122130
/** Changes something that belongs to no thread, such as a pending upload or a scheduled task. */
123131
export const writes = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
124-
declare((params: P) => writingCaller.pipe(Effect.flatMap(() => handle(params))));
132+
declare((params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))));
125133

126134
/**
127135
* Changes the threads `threads` names. An omitted id is the caller's own
@@ -191,14 +199,14 @@ export const writesEnvironment = <P, A, E, R>(
191199
check: Effect.Effect<Caller, OrchestratorMcpFailure, CheckServices>,
192200
) => Effect.Effect<A, E, R>,
193201
) => {
194-
const check = writingCaller.pipe(
202+
const check = orchestratingCaller.pipe(
195203
Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
196204
);
197205
return declare((params: P) => check.pipe(Effect.flatMap(() => handle(params, check))));
198206
};
199207

200208
/** What a declaration's own check needs. */
201-
type CheckServices = Effect.Services<typeof writingCaller>;
209+
type CheckServices = Effect.Services<typeof orchestratingCaller>;
202210

203211
/**
204212
* Each handler of `Handlers`, built by one of the declarations above. A

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1692,5 +1692,57 @@ describe("OrchestratorMcpService provider resolution", () => {
16921692
assert.equal(yield* Ref.get(upserted), 0);
16931693
}),
16941694
);
1695+
1696+
it.effect("reports a saved task even when its bound thread cannot be read", () =>
1697+
Effect.gen(function* () {
1698+
const upserted = yield* Ref.make(0);
1699+
const bound = task({ threadId: boundThreadId });
1700+
const lookups = yield* Ref.make(0);
1701+
// The edit's own check reads the thread; the read after the save fails.
1702+
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
1703+
Effect.provide(
1704+
OrchestratorMcpService.layer.pipe(
1705+
Layer.provide(
1706+
Layer.mergeAll(
1707+
NodeServices.layer,
1708+
Layer.mock(ThreadManagementService.ThreadManagementService)({
1709+
getThreadShell: (threadId) =>
1710+
Ref.getAndUpdate(lookups, (count) => count + 1).pipe(
1711+
Effect.flatMap((count) =>
1712+
count === 0
1713+
? Effect.succeed(
1714+
liveThreadShell(threadId, { runtimeMode: "approval-required" }),
1715+
)
1716+
: Effect.fail(new OrchestratorProjectionError({ threadId })),
1717+
),
1718+
),
1719+
}),
1720+
Layer.mock(ProviderRegistry.ProviderRegistry)({
1721+
getProviders: Effect.succeed([]),
1722+
}),
1723+
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
1724+
list: () => Effect.succeed([]),
1725+
}),
1726+
Layer.mock(ProjectService.ProjectService)({}),
1727+
Layer.mock(SecretRequests.SecretRequests)({}),
1728+
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
1729+
list: () => Effect.succeed({ tasks: [bound] }),
1730+
upsert: () =>
1731+
Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: bound })),
1732+
}),
1733+
),
1734+
),
1735+
),
1736+
),
1737+
);
1738+
const updated = yield* mcp.updateScheduledTask(supervisedClient, {
1739+
scheduledTaskId: bound.id,
1740+
prompt: "Something else",
1741+
});
1742+
assert.equal(yield* Ref.get(upserted), 1);
1743+
assert.equal(updated.scheduledTaskId, bound.id);
1744+
assert.equal(updated.webhookUrl, undefined);
1745+
}),
1746+
);
16951747
});
16961748
});

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1413,10 +1413,14 @@ const make = Effect.gen(function* () {
14131413
const live =
14141414
caller.parent === undefined ||
14151415
Exit.isSuccess(yield* Effect.exit(assertLiveCaller(scope, caller.parent)));
1416-
const modes = yield* scheduledTaskRunModes(task);
1416+
// This runs after a save, so a failed lookup of the bound thread hides
1417+
// the webhook URL instead of reporting a saved task as an error.
1418+
const modes = yield* scheduledTaskRunModes(task).pipe(Effect.option);
14171419
return scheduledTaskSummary(
14181420
task,
1419-
live && modes.every((mode) => withinLimits(caller.limits, mode)),
1421+
live &&
1422+
Option.isSome(modes) &&
1423+
modes.value.every((mode) => withinLimits(caller.limits, mode)),
14201424
);
14211425
});
14221426

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,5 +444,13 @@ it.effect("a launch binds only an existing checkout that is one of the project's
444444
{ type: "existing_worktree", worktreePath: worktree },
445445
{ type: "existing_worktree", worktreePath: repo },
446446
]);
447+
448+
// A removed worktree stays listed as prunable until `git worktree prune`;
449+
// whatever directory is later made at its path is not one of the project's.
450+
yield* fileSystem.remove(worktree, { recursive: true });
451+
yield* fileSystem.makeDirectory(worktree);
452+
expect((yield* launchInto(worktree)).at(-1)?.result).toMatchObject({
453+
code: "invalid_request",
454+
});
447455
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
448456
);

‎apps/server/src/vcs/GitVcsDriver.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,10 @@ export class GitVcsDriver extends Context.Service<
398398
readonly pruneWorktrees: (input: {
399399
readonly cwd: string;
400400
}) => Effect.Effect<void, GitCommandError>;
401-
/** Absolute paths of every worktree of the repository at `cwd`, the main checkout included. */
401+
/**
402+
* Absolute paths of every live worktree of the repository at `cwd`, the
403+
* main checkout included. Worktrees whose directory is gone are left out.
404+
*/
402405
readonly listWorktreePaths: (cwd: string) => Effect.Effect<string[], GitCommandError>;
403406
readonly deleteLocalBranch: (
404407
input: GitDeleteLocalBranchInput,

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3961,11 +3961,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
39613961
"--porcelain",
39623962
"-z",
39633963
]).pipe(
3964+
// One record per worktree, each ended by an empty field. A `prunable`
3965+
// record's directory is gone, and another checkout may now sit there.
39643966
Effect.map((stdout) =>
3965-
stdout
3966-
.split("\0")
3967-
.filter((field) => field.startsWith("worktree "))
3968-
.map((field) => path.resolve(cwd, field.slice("worktree ".length))),
3967+
stdout.split("\0\0").flatMap((record) => {
3968+
const fields = record.split("\0");
3969+
const worktree = fields.find((field) => field.startsWith("worktree "));
3970+
return worktree === undefined || fields.some((field) => field.startsWith("prunable"))
3971+
? []
3972+
: [path.resolve(cwd, worktree.slice("worktree ".length))];
3973+
}),
39693974
),
39703975
);
39713976

0 commit comments

Comments
 (0)