Open History to see the last commit
1import {
2 McpCapabilityUnavailableError,
3 OrchestratorMcpFailure,
4 PositiveInt,
5 PullRequestReviewGuide,
6 PullRequestReviewGuideRun,
7 PullRequestState,
8 ThreadPullRequestLinkSource,
9 TrimmedNonEmptyString,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Schema from "effect/Schema";
13import * as Tool from "effect/ai/Tool";
14import * as Toolkit from "effect/ai/Toolkit";
15
16import * as McpInvocationContext from "../../McpInvocationContext.ts";
17import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
18import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
19import * as ProjectService from "../../../project/ProjectService.ts";
20import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
21
22const dependencies = [
23 McpInvocationContext.McpInvocationContext,
24 ThreadManagementService.ThreadManagementService,
25 Orchestrator.OrchestratorV2,
26 ProjectService.ProjectService,
27];
28
29const guideDependencies = [
30 ...dependencies,
31 PullRequestReviewGuideService.PullRequestReviewGuideService,
32];
33
34const REGISTER_EVERY_PR =
35 "Register every pull request you open for this thread, including each layer of a stack, right after creating it.";
36
37export const PullRequestTargetInput = Schema.Struct({
38 threadId: Schema.optional(
39 ThreadId.annotate({
40 description: "Thread to act on. Omit for this thread.",
41 }),
42 ),
43 url: Schema.optional(
44 TrimmedNonEmptyString.annotate({
45 description:
46 "The pull request's web URL, for example https://github.com/owner/repo/pull/123. Preferred when you have it; host, repository and number are read from it.",
47 }),
48 ),
49 repository: Schema.optional(
50 TrimmedNonEmptyString.annotate({
51 description:
52 "Repository path below the host, for example owner/repo. Required with number when url is omitted.",
53 }),
54 ),
55 number: Schema.optional(
56 PositiveInt.annotate({
57 description: "Pull request number. Required with repository when url is omitted.",
58 }),
59 ),
60 host: Schema.optional(
61 TrimmedNonEmptyString.annotate({
62 description:
63 "Host the repository lives on, for example github.com. Defaults to the host of this thread's project.",
64 }),
65 ),
66});
67export type PullRequestTargetInput = typeof PullRequestTargetInput.Type;
68
69export class PullRequestUrlInvalidError extends Schema.TaggedError<PullRequestUrlInvalidError>()(
70 "PullRequestUrlInvalidError",
71 {},
72) {
73 override get message(): string {
74 return "This is not a recognised pull request URL. Pass repository and number instead.";
75 }
76}
77
78export class PullRequestTargetIncompleteError extends Schema.TaggedError<PullRequestTargetIncompleteError>()(
79 "PullRequestTargetIncompleteError",
80 {},
81) {
82 override get message(): string {
83 return "Pass either url, or both repository and number.";
84 }
85}
86
87export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequestHostRequiredError>()(
88 "PullRequestHostRequiredError",
89 {},
90) {
91 override get message(): string {
92 return "This thread's project has no recognised remote. Pass host or url.";
93 }
94}
95
96export class PullRequestThreadRequiredError extends Schema.TaggedError<PullRequestThreadRequiredError>()(
97 "PullRequestThreadRequiredError",
98 {},
99) {
100 override get message(): string {
101 return "Pass threadId: this MCP client is not running inside a T3 thread.";
102 }
103}
104
105export class PullRequestThreadNotFoundError extends Schema.TaggedError<PullRequestThreadNotFoundError>()(
106 "PullRequestThreadNotFoundError",
107 { threadId: Schema.String },
108) {
109 override get message(): string {
110 return `Thread ${this.threadId} was not found.`;
111 }
112}
113
114export class PullRequestLinkFailedError extends Schema.TaggedError<PullRequestLinkFailedError>()(
115 "PullRequestLinkFailedError",
116 { cause: Schema.Defect() },
117) {
118 override get message(): string {
119 return "Could not link the pull request.";
120 }
121}
122
123export class PullRequestUnlinkFailedError extends Schema.TaggedError<PullRequestUnlinkFailedError>()(
124 "PullRequestUnlinkFailedError",
125 { cause: Schema.Defect() },
126) {
127 override get message(): string {
128 return "Could not unlink the pull request.";
129 }
130}
131
132export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
133 "PullRequestWatchFailedError",
134 { cause: Schema.Defect() },
135) {
136 override get message(): string {
137 return "Could not change whether the pull request is watched.";
138 }
139}
140
141export class PullRequestNotOpenError extends Schema.TaggedError<PullRequestNotOpenError>()(
142 "PullRequestNotOpenError",
143 { state: Schema.String },
144) {
145 override get message(): string {
146 return `The pull request is ${this.state}, so there is nothing to watch.`;
147 }
148}
149
150export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
151 "PullRequestWatchFromSubagentError",
152 {},
153) {
154 override get message(): string {
155 return "This thread is a subagent, so it cannot watch pull requests. Its parent thread owns the pull request: finish your task and report back instead.";
156 }
157}
158
159export class PullRequestListFailedError extends Schema.TaggedError<PullRequestListFailedError>()(
160 "PullRequestListFailedError",
161 { cause: Schema.Defect() },
162) {
163 override get message(): string {
164 return "Could not list the pull request.";
165 }
166}
167
168export class PullRequestProjectNotFoundError extends Schema.TaggedError<PullRequestProjectNotFoundError>()(
169 "PullRequestProjectNotFoundError",
170 { repository: Schema.String },
171) {
172 override get message(): string {
173 return `No project in this environment is a checkout of ${this.repository}, so its pull requests cannot be read here. Add one with t3_project_create.`;
174 }
175}
176
177export class PullRequestGuideFailedError extends Schema.TaggedError<PullRequestGuideFailedError>()(
178 "PullRequestGuideFailedError",
179 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
180) {
181 override get message(): string {
182 return this.detail;
183 }
184}
185
186export const PullRequestToolError = Schema.Union([
187 OrchestratorMcpFailure,
188 McpCapabilityUnavailableError,
189 PullRequestUrlInvalidError,
190 PullRequestTargetIncompleteError,
191 PullRequestHostRequiredError,
192 PullRequestThreadRequiredError,
193 PullRequestThreadNotFoundError,
194 PullRequestLinkFailedError,
195 PullRequestUnlinkFailedError,
196 PullRequestListFailedError,
197 PullRequestWatchFailedError,
198 PullRequestNotOpenError,
199 PullRequestWatchFromSubagentError,
200 PullRequestProjectNotFoundError,
201 PullRequestGuideFailedError,
202]);
203export type PullRequestToolError = typeof PullRequestToolError.Type;
204
205const PullRequestIdentity = {
206 host: Schema.String,
207 repository: Schema.String,
208 number: Schema.Int,
209 url: Schema.String,
210};
211
212export const LinkPullRequestResult = Schema.Struct({
213 ...PullRequestIdentity,
214 alreadyLinked: Schema.Boolean.annotate({
215 description: "True when the pull request was linked to this thread before the call.",
216 }),
217});
218export type LinkPullRequestResult = typeof LinkPullRequestResult.Type;
219
220export const UnlinkPullRequestResult = Schema.Struct({
221 host: Schema.String,
222 repository: Schema.String,
223 number: Schema.Int,
224 wasLinked: Schema.Boolean.annotate({
225 description: "False when the pull request was not linked to this thread to begin with.",
226 }),
227});
228export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type;
229
230export const WatchPullRequestResult = Schema.Struct({
231 ...PullRequestIdentity,
232 watching: Schema.Boolean.annotate({
233 description: "Whether T3 Code now watches the pull request for this thread.",
234 }),
235 wasWatching: Schema.Boolean.annotate({
236 description: "Whether it was already watched before the call.",
237 }),
238});
239export type WatchPullRequestResult = typeof WatchPullRequestResult.Type;
240
241export const ThreadPullRequestEntry = Schema.Struct({
242 ...PullRequestIdentity,
243 source: ThreadPullRequestLinkSource,
244 watching: Schema.Boolean,
245 state: Schema.NullOr(PullRequestState),
246 title: Schema.NullOr(Schema.String),
247 headBranch: Schema.NullOr(Schema.String),
248 baseBranch: Schema.NullOr(Schema.String),
249 isDraft: Schema.NullOr(Schema.Boolean),
250 stack: Schema.NullOr(
251 Schema.Struct({
252 kind: Schema.Literals(["native", "derived"]),
253 /** 1-based layer, bottom of the stack first. Pull requests built on the same one share it. */
254 position: Schema.Int,
255 size: Schema.Int,
256 }),
257 ),
258});
259export type ThreadPullRequestEntry = typeof ThreadPullRequestEntry.Type;
260
261export const ListThreadPullRequestsResult = Schema.Struct({
262 pullRequests: Schema.Array(ThreadPullRequestEntry),
263 chains: Schema.Array(
264 Schema.Struct({
265 kind: Schema.Literals(["native", "derived"]),
266 /** Bottom to top; each pull request comes before the ones built on it. */
267 numbers: Schema.Array(Schema.Int),
268 }),
269 ),
270});
271export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type;
272
273const LinkPullRequestTool = Tool.make("link_pull_request", {
274 description: `${REGISTER_EVERY_PR} Links a pull request to this thread so T3 Code tracks it, shows its status beside the thread, and settles the thread when it merges. Pass the URL, or repository plus number. Linking an already-linked pull request succeeds with alreadyLinked=true.`,
275 parameters: PullRequestTargetInput,
276 success: LinkPullRequestResult,
277 failure: PullRequestToolError,
278 dependencies,
279})
280 .annotate(Tool.Title, "Link pull request to thread")
281 .annotate(Tool.Readonly, false)
282 .annotate(Tool.Destructive, false)
283 .annotate(Tool.Idempotent, true)
284 .annotate(Tool.OpenWorld, false);
285
286const UnlinkPullRequestTool = Tool.make("unlink_pull_request", {
287 description:
288 "Remove a pull request link from this thread, for example after closing a pull request you opened by mistake. Pass the URL, or repository plus number. Unlinking a pull request that is not linked succeeds with wasLinked=false.",
289 parameters: PullRequestTargetInput,
290 success: UnlinkPullRequestResult,
291 failure: PullRequestToolError,
292 dependencies,
293})
294 .annotate(Tool.Title, "Unlink pull request from thread")
295 .annotate(Tool.Readonly, false)
296 .annotate(Tool.Destructive, true)
297 .annotate(Tool.Idempotent, true)
298 .annotate(Tool.OpenWorld, false);
299
300const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
301 description: `List the pull requests linked to a thread (omit threadId for this thread) with their last known host state, and how they chain into stacks (bottom to top). ${REGISTER_EVERY_PR}`,
302 parameters: Schema.Struct({
303 threadId: Schema.optional(
304 ThreadId.annotate({ description: "Thread to list. Omit for this thread." }),
305 ),
306 }),
307 success: ListThreadPullRequestsResult,
308 failure: PullRequestToolError,
309 dependencies,
310})
311 .annotate(Tool.Title, "List thread pull requests")
312 .annotate(Tool.Readonly, true)
313 .annotate(Tool.Destructive, false)
314 .annotate(Tool.Idempotent, true)
315 .annotate(Tool.OpenWorld, false);
316
317const WatchPullRequestTool = Tool.make("watch_pull_request", {
318 description:
319 "Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every two minutes and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles or is archived, when T3 Code fails to read it 8 times in a row (a host rate limit only delays it), when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch. A subagent cannot watch: its parent thread owns the pull request.",
320 parameters: PullRequestTargetInput,
321 success: WatchPullRequestResult,
322 failure: PullRequestToolError,
323 dependencies,
324})
325 .annotate(Tool.Title, "Watch pull request")
326 .annotate(Tool.Readonly, false)
327 .annotate(Tool.Destructive, false)
328 .annotate(Tool.Idempotent, true)
329 .annotate(Tool.OpenWorld, false);
330
331const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
332 description:
333 "Stop T3 Code from watching a pull request for this thread. The pull request stays linked. Pass the URL, or repository plus number.",
334 parameters: PullRequestTargetInput,
335 success: WatchPullRequestResult,
336 failure: PullRequestToolError,
337 dependencies,
338})
339 .annotate(Tool.Title, "Stop watching pull request")
340 .annotate(Tool.Readonly, false)
341 .annotate(Tool.Destructive, false)
342 .annotate(Tool.Idempotent, true)
343 .annotate(Tool.OpenWorld, false);
344
345const GuideTarget = Schema.Struct({
346 url: PullRequestTargetInput.fields.url,
347 repository: PullRequestTargetInput.fields.repository,
348 number: PullRequestTargetInput.fields.number,
349 host: PullRequestTargetInput.fields.host,
350});
351
352const GuideOutcome = Schema.Struct({
353 ...PullRequestIdentity,
354 outcome: Schema.Literals(["started", "running", "failed"]).annotate({
355 description:
356 "started: a run began. running: one was already going for this head and the call joined it. failed: this pull request could not be guided; see detail.",
357 }),
358 detail: Schema.NullOr(Schema.String),
359});
360
361export const WritePullRequestGuidesResult = Schema.Struct({
362 guides: Schema.Array(GuideOutcome),
363});
364export type WritePullRequestGuidesResult = typeof WritePullRequestGuidesResult.Type;
365
366export const ReadPullRequestGuideResult = Schema.Struct({
367 ...PullRequestIdentity,
368 guide: Schema.NullOr(PullRequestReviewGuide),
369 run: Schema.NullOr(PullRequestReviewGuideRun),
370 currentHeadSha: Schema.NullOr(Schema.String),
371 stale: Schema.Boolean.annotate({
372 description:
373 "True when the guide was written for an earlier head than the pull request has now.",
374 }),
375});
376export type ReadPullRequestGuideResult = typeof ReadPullRequestGuideResult.Type;
377
378const WritePullRequestGuidesTool = Tool.make("write_pull_request_guides", {
379 description:
380 "Write review guides for up to 20 pull requests, the tour a maintainer reads in a pull request's Guide tab. Each run reads its change in a temporary checkout and takes minutes, so this returns once the runs are under way; read a guide with read_pull_request_guide to see when it is written. A guide for the same head that is already running is joined, not restarted; a pull request whose guide is current is written again. Each pull request is read through the project in this environment whose checkout has that repository. Fails while review guides are off on this server.",
381 parameters: Schema.Struct({
382 pullRequests: Schema.Array(GuideTarget).check(Schema.isMinLength(1), Schema.isMaxLength(20)),
383 }),
384 success: WritePullRequestGuidesResult,
385 failure: PullRequestToolError,
386 dependencies: guideDependencies,
387})
388 .annotate(Tool.Title, "Write pull request guides")
389 .annotate(Tool.Readonly, false)
390 .annotate(Tool.Destructive, false)
391 .annotate(Tool.Idempotent, false)
392 .annotate(Tool.OpenWorld, true);
393
394const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", {
395 description:
396 "Read a pull request's stored review guide and its run: run.Running while one is being written, run.Failed with the reason when the last one failed, guide null when none was written. stale is true after a push the guide has not caught up with. Never starts a run.",
397 parameters: GuideTarget,
398 success: ReadPullRequestGuideResult,
399 failure: PullRequestToolError,
400 dependencies: guideDependencies,
401})
402 .annotate(Tool.Title, "Read pull request guide")
403 .annotate(Tool.Readonly, true)
404 .annotate(Tool.Destructive, false)
405 .annotate(Tool.Idempotent, true)
406 .annotate(Tool.OpenWorld, true);
407
408export const PullRequestsToolkit = Toolkit.make(
409 LinkPullRequestTool,
410 UnlinkPullRequestTool,
411 ListThreadPullRequestsTool,
412 WatchPullRequestTool,
413 UnwatchPullRequestTool,
414 WritePullRequestGuidesTool,
415 ReadPullRequestGuideTool,
416);