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