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

tools.ts

479 lines16.5 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 PullRequestLinkFailedError extends Schema.TaggedError<PullRequestLinkFailedError>()(
108 "PullRequestLinkFailedError",
109 { cause: Schema.Defect() },
110) {
111 override get message(): string {
112 return "Could not link the pull request.";
113 }
115​
116export class PullRequestUnlinkFailedError extends Schema.TaggedError<PullRequestUnlinkFailedError>()(
117 "PullRequestUnlinkFailedError",
118 { cause: Schema.Defect() },
119) {
120 override get message(): string {
121 return "Could not unlink the pull request.";
122 }
124​
125export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
126 "PullRequestWatchFailedError",
127 { cause: Schema.Defect() },
128) {
129 override get message(): string {
130 return "Could not change whether the pull request is watched.";
131 }
133​
134export class PullRequestNotOpenError extends Schema.TaggedError<PullRequestNotOpenError>()(
135 "PullRequestNotOpenError",
136 { state: Schema.String },
137) {
138 override get message(): string {
139 return `The pull request is ${this.state}, so there is nothing to watch.`;
140 }
142​
143export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
144 "PullRequestWatchFromSubagentError",
145 {},
146) {
147 override get message(): string {
148 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.";
149 }
151​
152export class PullRequestListFailedError extends Schema.TaggedError<PullRequestListFailedError>()(
153 "PullRequestListFailedError",
154 { cause: Schema.Defect() },
155) {
156 override get message(): string {
157 return "Could not list the pull request.";
158 }
160​
161export class PullRequestProjectNotFoundError extends Schema.TaggedError<PullRequestProjectNotFoundError>()(
162 "PullRequestProjectNotFoundError",
163 { repository: Schema.String },
164) {
165 override get message(): string {
166 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.`;
167 }
169​
170export class PullRequestGuideFailedError extends Schema.TaggedError<PullRequestGuideFailedError>()(
171 "PullRequestGuideFailedError",
172 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
173) {
174 override get message(): string {
175 return this.detail;
176 }
178​
179export const PullRequestToolError = Schema.Union([
180 OrchestratorMcpFailure,
181 McpCapabilityUnavailableError,
182 PullRequestUrlInvalidError,
183 PullRequestTargetIncompleteError,
184 PullRequestHostRequiredError,
185 PullRequestUrlUnavailableError,
186 PullRequestThreadRequiredError,
187 PullRequestLinkFailedError,
188 PullRequestUnlinkFailedError,
189 PullRequestListFailedError,
190 PullRequestWatchFailedError,
191 PullRequestNotOpenError,
192 PullRequestWatchFromSubagentError,
193 PullRequestProjectNotFoundError,
194 PullRequestGuideFailedError,
195]);
196export type PullRequestToolError = typeof PullRequestToolError.Type;
197​
198const PullRequestIdentity = {
199 host: Schema.String,
200 repository: Schema.String,
201 number: Schema.Int,
202 url: Schema.String,
203};
204​
205/** A delegated child's report is how its parent learns the PR, so the link result asks for it. */
206export const CHILD_PULL_REQUEST_REPORT_NEXT =
207 "End your reply with: PR <full URL>, head <SHA>, checks and reviews <state>.";
208​
209export const LinkPullRequestResult = Schema.Struct({
210 ...PullRequestIdentity,
211 alreadyLinked: Schema.Boolean,
212 next: Schema.optional(Schema.String),
213});
214export type LinkPullRequestResult = typeof LinkPullRequestResult.Type;
215​
216const PullRequestNumbersByRepository = Schema.Array(
217 Schema.Struct({
218 host: Schema.String,
219 repository: Schema.String,
220 numbers: Schema.Array(Schema.Int),
221 }),
222);
223​
224export const LinkPullRequestsResult = Schema.Struct({
225 linked: PullRequestNumbersByRepository,
226 alreadyLinked: PullRequestNumbersByRepository,
227 linkedCount: Schema.Int,
228 invalidUrls: Schema.optional(Schema.Array(Schema.String)),
229 next: Schema.optional(Schema.String),
230});
231export type LinkPullRequestsResult = typeof LinkPullRequestsResult.Type;
232​
233export const UnlinkPullRequestResult = Schema.Struct({
234 host: Schema.String,
235 repository: Schema.String,
236 number: Schema.Int,
237 wasLinked: Schema.Boolean,
238});
239export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type;
240​
241export const UnlinkPullRequestsResult = Schema.Struct({
242 unlinked: Schema.Array(
243 Schema.Struct({
244 host: Schema.String,
245 repository: Schema.String,
246 state: PullRequestState,
247 numbers: Schema.Array(Schema.Int),
248 }),
249 ),
250 unlinkedCount: Schema.Int,
251 remaining: Schema.Int,
252});
253export type UnlinkPullRequestsResult = typeof UnlinkPullRequestsResult.Type;
254​
255export const WatchPullRequestResult = Schema.Struct({
256 ...PullRequestIdentity,
257 watching: Schema.Boolean,
258 wasWatching: Schema.Boolean,
259});
260export type WatchPullRequestResult = typeof WatchPullRequestResult.Type;
261​
262export const ThreadPullRequestEntry = Schema.Struct({
263 ...PullRequestIdentity,
264 source: ThreadPullRequestLinkSource,
265 watching: Schema.Boolean,
266 state: Schema.NullOr(PullRequestState),
267 title: Schema.NullOr(Schema.String),
268 headBranch: Schema.NullOr(Schema.String),
269 baseBranch: Schema.NullOr(Schema.String),
270 isDraft: Schema.NullOr(Schema.Boolean),
271 stack: Schema.NullOr(
272 Schema.Struct({
273 kind: Schema.Literals(["native", "derived"]),
274 /** 1-based layer from the bottom; siblings share a layer. */
275 position: Schema.Int,
276 size: Schema.Int,
277 }),
278 ),
279});
280export type ThreadPullRequestEntry = typeof ThreadPullRequestEntry.Type;
281​
282export const ListThreadPullRequestsResult = Schema.Struct({
283 pullRequests: Schema.Array(ThreadPullRequestEntry),
284 chains: Schema.Array(
285 Schema.Struct({
286 kind: Schema.Literals(["native", "derived"]),
287 /** Bottom to top; each pull request comes before the ones built on it. */
288 numbers: Schema.Array(Schema.Int),
289 }),
290 ),
291});
292export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type;
293​
294const LinkPullRequestTool = Tool.make("link_pull_request", {
295 description:
296 "Link a PR to this thread. T3 shows its status and settles the thread on merge. For several PRs, use `link_pull_requests`.",
297 parameters: PullRequestTargetInput,
298 success: LinkPullRequestResult,
299 failure: PullRequestToolError,
300 dependencies,
301})
302 .annotate(Tool.Title, "Link pull request to thread")
303 .annotate(Tool.Readonly, false)
304 .annotate(Tool.Destructive, false)
305 .annotate(Tool.Idempotent, true)
306 .annotate(Tool.OpenWorld, false);
307​
308const LinkPullRequestsTool = Tool.make("link_pull_requests", {
309 description:
310 "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`.",
311 parameters: Schema.Struct({
312 environmentId: OrchestratorMcpEnvironmentTarget,
313 threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
314 urls: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1)),
315 }),
316 success: LinkPullRequestsResult,
317 failure: PullRequestToolError,
318 dependencies,
319})
320 .annotate(Tool.Title, "Link pull requests to thread")
321 .annotate(Tool.Readonly, false)
322 .annotate(Tool.Destructive, false)
323 .annotate(Tool.Idempotent, true)
324 .annotate(Tool.OpenWorld, false);
325​
326const UnlinkPullRequestTool = Tool.make("unlink_pull_request", {
327 description:
328 "Remove a PR link from this thread. Succeeds with `wasLinked=false` when it was not linked.",
329 parameters: PullRequestTargetInput,
330 success: UnlinkPullRequestResult,
331 failure: PullRequestToolError,
332 dependencies,
333})
334 .annotate(Tool.Title, "Unlink pull request from thread")
335 .annotate(Tool.Readonly, false)
336 .annotate(Tool.Destructive, true)
337 .annotate(Tool.Idempotent, true)
338 .annotate(Tool.OpenWorld, false);
339​
340const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", {
341 description:
342 "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.",
343 parameters: Schema.Struct({
344 environmentId: OrchestratorMcpEnvironmentTarget,
345 threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
346 states: Schema.Array(PullRequestState).check(Schema.isMinLength(1)),
347 }),
348 success: UnlinkPullRequestsResult,
349 failure: PullRequestToolError,
350 dependencies,
351})
352 .annotate(Tool.Title, "Unlink pull requests by state")
353 .annotate(Tool.Readonly, false)
354 .annotate(Tool.Destructive, true)
355 .annotate(Tool.Idempotent, true)
356 .annotate(Tool.OpenWorld, false);
357​
358const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
359 description:
360 "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.",
361 parameters: Schema.Struct({
362 environmentId: OrchestratorMcpEnvironmentTarget,
363 threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
364 }),
365 success: ListThreadPullRequestsResult,
366 failure: PullRequestToolError,
367 dependencies,
368})
369 .annotate(Tool.Title, "List thread pull requests")
370 .annotate(Tool.Readonly, true)
371 .annotate(Tool.Destructive, false)
372 .annotate(Tool.Idempotent, true)
373 .annotate(Tool.OpenWorld, false);
374​
375const WatchPullRequestTool = Tool.make("watch_pull_request", {
376 description:
377 "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.",
378 parameters: PullRequestTargetInput,
379 success: WatchPullRequestResult,
380 failure: PullRequestToolError,
381 dependencies,
382})
383 .annotate(Tool.Title, "Watch pull request")
384 .annotate(Tool.Readonly, false)
385 .annotate(Tool.Destructive, false)
386 .annotate(Tool.Idempotent, true)
387 .annotate(Tool.OpenWorld, false)
388 .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents);
389​
390const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
391 description: "Stop watching a PR for this thread. It stays linked.",
392 parameters: PullRequestTargetInput,
393 success: WatchPullRequestResult,
394 failure: PullRequestToolError,
395 dependencies,
396})
397 .annotate(Tool.Title, "Stop watching pull request")
398 .annotate(Tool.Readonly, false)
399 .annotate(Tool.Destructive, false)
400 .annotate(Tool.Idempotent, true)
401 .annotate(Tool.OpenWorld, false)
402 .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents);
403​
404const GuideTarget = Schema.Struct({
405 url: PullRequestTargetInput.fields.url,
406 repository: PullRequestTargetInput.fields.repository,
407 number: PullRequestTargetInput.fields.number,
408 host: PullRequestTargetInput.fields.host,
409});
410​
411const GuideOutcome = Schema.Struct({
412 ...PullRequestIdentity,
413 outcome: Schema.Literals(["started", "running", "failed"]).annotate({
414 description: "started: a run began. running: joined a run for this head. failed: see detail.",
415 }),
416 detail: Schema.NullOr(Schema.String),
417});
418​
419export const WritePullRequestGuidesResult = Schema.Struct({
420 guides: Schema.Array(GuideOutcome),
421});
422export type WritePullRequestGuidesResult = typeof WritePullRequestGuidesResult.Type;
423​
424export const ReadPullRequestGuideResult = Schema.Struct({
425 ...PullRequestIdentity,
426 guide: Schema.NullOr(PullRequestReviewGuide),
427 run: Schema.NullOr(PullRequestReviewGuideRun),
428 currentHeadSha: Schema.NullOr(Schema.String),
429 stale: Schema.Boolean.annotate({
430 description: "True when the PR head moved after the guide was written.",
431 }),
432});
433export type ReadPullRequestGuideResult = typeof ReadPullRequestGuideResult.Type;
434​
435const WritePullRequestGuidesTool = Tool.make("write_pull_request_guides", {
436 description:
437 "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.",
438 parameters: Schema.Struct({
439 environmentId: OrchestratorMcpEnvironmentTarget,
440 pullRequests: Schema.Array(GuideTarget).check(Schema.isMinLength(1), Schema.isMaxLength(20)),
441 }),
442 success: WritePullRequestGuidesResult,
443 failure: PullRequestToolError,
444 dependencies: guideDependencies,
445})
446 .annotate(Tool.Title, "Write pull request guides")
447 .annotate(Tool.Readonly, false)
448 .annotate(Tool.Destructive, false)
449 .annotate(Tool.Idempotent, false)
450 .annotate(Tool.OpenWorld, true);
451​
452const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", {
453 description:
454 "Read a PR's stored review guide and run state. `guide` is null when none exists. Never starts a run.",
455 parameters: Schema.Struct({
456 environmentId: OrchestratorMcpEnvironmentTarget,
457 ...GuideTarget.fields,
458 }),
459 success: ReadPullRequestGuideResult,
460 failure: PullRequestToolError,
461 dependencies: guideDependencies,
462})
463 .annotate(Tool.Title, "Read pull request guide")
464 .annotate(Tool.Readonly, true)
465 .annotate(Tool.Destructive, false)
466 .annotate(Tool.Idempotent, true)
467 .annotate(Tool.OpenWorld, true);
468​
469export const PullRequestsToolkit = Toolkit.make(
470 LinkPullRequestTool,
471 LinkPullRequestsTool,
472 UnlinkPullRequestTool,
473 UnlinkPullRequestsTool,
474 ListThreadPullRequestsTool,
475 WatchPullRequestTool,
476 UnwatchPullRequestTool,
477 WritePullRequestGuidesTool,
478 ReadPullRequestGuideTool,
479);