Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 ThreadId,
5 OrchestratorMcpFailure,
6 type OrchestrationV2ThreadLaunchWorkspaceStrategy,
7 ProjectId,
8 type TaskFolderError,
9 type Project as ProjectRecord,
10 type ServerProvider,
11 T3_PROJECT_FILE_NAME,
12} from "@t3tools/contracts";
13import * as Digest from "effect/crypto/Digest";
14import * as Effect from "effect/Effect";
15import * as Hex from "effect/encoding/Hex";
16import * as FileSystem from "effect/FileSystem";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
20import { outputRequestProblem } from "../../../orchestration-v2/runOutput.ts";
21import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
22import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
23import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
24import * as Project from "../../../project/ProjectService.ts";
25import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts";
26import { mutateProjectWithClone } from "../../../project/ProjectMutation.ts";
27import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
28import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
29import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
30import * as ServerSettings from "../../../serverSettings.ts";
31import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
32import * as DateTime from "effect/DateTime";
33import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
34import {
35 resolveProjectFileBackedSetting,
36 resolveProjectSettings,
37} from "@t3tools/shared/projectSettings";
38import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
39import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
40import { resolveRuntimeMode } from "../../delegatedTaskModes.ts";
41import * as McpInvocationContext from "../../McpInvocationContext.ts";
42import * as McpToolAccess from "../../McpToolAccess.ts";
43import * as OrchestrationMcp from "../../OrchestratorMcpService.ts";
44import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
45import { ProjectToolkit } from "./tools.ts";
46
47const isAboveCeilingError = Schema.is(OrchestratorRuntimeModeAboveCeilingError);
48
49function projectFailure(error: Project.ProjectServiceError) {
50 if (error._tag === "ProjectOperationError") return unavailable();
51 const message =
52 error._tag === "ProjectInvalidError"
53 ? error.detail
54 : error._tag === "ProjectNotFoundError"
55 ? "The project was not found."
56 : error._tag === "ProjectConflictError"
57 ? "The workspace is already registered to a project."
58 : "The project is not empty; force=true is required to delete it.";
59 return new OrchestratorMcpFailure({ code: "invalid_request", message });
60}
61
62function worktreeCheckHint(
63 error:
64 | ThreadLaunch.ThreadLaunchBaseRefError
65 | ThreadLaunch.ThreadLaunchBranchExistsError
66 | ThreadLaunch.ThreadLaunchBranchConflictError
67 | ThreadLaunch.ThreadLaunchNotRepositoryError
68 | TaskFolderError,
69 strategy: { readonly startFromOrigin?: boolean | undefined },
70) {
71 if (error._tag === "TaskFolderError")
72 return "Pass `repositories` paths from the project's tracked Git folders.";
73 if (error._tag === "ThreadLaunchNotRepositoryError")
74 return `Use workspaceStrategy: {type: "root"}, or pass the projectId of a Git repository.`;
75 if (error._tag === "ThreadLaunchBranchExistsError")
76 return "Pass a branch name that does not exist yet, or omit branch to get a generated name.";
77 if (error._tag === "ThreadLaunchBranchConflictError") {
78 const sibling = error.branch.replaceAll("/", "-");
79 return `Use a name that does not nest under or contain an existing branch${
80 sibling === error.branch ? "" : `, such as "${sibling}"`
81 }.`;
82 }
83 return `Pass a branch, tag, or commit that exists there${
84 strategy.startFromOrigin === true
85 ? "; no remote of the project has it either."
86 : ", or set startFromOrigin:true if it exists only on a remote."
87 }`;
88}
89
90/** Require project worktrees so launches cannot target arbitrary host directories. */
91const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
92 workspaceRoot: string,
93 worktreePath: string,
94) {
95 const git = yield* GitVcsDriver.GitVcsDriver;
96 const fileSystem = yield* FileSystem.FileSystem;
97 const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path));
98 const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe(
99 Effect.flatMap((paths) => Effect.forEach(paths, real)),
100 Effect.orElseSucceed((): ReadonlyArray<string> => []),
101 );
102 if (!worktrees.includes(yield* real(worktreePath)))
103 return yield* new OrchestratorMcpFailure({
104 code: "invalid_request",
105 message:
106 "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.",
107 });
108});
109
110/** The composer falls back to the project's t3.json when no setting picks the mode. */
111const projectFileThreadEnvMode = Effect.fn("mcp.projectFileThreadEnvMode")(function* (
112 workspaceRoot: string,
113) {
114 const fileSystem = yield* FileSystem.FileSystem;
115 const contents = yield* fileSystem
116 .readFileString(`${workspaceRoot}/${T3_PROJECT_FILE_NAME}`)
117 .pipe(Effect.orElseSucceed(() => null));
118 return resolveProjectFileBackedSetting(
119 "defaultThreadEnvMode",
120 null,
121 contents === null ? null : parseT3ProjectFile(contents),
122 ).value;
123});
124
125// Anchored to the fatal line: other diagnostics, such as a dubious-ownership refusal, quote the path.
126const NON_REPOSITORY_FATAL =
127 /^fatal: (?:not a git repository|gitfile does not point to a valid repository)/im;
128
129/** Branches from the checkout's current branch, as the composer does; a checkout with no commit or a detached HEAD stays shared. */
130const defaultWorktreeStrategy = Effect.fn("mcp.defaultWorktreeStrategy")(function* (
131 workspaceRoot: string,
132): Effect.fn.Return<
133 OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined,
134 OrchestratorMcpFailure,
135 GitVcsDriver.GitVcsDriver
136> {
137 const git = yield* GitVcsDriver.GitVcsDriver;
138 const unreadable = new OrchestratorMcpFailure({
139 code: "orchestration_error",
140 message:
141 "Could not read the project's current branch for the new worktree. No thread was created. Retry, or pass workspaceStrategy.",
142 });
143 const commit = yield* git
144 .execute({
145 operation: "mcp.defaultWorktreeStrategy",
146 cwd: workspaceRoot,
147 // Not peeled: a branch whose tip object is missing still resolves, so only an unborn HEAD exits 1.
148 args: ["rev-parse", "--verify", "--quiet", "HEAD"],
149 allowNonZeroExit: true,
150 timeoutMs: 5_000,
151 })
152 .pipe(Effect.orElseSucceed(() => null));
153 // Only Git saying "no commit yet" (exit 1) or "not a repository" keeps the launch shared.
154 if (commit?.exitCode === 1 || (commit !== null && NON_REPOSITORY_FATAL.test(commit.stderr)))
155 return undefined;
156 if (commit?.exitCode !== 0) return yield* unreadable;
157 // symbolic-ref skips the index, so a held index lock cannot drop the launch into the shared checkout.
158 const head = yield* git
159 .execute({
160 operation: "mcp.defaultWorktreeStrategy",
161 cwd: workspaceRoot,
162 args: ["symbolic-ref", "--quiet", "--short", "HEAD"],
163 allowNonZeroExit: true,
164 timeoutMs: 5_000,
165 })
166 .pipe(Effect.orElseSucceed(() => null));
167 if (head?.exitCode === 1) return undefined;
168 const branch = head?.exitCode === 0 ? head.stdout.trim() : "";
169 if (branch.length === 0) return yield* unreadable;
170 return { type: "worktree" as const, baseRef: branch };
171});
172
173/** A fixed-length id, so a long key fits in the scratch folder name derived from it. */
174const launchCommandId = Effect.fn("mcp.launchCommandId")(function* (
175 namespace: string,
176 key: string,
177) {
178 const crypto = yield* Digest.Digest;
179 // @effect-diagnostics-next-line globalJsonInEffect:off - a JSON pair keeps the caller apart from the key.
180 const bytes = new TextEncoder().encode(JSON.stringify([namespace, key]));
181 const digest = yield* crypto.digest(Digest.sha256, bytes).pipe(Effect.mapError(unavailable));
182 return CommandId.make(`mcp:launch:${Hex.encode(digest)}`);
183});
184
185const access = Effect.gen(function* () {
186 yield* readCaller();
187 return yield* Project.ProjectService;
188});
189
190/** Settings, not the project record, hold the default model and actions that new threads use. */
191const withSavedProjectSettings = Effect.gen(function* () {
192 const settings = yield* ServerSettings.ServerSettingsService.pipe(
193 Effect.flatMap((service) => service.getSettings),
194 Effect.mapError(unavailable),
195 );
196 return (project: ProjectRecord) => {
197 const resolved = resolveProjectSettings(settings, project.id, project);
198 return {
199 ...project,
200 defaultModelSelection:
201 resolved.sources.defaultModelSelection === "project"
202 ? resolved.settings.defaultModelSelection
203 : null,
204 scripts: resolveProjectScripts(settings, project),
205 };
206 };
207});
208
209// The project is already committed, so a failed Settings read must not report the create as failed.
210const withSavedProjectSettingsAfterCreate = withSavedProjectSettings.pipe(
211 Effect.orElseSucceed(() => (project: ProjectRecord) => project),
212);
213
214export const layer = McpToolAccess.toLayer(ProjectToolkit, {
215 t3_thread_launch: McpToolAccess.startsThreads(
216 (input) => input,
217 (input, { runtimeMode, interactionMode, linkOrigin }) =>
218 Effect.gen(function* () {
219 const scope = yield* McpInvocationContext.McpInvocationContext;
220 const context = yield* readCaller();
221 const { caller } = context;
222 // A retry with the same key replays the first launch: the ids derive
223 // from the caller and the key, and the launch service replays a
224 // command it already accepted.
225 const commandId =
226 input.clientRequestId === undefined
227 ? yield* newCommandId()
228 : yield* launchCommandId(scope.requestNamespace, input.clientRequestId);
229 const threadId = ThreadId.make(commandId);
230 const messageId = MessageId.make(commandId);
231 const attachments = input.attachments ?? [];
232 if (input.generateTitle === true && !input.message?.trim() && attachments.length === 0)
233 return yield* new OrchestratorMcpFailure({
234 code: "invalid_request",
235 message: "Title generation requires a message or attachments. No thread was created.",
236 });
237 const schemaProblem =
238 input.outputSchema === undefined
239 ? null
240 : outputRequestProblem(input.outputSchema, {
241 text: input.message ?? "",
242 attachments: input.attachments,
243 });
244 if (schemaProblem !== null || (input.outputSchema !== undefined && !input.message))
245 return yield* new OrchestratorMcpFailure({
246 code: "invalid_request",
247 message: schemaProblem ?? "outputSchema needs a message that asks for the result.",
248 });
249 if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
250 return yield* new OrchestratorMcpFailure({
251 code: "invalid_request",
252 message: "A new thread accepts only pending attachment uploads.",
253 });
254 if (
255 input.scratch === true &&
256 (input.projectId !== undefined || input.workspaceStrategy !== undefined)
257 )
258 return yield* new OrchestratorMcpFailure({
259 code: "invalid_request",
260 message:
261 "scratch:true picks its own project and folder; omit projectId and workspaceStrategy.",
262 });
263 const projectId =
264 input.scratch === true
265 ? (yield* ManagedProjectFolders.ManagedProjectFolders.pipe(
266 Effect.flatMap((folders) => folders.ensureScratchProject),
267 Effect.mapError(
268 (error) =>
269 new OrchestratorMcpFailure({
270 code: "orchestration_error",
271 message: error.message,
272 }),
273 ),
274 )).projectId
275 : yield* resolveProjectId(context, input.projectId);
276 // A retry of an accepted launch replays it: it keeps the model it started
277 // with and skips the checks only a new launch needs, which the project
278 // may no longer pass, such as a base branch deleted since.
279 const launched =
280 input.clientRequestId === undefined
281 ? null
282 : yield* context.threads.getThreadShell(threadId).pipe(Effect.mapError(unavailable));
283 const launchedModel =
284 launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection;
285 const replaying = launchedModel !== undefined;
286 if (launched !== null && replaying && launched.projectId !== projectId)
287 return yield* new OrchestratorMcpFailure({
288 code: "invalid_request",
289 message: "A launch retry must use the original project.",
290 });
291 const project =
292 replaying && input.workspaceStrategy?.type !== "existing_worktree"
293 ? undefined
294 : yield* Project.ProjectService.pipe(
295 Effect.flatMap((projects) => projects.getById(projectId)),
296 Effect.mapError(unavailable),
297 Effect.flatMap(
298 Option.match({
299 onNone: () =>
300 Effect.fail(
301 new OrchestratorMcpFailure({
302 code: "invalid_request",
303 message: "The project was not found.",
304 }),
305 ),
306 onSome: Effect.succeed,
307 }),
308 ),
309 );
310 if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree")
311 yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath);
312 if (!replaying && input.modelSelection !== undefined) {
313 const { instanceId, model } = input.modelSelection;
314 const registry = yield* ProviderRegistry.ProviderRegistry;
315 // The thread runs in this folder, whose own provider config can add models.
316 const cwd =
317 input.workspaceStrategy?.type === "existing_worktree"
318 ? input.workspaceStrategy.worktreePath
319 : project?.workspaceRoot;
320 const requireModel = (
321 providers: ReadonlyArray<ServerProvider>,
322 ): Effect.Effect<void, OrchestratorMcpFailure> => {
323 const provider = OrchestrationMcp.withWorkspaceModels(providers, cwd).find(
324 (candidate) => candidate.instanceId === instanceId,
325 );
326 return provider === undefined
327 ? Effect.void
328 : OrchestrationMcp.requireAdvertisedModel(provider, model);
329 };
330 const checked = requireModel(yield* registry.getProviders);
331 yield* cwd === undefined
332 ? checked
333 : checked.pipe(
334 Effect.catchIf(
335 (error) => error.code === "model_unavailable",
336 () =>
337 Project.ProjectService.pipe(
338 Effect.flatMap((projects) => projects.workspaceScanDirectory(cwd)),
339 Effect.flatMap((scanCwd) =>
340 registry.refreshWorkspaceSnapshot({ instanceId, cwd, scanCwd }),
341 ),
342 Effect.flatMap(requireModel),
343 ),
344 ),
345 );
346 }
347 const projectSettings =
348 replaying || project === undefined
349 ? undefined
350 : yield* ServerSettings.ServerSettingsService.pipe(
351 Effect.flatMap((settings) => settings.getSettings),
352 Effect.mapError(unavailable),
353 Effect.map(
354 (settings) => resolveProjectSettings(settings, projectId, project).settings,
355 ),
356 );
357 // An outside caller that names no workspace follows the new-threads-in-a-worktree
358 // default, as the composer does.
359 const requestedStrategy =
360 input.workspaceStrategy === undefined &&
361 caller === undefined &&
362 project !== undefined &&
363 projectSettings !== undefined &&
364 (projectSettings.defaultThreadEnvMode ??
365 (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree"
366 ? yield* defaultWorktreeStrategy(project.workspaceRoot)
367 : input.workspaceStrategy;
368 // An omitted startFromOrigin follows the new-worktree setting, as the composer and
369 // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base.
370 const strategy =
371 projectSettings !== undefined &&
372 requestedStrategy?.type === "worktree" &&
373 requestedStrategy.startFromOrigin === undefined
374 ? {
375 ...requestedStrategy,
376 startFromOrigin: projectSettings.newWorktreesStartFromOrigin,
377 }
378 : requestedStrategy;
379 // Reject unresolved base refs and blocked branch names before accepting a launch; worktree provisioning happens later.
380 if (!replaying && strategy?.type === "worktree")
381 yield* ThreadLaunch.ThreadLaunchService.pipe(
382 Effect.flatMap((launches) =>
383 launches.checkWorktreeBase({ projectId, workspaceStrategy: strategy }),
384 ),
385 Effect.mapError(
386 (error) =>
387 new OrchestratorMcpFailure({
388 code: "invalid_request",
389 message: `${error.message} No thread was created. ${worktreeCheckHint(error, strategy)}`,
390 }),
391 ),
392 );
393 // A caller outside a thread has nothing to inherit, so it starts with the
394 // project's effective defaults, as the composer does. Its mode stays
395 // within the ceiling it was approved with.
396 const projectDefaults = caller === undefined ? projectSettings : undefined;
397 const modelSelection =
398 input.modelSelection ??
399 launchedModel ??
400 caller?.modelSelection ??
401 (projectDefaults
402 ? resolveNewThreadModelSelection({
403 defaultSelection: projectDefaults.defaultModelSelection,
404 fallbackSelection: projectDefaults.fallbackModelSelection,
405 providers: yield* ProviderRegistry.ProviderRegistry.pipe(
406 Effect.flatMap((registry) => registry.getProviders),
407 ),
408 settings: projectDefaults,
409 projectId,
410 now: DateTime.toEpochMillis(yield* DateTime.now),
411 }).selection
412 : null) ??
413 undefined;
414 if (modelSelection === undefined)
415 return yield* new OrchestratorMcpFailure({
416 code: "invalid_request",
417 message:
418 "Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.",
419 });
420 let startedRuntimeMode =
421 projectDefaults !== undefined && input.runtimeMode === undefined
422 ? yield* resolveRuntimeMode(runtimeMode, projectDefaults.defaultRuntimeMode).pipe(
423 Effect.orElseSucceed(() => runtimeMode),
424 )
425 : runtimeMode;
426 if (!replaying) {
427 const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders;
428 startedRuntimeMode = yield* resolveRuntimeMode(startedRuntimeMode, input.runtimeMode, {
429 modelSelection,
430 supportedRuntimeModes: providers.find(
431 (provider) => provider.instanceId === modelSelection.instanceId,
432 )?.supportedRuntimeModes,
433 });
434 }
435 const result = yield* ThreadMessageIntake.launchThread({
436 commandId,
437 threadId,
438 projectId,
439 title: input.title,
440 ...(input.generateTitle === undefined ? {} : { generateTitle: input.generateTitle }),
441 ...(input.generateTitle === true ? {} : { titleRenamed: true }),
442 modelSelection,
443 runtimeMode: startedRuntimeMode,
444 interactionMode,
445 workspaceStrategy: strategy ?? { type: "root" },
446 ...(input.message === undefined && attachments.length === 0
447 ? {}
448 : {
449 initialMessage: {
450 messageId,
451 ...(caller === undefined ? {} : { senderThreadId: caller.id }),
452 text: input.message ?? "",
453 attachments,
454 ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
455 },
456 }),
457 createdBy: "agent",
458 creationSource: "mcp",
459 ...(linkOrigin === undefined ? {} : { linkOrigin }),
460 // Kept only alongside linkOrigin: thread.create drops it otherwise.
461 ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),
462 }).pipe(
463 Effect.mapError((error) => {
464 if (error._tag === "AttachmentClaimError") {
465 return new OrchestratorMcpFailure({
466 code: "orchestration_error",
467 message: error.message,
468 });
469 }
470 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
471 return new OrchestratorMcpFailure({
472 code: "invalid_request",
473 message: error.message,
474 });
475 }
476 // The administrator's ceiling refuses the mode; say so rather than "unavailable".
477 if (error._tag === "ThreadLaunchError" && isAboveCeilingError(error.cause)) {
478 return new OrchestratorMcpFailure({
479 code: "invalid_request",
480 message: error.cause.message,
481 });
482 }
483 return unavailable();
484 }),
485 );
486 const thread = result.projection.thread;
487 const run = result.projection.runs.find((run) => run.userMessageId === messageId);
488 return {
489 threadId: thread.id,
490 link: McpInvocationContext.threadLinkFor(scope, thread.id, thread.title),
491 projectId: thread.projectId,
492 modelSelection: thread.modelSelection,
493 runId: run?.id ?? null,
494 status: run?.status ?? null,
495 };
496 }),
497 // The launched thread carries the caller's link, if it has one.
498 "stamped",
499 ),
500 t3_project_list: McpToolAccess.reads((input) =>
501 Effect.gen(function* () {
502 const projects = yield* access;
503 // Identities are resolved: linked environments find this side's project by repository.
504 const page = yield* projects
505 .listPage({ cursor: input.cursor ?? 0, limit: input.limit ?? 20 })
506 .pipe(Effect.mapError(unavailable));
507 return { ...page, projects: page.projects.map(yield* withSavedProjectSettings) };
508 }),
509 ),
510 t3_project_read: McpToolAccess.reads((input) =>
511 Effect.gen(function* () {
512 const projects = yield* access;
513 const result = yield* projects.getById(input.projectId).pipe(Effect.mapError(unavailable));
514 if (Option.isNone(result))
515 return yield* new OrchestratorMcpFailure({
516 code: "invalid_request",
517 message: "The project was not found.",
518 });
519 return (yield* withSavedProjectSettings)(result.value);
520 }),
521 ),
522 t3_project_create: McpToolAccess.writesEnvironment(
523 ({ workspaceRoot, ...input }) =>
524 Effect.gen(function* () {
525 const projects = yield* Project.ProjectService;
526 if (workspaceRoot === undefined) {
527 // Only updates record model defaults; reject defaults that creation would silently drop.
528 if (
529 input.scripts !== undefined ||
530 input.trackedFolders !== undefined ||
531 input.createWorkspaceRootIfMissing !== undefined ||
532 input.defaultModelSelection !== undefined
533 )
534 return yield* new OrchestratorMcpFailure({
535 code: "invalid_request",
536 message:
537 "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
538 });
539 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
540 const created = yield* folders.createNamedProject({ name: input.title }).pipe(
541 Effect.mapError(
542 (error) =>
543 new OrchestratorMcpFailure({
544 code: "orchestration_error",
545 message: error.message,
546 }),
547 ),
548 );
549 const project = yield* projects
550 .getById(created.projectId)
551 .pipe(
552 Effect.mapError(unavailable),
553 Effect.flatMap(
554 Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
555 ),
556 );
557 return {
558 ...(yield* withSavedProjectSettingsAfterCreate)(project),
559 ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
560 };
561 }
562 if (input.defaultModelSelection !== undefined && input.defaultModelSelection !== null)
563 return yield* new OrchestratorMcpFailure({
564 code: "invalid_request",
565 message:
566 "Creating a project does not set its default model; set defaultModelSelection afterwards with t3_project_update.",
567 });
568 const commandId = yield* newCommandId();
569 const created = yield* projects
570 .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
571 .pipe(Effect.mapError(projectFailure));
572 return (yield* withSavedProjectSettingsAfterCreate)(created);
573 }),
574 // Linked work may bring the repository it works in; an existing
575 // registered workspace is still refused.
576 { linkedCallers: "allowed" },
577 ),
578 t3_project_update: McpToolAccess.writesEnvironment((input) =>
579 Effect.gen(function* () {
580 const projects = yield* Project.ProjectService;
581 const updated = yield* projects
582 .update({ ...input, commandId: yield* newCommandId() })
583 .pipe(Effect.mapError(projectFailure));
584 return (yield* withSavedProjectSettings)(updated);
585 }),
586 ),
587 t3_project_delete: McpToolAccess.writesEnvironment((input) =>
588 Effect.gen(function* () {
589 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
590 if (yield* folders.isScratchProject(input.projectId))
591 return yield* new OrchestratorMcpFailure({
592 code: "invalid_request",
593 message:
594 '"No project" is the built-in scratch project and cannot be deleted through MCP. The user can remove it in Settings.',
595 });
596 const projects = yield* Project.ProjectService;
597 const clones = yield* ProjectCloneTracker.ProjectCloneTracker;
598 return yield* mutateProjectWithClone(projects, clones, {
599 ...input,
600 type: "project.delete",
601 commandId: yield* newCommandId(),
602 }).pipe(Effect.mapError(projectFailure));
603 }),
604 ),
605 t3_project_clone: McpToolAccess.writesEnvironment(
606 (input) =>
607 Effect.gen(function* () {
608 const repositories = yield* Repositories.SourceControlRepositoryService;
609 // Agents' MCP calls have their own long budget, and an aborted call interrupts git.
610 return yield* repositories.cloneRepository(input, { timeoutMs: null }).pipe(
611 Effect.mapError(
612 (error) =>
613 new OrchestratorMcpFailure({
614 code: "orchestration_error",
615 message: error.detail,
616 }),
617 ),
618 );
619 }),
620 // An existing destination is never adopted.
621 { linkedCallers: "allowed" },
622 ),
623});