Open History to see the last commit
1import { MessageId, ThreadId, OrchestratorMcpFailure, ProjectId } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
6import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
7import * as Project from "../../../project/ProjectService.ts";
8import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
9import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
10import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
11import * as McpToolAccess from "../../McpToolAccess.ts";
12import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
13import { ProjectToolkit } from "./tools.ts";
14
15function projectFailure(error: Project.ProjectServiceError) {
16 if (error._tag === "ProjectOperationError") return unavailable();
17 const message =
18 error._tag === "ProjectNotFoundError"
19 ? "The project was not found."
20 : error._tag === "ProjectConflictError"
21 ? "The workspace is already registered to a project."
22 : "The project is not empty; force=true is required to delete it.";
23 return new OrchestratorMcpFailure({ code: "invalid_request", message });
24}
25
26/**
27 * An existing checkout a launch may bind: one of the project's own git
28 * worktrees. Without this check a launch could point an agent at any directory
29 * on the machine.
30 */
31const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
32 workspaceRoot: string,
33 worktreePath: string,
34) {
35 const git = yield* GitVcsDriver.GitVcsDriver;
36 const fileSystem = yield* FileSystem.FileSystem;
37 const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path));
38 const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe(
39 Effect.flatMap((paths) => Effect.forEach(paths, real)),
40 Effect.orElseSucceed((): ReadonlyArray<string> => []),
41 );
42 if (!worktrees.includes(yield* real(worktreePath)))
43 return yield* new OrchestratorMcpFailure({
44 code: "invalid_request",
45 message:
46 "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.",
47 });
48});
49
50const access = Effect.gen(function* () {
51 yield* readCaller();
52 return yield* Project.ProjectService;
53});
54export const layer = McpToolAccess.toLayer(ProjectToolkit, {
55 t3_thread_launch: McpToolAccess.startsThreads(
56 (input) => input,
57 (input, { runtimeMode, interactionMode }) =>
58 Effect.gen(function* () {
59 const context = yield* readCaller();
60 const { caller } = context;
61 const commandId = yield* newCommandId();
62 const threadId = ThreadId.make(commandId);
63 const messageId = MessageId.make(commandId);
64 const attachments = input.attachments ?? [];
65 if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
66 return yield* new OrchestratorMcpFailure({
67 code: "invalid_request",
68 message: "A new thread accepts only pending attachment uploads.",
69 });
70 if (
71 input.scratch === true &&
72 (input.projectId !== undefined || input.workspaceStrategy !== undefined)
73 )
74 return yield* new OrchestratorMcpFailure({
75 code: "invalid_request",
76 message:
77 "scratch:true picks its own project and folder; omit projectId and workspaceStrategy.",
78 });
79 const projectId =
80 input.scratch === true
81 ? (yield* ManagedProjectFolders.ManagedProjectFolders.pipe(
82 Effect.flatMap((folders) => folders.ensureScratchProject),
83 Effect.mapError(
84 (error) =>
85 new OrchestratorMcpFailure({
86 code: "orchestration_error",
87 message: error.message,
88 }),
89 ),
90 )).projectId
91 : yield* resolveProjectId(context, input.projectId);
92 const readProject = Project.ProjectService.pipe(
93 Effect.flatMap((projects) => projects.getById(projectId)),
94 Effect.mapError(unavailable),
95 Effect.map(Option.getOrUndefined),
96 );
97 if (input.workspaceStrategy?.type === "existing_worktree") {
98 const project = yield* readProject;
99 if (project === undefined)
100 return yield* new OrchestratorMcpFailure({
101 code: "invalid_request",
102 message: "The project was not found.",
103 });
104 yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath);
105 }
106 const modelSelection =
107 input.modelSelection ??
108 caller?.modelSelection ??
109 (yield* readProject)?.defaultModelSelection ??
110 undefined;
111 if (modelSelection === undefined)
112 return yield* new OrchestratorMcpFailure({
113 code: "invalid_request",
114 message:
115 "Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.",
116 });
117 const result = yield* ThreadMessageIntake.launchThread({
118 commandId,
119 threadId,
120 projectId,
121 title: input.title,
122 modelSelection,
123 runtimeMode,
124 interactionMode,
125 workspaceStrategy: input.workspaceStrategy ?? { type: "root" },
126 ...(input.message === undefined && attachments.length === 0
127 ? {}
128 : {
129 initialMessage: {
130 messageId,
131 ...(caller === undefined ? {} : { senderThreadId: caller.id }),
132 text: input.message ?? "",
133 attachments,
134 },
135 }),
136 createdBy: "agent",
137 creationSource: "mcp",
138 }).pipe(
139 Effect.mapError((error) =>
140 error._tag === "AttachmentClaimError"
141 ? new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message })
142 : unavailable(),
143 ),
144 );
145 const thread = result.projection.thread;
146 const run = result.projection.runs.find((run) => run.userMessageId === messageId);
147 return {
148 threadId: thread.id,
149 projectId: thread.projectId,
150 modelSelection: thread.modelSelection,
151 runId: run?.id ?? null,
152 status: run?.status ?? null,
153 };
154 }),
155 ),
156 t3_project_list: McpToolAccess.reads((input) =>
157 Effect.gen(function* () {
158 const projects = yield* access;
159 const snapshot = yield* projects.snapshot.pipe(Effect.mapError(unavailable));
160 const rows = snapshot.projects.filter((project) => project.deletedAt === null);
161 const start = input.cursor ?? 0,
162 end = start + (input.limit ?? 20);
163 return { projects: rows.slice(start, end), nextCursor: end < rows.length ? end : null };
164 }),
165 ),
166 t3_project_read: McpToolAccess.reads((input) =>
167 Effect.gen(function* () {
168 const projects = yield* access;
169 const result = yield* projects.getById(input.projectId).pipe(Effect.mapError(unavailable));
170 if (Option.isNone(result))
171 return yield* new OrchestratorMcpFailure({
172 code: "invalid_request",
173 message: "The project was not found.",
174 });
175 return result.value;
176 }),
177 ),
178 t3_project_create: McpToolAccess.writesEnvironment(({ workspaceRoot, ...input }) =>
179 Effect.gen(function* () {
180 const projects = yield* Project.ProjectService;
181 if (workspaceRoot === undefined) {
182 // Project creation records no model default (only an update does), so
183 // reject what this mode would otherwise drop silently.
184 if (
185 input.scripts !== undefined ||
186 input.createWorkspaceRootIfMissing !== undefined ||
187 input.defaultModelSelection !== undefined
188 )
189 return yield* new OrchestratorMcpFailure({
190 code: "invalid_request",
191 message:
192 "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
193 });
194 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
195 const created = yield* folders
196 .createNamedProject({ name: input.title })
197 .pipe(
198 Effect.mapError(
199 (error) =>
200 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
201 ),
202 );
203 const project = yield* projects
204 .getById(created.projectId)
205 .pipe(
206 Effect.mapError(unavailable),
207 Effect.flatMap(
208 Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
209 ),
210 );
211 return {
212 ...project,
213 ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
214 };
215 }
216 const commandId = yield* newCommandId();
217 return yield* projects
218 .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
219 .pipe(Effect.mapError(projectFailure));
220 }),
221 ),
222 t3_project_update: McpToolAccess.writesEnvironment((input) =>
223 Effect.gen(function* () {
224 const projects = yield* Project.ProjectService;
225 return yield* projects
226 .update({ ...input, commandId: yield* newCommandId() })
227 .pipe(Effect.mapError(projectFailure));
228 }),
229 ),
230 t3_project_delete: McpToolAccess.writesEnvironment((input) =>
231 Effect.gen(function* () {
232 const projects = yield* Project.ProjectService;
233 return yield* projects
234 .delete({ ...input, commandId: yield* newCommandId() })
235 .pipe(Effect.mapError(projectFailure));
236 }),
237 ),
238 t3_project_clone: McpToolAccess.writesEnvironment((input) =>
239 Effect.gen(function* () {
240 const repositories = yield* Repositories.SourceControlRepositoryService;
241 return yield* repositories.cloneRepository(input).pipe(
242 Effect.mapError(
243 (error) =>
244 new OrchestratorMcpFailure({
245 code: "orchestration_error",
246 message: error.detail,
247 }),
248 ),
249 );
250 }),
251 ),
252});