Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

tools.ts

489 lines16.8 KB

1import {
2 McpCapabilityUnavailableError,
3 OrchestratorMcpEnvironmentTarget,
4 OrchestratorMcpFailure,
5 PositiveInt,
6 PullRequestReviewGuide,
7 PullRequestReviewGuideRun,
8 PullRequestState,
9 ThreadPullRequestLinkSource,
10 TrimmedNonEmptyString,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Schema from "effect/Schema";
14import * as McpSchema from "effect/ai/McpSchema";
15import * as Tool from "effect/ai/Tool";
16import * as Toolkit from "effect/ai/Toolkit";
17​
18import * as McpInvocationContext from "../../McpInvocationContext.ts";
19import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
20import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
21import * as ProjectService from "../../../project/ProjectService.ts";
22import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
23​
24const dependencies = [
25 McpInvocationContext.McpInvocationContext,
26 ThreadManagementService.ThreadManagementService,
27 Orchestrator.OrchestratorV2,
28 ProjectService.ProjectService,
29];
30​
31const guideDependencies = [
32 ...dependencies,
33 PullRequestReviewGuideService.PullRequestReviewGuideService,
34];
35​
36export const PullRequestTargetInput = Schema.Struct({
37 environmentId: OrchestratorMcpEnvironmentTarget,
38 threadId: Schema.optional(
39 ThreadId.annotate({
40 description: "Thread. Default: this thread.",
41 }),
42 ),
43 url: Schema.optional(TrimmedNonEmptyString),
44 repository: Schema.optional(
45 TrimmedNonEmptyString.annotate({
46 description: "With `number`, when no `url`.",
47 }),
48 ),
49 number: Schema.optional(
50 PositiveInt.annotate({
51 description: "With `repository`, when no `url`.",
52 }),
53 ),
54 host: Schema.optional(
55 TrimmedNonEmptyString.annotate({
56 description: "Default: this project's host.",
57 }),
58 ),
59});
60export type PullRequestTargetInput = typeof PullRequestTargetInput.Type;
61​
62export class PullRequestUrlInvalidError extends Schema.TaggedError<PullRequestUrlInvalidError>()(
63 "PullRequestUrlInvalidError",
64 {},
65) {
66 override get message(): string {
67 return "This is not a recognised pull request URL. Pass repository and number instead.";
68 }
70​
71export class PullRequestTargetIncompleteError extends Schema.TaggedError<PullRequestTargetIncompleteError>()(
72 "PullRequestTargetIncompleteError",
73 {},
74) {
75 override get message(): string {
76 return "Pass either url, or both repository and number.";
77 }
79​
80export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequestHostRequiredError>()(
81 "PullRequestHostRequiredError",
82 {},
83) {
84 override get message(): string {
85 return "This thread's project has no recognised remote. Pass host or url.";
86 }
88​
89export class PullRequestUrlUnavailableError extends Schema.TaggedError<PullRequestUrlUnavailableError>()(
90 "PullRequestUrlUnavailableError",
91 {},
92) {
93 override get message(): string {
94 return "This thread's project is on a host with no known pull request URL shape. Pass url.";
95 }
97​
98export class PullRequestThreadRequiredError extends Schema.TaggedError<PullRequestThreadRequiredError>()(
99 "PullRequestThreadRequiredError",
100 {},
101) {
102 override get message(): string {
103 return "Pass threadId: this MCP client is not running inside a T3 thread.";
104 }
106​
107export class PullRequestThreadNotFoundError extends Schema.TaggedError<PullRequestThreadNotFoundError>()(
108 "PullRequestThreadNotFoundError",
109 { threadId: Schema.String },
110) {
111 override get message(): string {
112 return `Thread ${this.threadId} was not found.`;
113 }
115​
116export class PullRequestLinkFailedError extends Schema.TaggedError<PullRequestLinkFailedError>()(
117 "PullRequestLinkFailedError",
118 { cause: Schema.Defect() },
119) {
120 override get message(): string {
121 return "Could not link the pull request.";
122 }
124​
125export class PullRequestUnlinkFailedError extends Schema.TaggedError<PullRequestUnlinkFailedError>()(
126 "PullRequestUnlinkFailedError",
127 { cause: Schema.Defect() },
128) {
129 override get message(): string {
130 return "Could not unlink the pull request.";
131 }
133​
134export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
135 "PullRequestWatchFailedError",
136 { cause: Schema.Defect() },
137) {
138 override get message(): string {
139 return "Could not change whether the pull request is watched.";
140 }
142​
143export class PullRequestNotOpenError extends Schema.TaggedError<PullRequestNotOpenError>()(
144 "PullRequestNotOpenError",
145 { state: Schema.String },
146) {
147 override get message(): string {
148 return `The pull request is ${this.state}, so there is nothing to watch.`;
149 }
151​
152export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
153 "PullRequestWatchFromSubagentError",
154 {},
155) {
156 override get message(): string {
157 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.";
158 }
160​
161export class PullRequestListFailedError extends Schema.TaggedError<PullRequestListFailedError>()(
162 "PullRequestListFailedError",
163 { cause: Schema.Defect() },
164) {
165 override get message(): string {
166 return "Could not list the pull request.";
167 }
169​
170export class PullRequestProjectNotFoundError extends Schema.TaggedError<PullRequestProjectNotFoundError>()(
171 "PullRequestProjectNotFoundError",
172 { repository: Schema.String },
173) {
174 override get message(): string {
175 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.`;
176 }
178​
179export class PullRequestGuideFailedError extends Schema.TaggedError<PullRequestGuideFailedError>()(
180 "PullRequestGuideFailedError",
181 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
182) {
183 override get message(): string {
184 return this.detail;
185 }
187​
188export const PullRequestToolError = Schema.Union([
189 OrchestratorMcpFailure,
190 McpCapabilityUnavailableError,
191 PullRequestUrlInvalidError,
192 PullRequestTargetIncompleteError,
193 PullRequestHostRequiredError,
194 PullRequestUrlUnavailableError,
195 PullRequestThreadRequiredError,
196 PullRequestThreadNotFoundError,
197 PullRequestLinkFailedError,
198 PullRequestUnlinkFailedError,
199 PullRequestListFailedError,
200 PullRequestWatchFailedError,
201 PullRequestNotOpenError,
202 PullRequestWatchFromSubagentError,
203 PullRequestProjectNotFoundError,
204 PullRequestGuideFailedError,
205]);
206export type PullRequestToolError = typeof PullRequestToolError.Type;
207​
208const PullRequestIdentity = {
209 host: Schema.String,
210 repository: Schema.String,
211 number: Schema.Int,
212 url: Schema.String,
213};
214​
215/** A delegated child's report is how its parent learns the PR, so the link result asks for it. */
216export const CHILD_PULL_REQUEST_REPORT_NEXT =
217 "End your reply with: PR <full URL>, head <SHA>, checks and reviews <state>.";
218​
219export const LinkPullRequestResult = Schema.Struct({
220 ...PullRequestIdentity,
221 alreadyLinked: Schema.Boolean,
222 next: Schema.optional(Schema.String),
223});
224export type LinkPullRequestResult = typeof LinkPullRequestResult.Type;
225​
226const PullRequestNumbersByRepository = Schema.Array(
227 Schema.Struct({
228 host: Schema.String,
229 repository: Schema.String,
230 numbers: Schema.Array(Schema.Int),
231 }),
232);
233​
234export const LinkPullRequestsResult = Schema.Struct({
235 linked: PullRequestNumbersByRepository,
236 alreadyLinked: PullRequestNumbersByRepository,
237 linkedCount: Schema.Int,
238 invalidUrls: Schema.optional(Schema.Array(Schema.String)),
239 next: Schema.optional(Schema.String),
240});
241export type LinkPullRequestsResult = typeof LinkPullRequestsResult.Type;
242​
243export const UnlinkPullRequestResult = Schema.Struct({
244 host: Schema.String,
245 repository: Schema.String,
246 number: Schema.Int,
247 wasLinked: Schema.Boolean,
248});
249export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type;
250​
251export const UnlinkPullRequestsResult = Schema.Struct({
252 unlinked: Schema.Array(
253 Schema.Struct({
254 host: Schema.String,
255 repository: Schema.String,
256 state: PullRequestState,
257 numbers: Schema.Array(Schema.Int),
258 }),
259 ),
260 unlinkedCount: Schema.Int,
261 remaining: Schema.Int,
262});
263export type UnlinkPullRequestsResult = typeof UnlinkPullRequestsResult.Type;
264​
265export const WatchPullRequestResult = Schema.Struct({
266 ...PullRequestIdentity,
267 watching: Schema.Boolean,
268 wasWatching: Schema.Boolean,
269});
270export type WatchPullRequestResult = typeof WatchPullRequestResult.Type;
271​
272export const ThreadPullRequestEntry = Schema.Struct({
273 ...PullRequestIdentity,
274 source: ThreadPullRequestLinkSource,
275 watching: Schema.Boolean,
276 state: Schema.NullOr(PullRequestState),
277 title: Schema.NullOr(Schema.String),
278 headBranch: Schema.NullOr(Schema.String),
279 baseBranch: Schema.NullOr(Schema.String),
280 isDraft: Schema.NullOr(Schema.Boolean),
281 stack: Schema.NullOr(
282 Schema.Struct({
283 kind: Schema.Literals(["native", "derived"]),
284 /** 1-based layer from the bottom; siblings share a layer. */
285 position: Schema.Int,
286 size: Schema.Int,
287 }),
288 ),
289});
290export type ThreadPullRequestEntry = typeof ThreadPullRequestEntry.Type;
291​
292export const ListThreadPullRequestsResult = Schema.Struct({
293 pullRequests: Schema.Array(ThreadPullRequestEntry),
294 chains: Schema.Array(
295 Schema.Struct({
296 kind: Schema.Literals(["native", "derived"]),
297 /** Bottom to top; each pull request comes before the ones built on it. */
298 numbers: Schema.Array(Schema.Int),
299 }),
300 ),
301});
302export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type;
303​
304const LinkPullRequestTool = Tool.make("link_pull_request", {
305 description:
306 "Link a PR to this thread. T3 shows its status and settles the thread on merge. For several PRs, use `link_pull_requests`.",
307 parameters: PullRequestTargetInput,
308 success: LinkPullRequestResult,
309 failure: PullRequestToolError,
310 dependencies,
311})
312 .annotate(Tool.Title, "Link pull request to thread")
313 .annotate(Tool.Readonly, false)
314 .annotate(Tool.Destructive, false)
315 .annotate(Tool.Idempotent, true)
316 .annotate(Tool.OpenWorld, false);
317​
318const LinkPullRequestsTool = Tool.make("link_pull_requests", {
319 description:
320 "Link several PRs to a thread in one call. Use it instead of one `link_pull_request` per PR. URLs that are not PRs come back in `invalidUrls`.",
321 parameters: Schema.Struct({
322 environmentId: OrchestratorMcpEnvironmentTarget,
323 threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
324 urls: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1)),
325 }),
326 success: LinkPullRequestsResult,
327 failure: PullRequestToolError,
328 dependencies,
329})
330 .annotate(Tool.Title, "Link pull requests to thread")
331 .annotate(Tool.Readonly, false)
332 .annotate(Tool.Destructive, false)
333 .annotate(Tool.Idempotent, true)
334 .annotate(Tool.OpenWorld, false);
335​
336const UnlinkPullRequestTool = Tool.make("unlink_pull_request", {
337 description:
338 "Remove a PR link from this thread. Succeeds with `wasLinked=false` when it was not linked.",
339 parameters: PullRequestTargetInput,
340 success: UnlinkPullRequestResult,
341 failure: PullRequestToolError,
342 dependencies,
343})
344 .annotate(Tool.Title, "Unlink pull request from thread")
345 .annotate(Tool.Readonly, false)
346 .annotate(Tool.Destructive, true)
347 .annotate(Tool.Idempotent, true)
348 .annotate(Tool.OpenWorld, false);
349​
350const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", {
351 description:
352 "Unlink every PR on a thread whose last known state (as `list_thread_pull_requests` shows) is in `states`, in one call. Use it instead of one `unlink_pull_request` per PR. PRs with no known state stay linked.",
353 parameters: Schema.Struct({
354 environmentId: OrchestratorMcpEnvironmentTarget,
355 threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
356 states: Schema.Array(PullRequestState).check(Schema.isMinLength(1)),
357 }),
358 success: UnlinkPullRequestsResult,
359 failure: PullRequestToolError,
360 dependencies,
361})
362 .annotate(Tool.Title, "Unlink pull requests by state")
363 .annotate(Tool.Readonly, false)
364 .annotate(Tool.Destructive, true)
365 .annotate(Tool.Idempotent, true)
366 .annotate(Tool.OpenWorld, false);
367​
368const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
369 description:
370 "List PRs linked to a thread, with last known state and stack order (bottom to top). Call only when you need that list. Never as an end-of-work check.",
371 parameters: Schema.Struct({
372 environmentId: OrchestratorMcpEnvironmentTarget,
373 threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
374 }),
375 success: ListThreadPullRequestsResult,
376 failure: PullRequestToolError,
377 dependencies,
378})
379 .annotate(Tool.Title, "List thread pull requests")
380 .annotate(Tool.Readonly, true)
381 .annotate(Tool.Destructive, false)
382 .annotate(Tool.Idempotent, true)
383 .annotate(Tool.OpenWorld, false);
384​
385const WatchPullRequestTool = Tool.make("watch_pull_request", {
386 description:
387 "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.",
388 parameters: PullRequestTargetInput,
389 success: WatchPullRequestResult,
390 failure: PullRequestToolError,
391 dependencies,
392})
393 .annotate(Tool.Title, "Watch pull request")
394 .annotate(Tool.Readonly, false)
395 .annotate(Tool.Destructive, false)
396 .annotate(Tool.Idempotent, true)
397 .annotate(Tool.OpenWorld, false)
398 .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents);
399​
400const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
401 description: "Stop watching a PR for this thread. It stays linked.",
402 parameters: PullRequestTargetInput,
403 success: WatchPullRequestResult,
404 failure: PullRequestToolError,
405 dependencies,
406})
407 .annotate(Tool.Title, "Stop watching pull request")
408 .annotate(Tool.Readonly, false)
409 .annotate(Tool.Destructive, false)
410 .annotate(Tool.Idempotent, true)
411 .annotate(Tool.OpenWorld, false)
412 .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents);
413​
414const GuideTarget = Schema.Struct({
415 url: PullRequestTargetInput.fields.url,
416 repository: PullRequestTargetInput.fields.repository,
417 number: PullRequestTargetInput.fields.number,
418 host: PullRequestTargetInput.fields.host,
419});
420​
421const GuideOutcome = Schema.Struct({
422 ...PullRequestIdentity,
423 outcome: Schema.Literals(["started", "running", "failed"]).annotate({
424 description: "started: a run began. running: joined a run for this head. failed: see detail.",
425 }),
426 detail: Schema.NullOr(Schema.String),
427});
428​
429export const WritePullRequestGuidesResult = Schema.Struct({
430 guides: Schema.Array(GuideOutcome),
431});
432export type WritePullRequestGuidesResult = typeof WritePullRequestGuidesResult.Type;
433​
434export const ReadPullRequestGuideResult = Schema.Struct({
435 ...PullRequestIdentity,
436 guide: Schema.NullOr(PullRequestReviewGuide),
437 run: Schema.NullOr(PullRequestReviewGuideRun),
438 currentHeadSha: Schema.NullOr(Schema.String),
439 stale: Schema.Boolean.annotate({
440 description: "True when the PR head moved after the guide was written.",
441 }),
442});
443export type ReadPullRequestGuideResult = typeof ReadPullRequestGuideResult.Type;
444​
445const WritePullRequestGuidesTool = Tool.make("write_pull_request_guides", {
446 description:
447 "Write review guides for up to 20 PRs (the tour in the PR Guide tab). Returns once runs start. Each run takes minutes in a temporary checkout. A run for the same head is joined. Read with `read_pull_request_guide`. Fails while guides are off.",
448 parameters: Schema.Struct({
449 environmentId: OrchestratorMcpEnvironmentTarget,
450 pullRequests: Schema.Array(GuideTarget).check(Schema.isMinLength(1), Schema.isMaxLength(20)),
451 }),
452 success: WritePullRequestGuidesResult,
453 failure: PullRequestToolError,
454 dependencies: guideDependencies,
455})
456 .annotate(Tool.Title, "Write pull request guides")
457 .annotate(Tool.Readonly, false)
458 .annotate(Tool.Destructive, false)
459 .annotate(Tool.Idempotent, false)
460 .annotate(Tool.OpenWorld, true);
461​
462const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", {
463 description:
464 "Read a PR's stored review guide and run state. `guide` is null when none exists. Never starts a run.",
465 parameters: Schema.Struct({
466 environmentId: OrchestratorMcpEnvironmentTarget,
467 ...GuideTarget.fields,
468 }),
469 success: ReadPullRequestGuideResult,
470 failure: PullRequestToolError,
471 dependencies: guideDependencies,
472})
473 .annotate(Tool.Title, "Read pull request guide")
474 .annotate(Tool.Readonly, true)
475 .annotate(Tool.Destructive, false)
476 .annotate(Tool.Idempotent, true)
477 .annotate(Tool.OpenWorld, true);
478​
479export const PullRequestsToolkit = Toolkit.make(
480 LinkPullRequestTool,
481 LinkPullRequestsTool,
482 UnlinkPullRequestTool,
483 UnlinkPullRequestsTool,
484 ListThreadPullRequestsTool,
485 WatchPullRequestTool,
486 UnwatchPullRequestTool,
487 WritePullRequestGuidesTool,
488 ReadPullRequestGuideTool,
489);