Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationProjectShell,
4 type OrchestrationV2ThreadShell,
5 type SourceControlProviderKind,
6 type ThreadId,
7 type ThreadPullRequestLink,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Crypto from "effect/Crypto";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13
14import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
15import * as ProjectService from "../../../project/ProjectService.ts";
16import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
17import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
18import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts";
19import {
20 normalizeThreadPullRequestKey,
21 resolveThreadPullRequestChains,
22 threadPullRequestKeyOf,
23 threadPullRequestKeysEqual,
24 threadPullRequestsOf,
25 visibleThreadPullRequests,
26} from "../../../sourceControl/threadPullRequests.ts";
27import * as McpInvocationContext from "../../McpInvocationContext.ts";
28import * as McpToolAccess from "../../McpToolAccess.ts";
29import {
30 type ListThreadPullRequestsResult,
31 PullRequestLinkFailedError,
32 PullRequestUrlInvalidError,
33 PullRequestTargetIncompleteError,
34 PullRequestHostRequiredError,
35 PullRequestUrlUnavailableError,
36 PullRequestUnlinkFailedError,
37 PullRequestListFailedError,
38 PullRequestNotOpenError,
39 type PullRequestTargetInput,
40 PullRequestWatchFailedError,
41 PullRequestWatchFromSubagentError,
42 PullRequestThreadNotFoundError,
43 PullRequestThreadRequiredError,
44 PullRequestGuideFailedError,
45 PullRequestProjectNotFoundError,
46 PullRequestsToolkit,
47 type ThreadPullRequestEntry,
48} from "./tools.ts";
49
50interface ResolvedTarget {
51 readonly host: string;
52 readonly repository: string;
53 readonly number: number;
54 readonly url: string;
55}
56
57function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
58 readonly host: string | null;
59 readonly kind: SourceControlProviderKind | null;
60} {
61 const identity = project?.repositoryIdentity;
62 const kind = identity?.provider ?? null;
63 if (!identity || kind === null) return { host: null, kind: null };
64 return {
65 host: sourceControlDefinitions.changeRequestHost(identity, kind),
66 kind,
67 };
68}
69
70const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
71 input: PullRequestTargetInput,
72 project: OrchestrationProjectShell | undefined,
73) {
74 if (input.url !== undefined) {
75 const parsed = sourceControlDefinitions.parseChangeRequestUrl(input.url)?.link;
76 if (parsed === undefined) {
77 return yield* new PullRequestUrlInvalidError({});
78 }
79 return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;
80 }
81 if (input.repository === undefined || input.number === undefined) {
82 return yield* new PullRequestTargetIncompleteError({});
83 }
84 const projectHost = projectHostAndProvider(project);
85 const host = (input.host ?? projectHost.host)?.toLowerCase();
86 if (host === undefined) {
87 return yield* new PullRequestHostRequiredError({});
88 }
89 const repository = input.repository.toLowerCase();
90 // Without a URL, a public forge host says what shape its change request URLs take;
91 // any other host is taken to run the project's own forge.
92 const kind = sourceControlDefinitions.findByPublicHost(host)?.kind ?? projectHost.kind;
93 const url =
94 kind === null
95 ? null
96 : sourceControlDefinitions.get(kind).changeRequestUrl({
97 host,
98 repository,
99 number: input.number,
100 remoteUrl: project?.repositoryIdentity?.locator.remoteUrl,
101 });
102 if (url === null) {
103 return yield* new PullRequestUrlUnavailableError({});
104 }
105 return {
106 ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
107 url,
108 } satisfies ResolvedTarget;
109});
110
111function entryOf(
112 link: ThreadPullRequestLink,
113 chains: ReturnType<typeof resolveThreadPullRequestChains>,
114): ThreadPullRequestEntry {
115 const key = threadPullRequestKeyOf(link);
116 let stack: ThreadPullRequestEntry["stack"] = null;
117 for (const chain of chains) {
118 if (chain.layers.length < 2) continue;
119 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
120 if (index !== -1) {
121 stack = { kind: chain.kind, position: chain.depths[index]! + 1, size: chain.layers.length };
122 break;
123 }
124 }
125 return {
126 host: normalizeThreadPullRequestKey(link).host,
127 repository: link.repository,
128 number: link.number,
129 url: link.url,
130 source: link.source,
131 watching: link.watch !== undefined,
132 state: link.snapshot?.state ?? null,
133 title: link.snapshot?.title ?? null,
134 headBranch: link.snapshot?.headBranch ?? null,
135 baseBranch: link.snapshot?.baseBranch ?? null,
136 isDraft: link.snapshot?.isDraft ?? null,
137 stack,
138 };
139}
140
141export function listThreadPullRequests(
142 thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
143): ListThreadPullRequestsResult {
144 const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
145 return {
146 pullRequests: visibleThreadPullRequests(thread.pullRequests ?? []).map((link) =>
147 entryOf(link, chains),
148 ),
149 chains: chains.map((chain) => ({
150 kind: chain.kind,
151 numbers: chain.layers.map((layer) => layer.number),
152 })),
153 };
154}
155
156function projectForPullRequest(
157 projects: ReadonlyArray<OrchestrationProjectShell>,
158 target: { readonly host: string; readonly repository: string },
159 preferred: OrchestrationProjectShell | undefined,
160): OrchestrationProjectShell | undefined {
161 // The same rule the guide service uses: a pull request reads through a project whose checkout
162 // names it with the same host-level key, which also maps Azure DevOps' org/project/_git/repo.
163 const matches = (project: OrchestrationProjectShell) => {
164 const own = pullRequestSyncKey(
165 { projectId: project.id, host: target.host, repository: target.repository, number: 1 },
166 project.repositoryIdentity ?? undefined,
167 );
168 const projectKey =
169 project.repositoryIdentity == null
170 ? null
171 : pullRequestSyncKey(
172 {
173 projectId: project.id,
174 repository:
175 sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? "",
176 number: 1,
177 },
178 project.repositoryIdentity,
179 );
180 return (
181 own !== null &&
182 projectKey !== null &&
183 own.host === projectKey.host &&
184 own.repository === projectKey.repository
185 );
186 };
187 if (preferred !== undefined && matches(preferred)) return preferred;
188 return projects.find(matches);
189}
190
191const make = Effect.gen(function* () {
192 const engine = yield* Orchestrator.OrchestratorV2;
193 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
194
195 const projects = yield* ProjectService.ProjectService;
196 const crypto = yield* Crypto.Crypto;
197
198 const commandId = (tag: string, threadId: ThreadId) =>
199 crypto.randomUUIDv4().pipe(
200 Effect.orDie,
201 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
202 );
203
204 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
205 Failure:
206 | typeof PullRequestLinkFailedError
207 | typeof PullRequestUnlinkFailedError
208 | typeof PullRequestListFailedError
209 | typeof PullRequestWatchFailedError,
210 requested: ThreadId | undefined,
211 ) {
212 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
213 const threadId = requested ?? scope.thread?.threadId;
214 if (threadId === undefined) {
215 return yield* new PullRequestThreadRequiredError();
216 }
217 const thread = yield* engine
218 .getThreadShell(threadId)
219 .pipe(Effect.map(Option.fromNullishOr))
220 .pipe(Effect.mapError((cause) => new Failure({ cause })));
221 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
222 return yield* new PullRequestThreadNotFoundError({ threadId });
223 }
224 return thread.value;
225 });
226
227 const projectOf = (
228 thread: OrchestrationV2ThreadShell,
229 Failure:
230 | typeof PullRequestLinkFailedError
231 | typeof PullRequestUnlinkFailedError
232 | typeof PullRequestWatchFailedError,
233 ) =>
234 projects.getShell(thread.projectId).pipe(
235 Effect.map(Option.getOrUndefined),
236 Effect.mapError((cause) => new Failure({ cause })),
237 );
238
239 const dispatchFailure =
240 (
241 Failure:
242 | typeof PullRequestLinkFailedError
243 | typeof PullRequestUnlinkFailedError
244 | typeof PullRequestWatchFailedError,
245 ) =>
246 <E>(
247 cause: Cause.Cause<E>,
248 ): Effect.Effect<
249 never,
250 PullRequestLinkFailedError | PullRequestUnlinkFailedError | PullRequestWatchFailedError
251 > =>
252 Cause.hasInterruptsOnly(cause)
253 ? Effect.failCause(cause as Cause.Cause<never>)
254 : Effect.fail(new Failure({ cause }));
255
256 const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (
257 input: PullRequestTargetInput,
258 watching: boolean,
259 ) {
260 const thread = yield* requireThread(PullRequestWatchFailedError, input.threadId);
261 const project = yield* projectOf(thread, PullRequestWatchFailedError);
262 const target = yield* resolveTarget(input, project);
263 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
264 threadPullRequestsOf(shell).find(
265 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
266 );
267 if (watching && thread.lineage.relationshipToParent === "subagent") {
268 return yield* new PullRequestWatchFromSubagentError();
269 }
270 const before = watchedLink(thread);
271 if (watching && before?.snapshot?.state === "merged") {
272 return yield* new PullRequestNotOpenError({ state: "merged" });
273 }
274 yield* engine
275 .dispatch({
276 type: "thread.pull-request.watch",
277 commandId: yield* commandId("mcp-pr-watch", thread.id),
278 threadId: thread.id,
279 host: target.host,
280 repository: target.repository,
281 number: target.number,
282 watching,
283 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
284 })
285 .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));
286 const after = yield* requireThread(PullRequestWatchFailedError, thread.id);
287 return {
288 host: target.host,
289 repository: target.repository,
290 number: target.number,
291 url: target.url,
292 watching: watchedLink(after)?.watch !== undefined,
293 wasWatching: before?.watch !== undefined,
294 };
295 });
296
297 const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
298 targets: ReadonlyArray<Omit<PullRequestTargetInput, "threadId">>,
299 ) {
300 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
301 const callerThread =
302 scope.thread === undefined
303 ? undefined
304 : yield* engine.getThreadShell(scope.thread.threadId).pipe(
305 Effect.orElseSucceed(() => null),
306 Effect.map((shell) => shell ?? undefined),
307 );
308 const known = yield* projects
309 .listShells()
310 .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
311 const callerProject = known.find((project) => project.id === callerThread?.projectId);
312 // A pull request named by host and repository builds its URL through the project that holds
313 // it, which need not be the caller's.
314 const urlProject = (input: PullRequestTargetInput) =>
315 input.url === undefined && input.host !== undefined && input.repository !== undefined
316 ? (projectForPullRequest(
317 known,
318 { host: input.host, repository: input.repository },
319 callerProject,
320 ) ?? callerProject)
321 : callerProject;
322 return yield* Effect.forEach(targets, (input) =>
323 resolveTarget(input, urlProject(input)).pipe(
324 Effect.map((target) => ({
325 input,
326 target,
327 project: projectForPullRequest(known, target, callerProject),
328 failure: null,
329 })),
330 Effect.catch((error) =>
331 Effect.succeed({ input, target: null, project: undefined, failure: error.message }),
332 ),
333 ),
334 );
335 });
336
337 const guideReference = (
338 project: OrchestrationProjectShell,
339 target: { readonly host: string; readonly repository: string; readonly number: number },
340 ) => ({
341 projectId: project.id,
342 host: target.host,
343 repository: target.repository,
344 number: target.number,
345 });
346
347 const guideFailureDetail = (error: { readonly message: string }) =>
348 "detail" in error && typeof error.detail === "string" ? error.detail : error.message;
349
350 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
351 handle: (params: P) => Effect.Effect<A, E, R>,
352 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
353
354 return {
355 link_pull_request: writesThread((input) =>
356 Effect.gen(function* () {
357 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
358 const project = yield* projectOf(thread, PullRequestLinkFailedError);
359 const target = yield* resolveTarget(input, project);
360 const existing = threadPullRequestsOf(thread).find((link) =>
361 threadPullRequestKeysEqual(link, target),
362 );
363 if (existing && existing.source !== "stack-dismissed")
364 return { ...target, alreadyLinked: true };
365 const alreadyLinked = yield* engine
366 .dispatch({
367 type: "thread.pull-request.link",
368 commandId: yield* commandId("mcp-pr-link", thread.id),
369 threadId: thread.id,
370 host: target.host,
371 repository: target.repository,
372 number: target.number,
373 url: target.url,
374 source: "agent",
375 })
376 .pipe(
377 Effect.as(false),
378
379 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
380 );
381 return { ...target, alreadyLinked };
382 }),
383 ),
384 unlink_pull_request: writesThread((input) =>
385 Effect.gen(function* () {
386 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
387 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
388 const target = yield* resolveTarget(input, project);
389 if (!threadPullRequestsOf(thread).some((link) => threadPullRequestKeysEqual(link, target)))
390 return {
391 host: target.host,
392 repository: target.repository,
393 number: target.number,
394 wasLinked: false,
395 };
396 const wasLinked = yield* engine
397 .dispatch({
398 type: "thread.pull-request.unlink",
399 commandId: yield* commandId("mcp-pr-unlink", thread.id),
400 threadId: thread.id,
401 host: target.host,
402 repository: target.repository,
403 number: target.number,
404 })
405 .pipe(
406 Effect.as(true),
407
408 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
409 );
410 return {
411 host: target.host,
412 repository: target.repository,
413 number: target.number,
414 wasLinked,
415 };
416 }),
417 ),
418 list_thread_pull_requests: McpToolAccess.reads((input) =>
419 requireThread(PullRequestListFailedError, input.threadId).pipe(
420 Effect.map(listThreadPullRequests),
421 ),
422 ),
423 watch_pull_request: writesThread((input) => setWatching(input, true)),
424 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
425 write_pull_request_guides: McpToolAccess.writesWithCapability((input) =>
426 Effect.gen(function* () {
427 const located = yield* locateAll(input.pullRequests);
428 const guides = yield* Effect.forEach(
429 located,
430 (entry) =>
431 Effect.gen(function* () {
432 if (entry.target === null) {
433 return {
434 host: entry.input.host ?? "",
435 repository: entry.input.repository ?? "",
436 number: entry.input.number ?? 0,
437 url: entry.input.url ?? "",
438 outcome: "failed" as const,
439 detail: entry.failure,
440 };
441 }
442 const identity = {
443 host: entry.target.host,
444 repository: entry.target.repository,
445 number: entry.target.number,
446 url: entry.target.url,
447 };
448 if (entry.project === undefined) {
449 return {
450 ...identity,
451 outcome: "failed" as const,
452 detail: new PullRequestProjectNotFoundError({
453 repository: entry.target.repository,
454 }).message,
455 };
456 }
457 return yield* reviewGuides.generate(guideReference(entry.project, entry.target)).pipe(
458 Effect.map((result) => ({
459 ...identity,
460 outcome: result.started ? ("started" as const) : ("running" as const),
461 detail: null,
462 })),
463 Effect.catch((error) =>
464 Effect.succeed({
465 ...identity,
466 outcome: "failed" as const,
467 detail: guideFailureDetail(error),
468 }),
469 ),
470 );
471 }),
472 { concurrency: 4 },
473 );
474 return { guides };
475 }),
476 ),
477 read_pull_request_guide: McpToolAccess.reads((input) =>
478 Effect.gen(function* () {
479 const [entry] = yield* locateAll([input]);
480 if (entry !== undefined && entry.target === null) {
481 return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" });
482 }
483 if (entry === undefined || entry.target === null || entry.project === undefined) {
484 return yield* new PullRequestProjectNotFoundError({
485 repository: entry?.target.repository ?? input.repository ?? "",
486 });
487 }
488 const result = yield* reviewGuides.get(guideReference(entry.project, entry.target)).pipe(
489 Effect.mapError(
490 (error) =>
491 new PullRequestGuideFailedError({
492 detail: guideFailureDetail(error),
493 cause: error,
494 }),
495 ),
496 );
497 return {
498 host: entry.target.host,
499 repository: entry.target.repository,
500 number: entry.target.number,
501 url: entry.target.url,
502 guide: result.guide,
503 run: result.run,
504 currentHeadSha: result.currentHeadSha,
505 stale:
506 result.guide !== null &&
507 result.currentHeadSha !== null &&
508 result.guide.headSha !== result.currentHeadSha,
509 };
510 }),
511 ),
512 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
513});
514
515export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);