Open History to see the last commit
1import {
2 threadIssueKeysEqual,
3 type IssueDetail,
4 type IssueRef,
5 type OrchestrationV2ThreadShell,
6 type ProjectId,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12
13import * as IssueService from "../../../issue/IssueService.ts";
14import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
15import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
16import * as McpInvocationContext from "../../McpInvocationContext.ts";
17import * as McpToolAccess from "../../McpToolAccess.ts";
18import {
19 IssueLinkFailedError,
20 IssueProjectNotFoundError,
21 IssueProjectRequiredError,
22 IssuesToolkit,
23 IssueTargetIncompleteError,
24 type IssueTargetInput,
25 IssueThreadNotFoundError,
26 IssueThreadRequiredError,
27 type ListThreadIssuesResult,
28} from "./tools.ts";
29
30/** A resolved reference, with the host the link stores and whether it may be written. */
31interface ResolvedTarget extends IssueRef {
32 readonly host: string;
33 readonly url: string | null;
34 readonly writable: boolean;
35 /** Present when resolving the URL already read the issue. */
36 readonly issue?: IssueDetail;
37}
38
39/** What the tools report from a thread shell; exported so the shape is testable without a layer. */
40function listThreadIssues(
41 thread: Pick<OrchestrationV2ThreadShell, "issues">,
42): ListThreadIssuesResult {
43 return {
44 issues: (thread.issues ?? []).map((link) => ({
45 projectId: link.projectId,
46 tracker: link.tracker,
47 host: link.host,
48 scope: link.scope,
49 key: link.key,
50 url: link.url,
51 source: link.source,
52 displayKey: link.displayKey,
53 title: link.title,
54 })),
55 };
56}
57
58const make = Effect.gen(function* () {
59 const engine = yield* Orchestrator.OrchestratorV2;
60 const issues = yield* IssueService.IssueService;
61 const threadIssues = yield* ThreadIssueService.ThreadIssueService;
62
63 /** The caller's own thread, read when a tool defaults to it. */
64 const callerThread = Effect.fn("IssuesToolkit.callerThread")(function* () {
65 const scope = yield* McpInvocationContext.requireMcpCapability("issues");
66 return scope.thread === undefined
67 ? undefined
68 : yield* engine.getThreadShell(scope.thread.threadId).pipe(
69 Effect.orElseSucceed(() => null),
70 Effect.map((shell) => shell ?? undefined),
71 );
72 });
73
74 const requireThread = Effect.fn("IssuesToolkit.requireThread")(function* (
75 requested: ThreadId | undefined,
76 ) {
77 const scope = yield* McpInvocationContext.requireMcpCapability("issues");
78 const threadId = requested ?? scope.thread?.threadId;
79 if (threadId === undefined) return yield* new IssueThreadRequiredError();
80 const thread = yield* engine.getThreadShell(threadId).pipe(
81 Effect.map(Option.fromNullishOr),
82 Effect.mapError((cause) => new IssueLinkFailedError({ cause })),
83 );
84 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
85 return yield* new IssueThreadNotFoundError({ threadId });
86 }
87 return thread.value;
88 });
89
90 /** Where a key-only reference is read: the named project's tracker, or the caller's thread's. */
91 const requireProjectScope = Effect.fn("IssuesToolkit.requireProjectScope")(function* (
92 requested: ProjectId | undefined,
93 select?: { readonly key?: string | undefined; readonly scope?: string | undefined },
94 ) {
95 // A named project skips the caller's thread, so the capability is checked here too.
96 yield* McpInvocationContext.requireMcpCapability("issues");
97 const projectId = requested ?? (yield* callerThread())?.projectId;
98 if (projectId === undefined) return yield* new IssueProjectRequiredError();
99 return yield* issues.projectScope(projectId, select).pipe(
100 Effect.catchTags({
101 IssueUnavailableError: () => Effect.fail(new IssueProjectNotFoundError({ projectId })),
102 }),
103 );
104 });
105
106 /**
107 * Turns whichever shape the agent passed into one reference. A URL resolves through whichever
108 * project here is a checkout of its repository; a key is completed with the named project's
109 * binding, or the caller's thread's project.
110 */
111 const resolveTarget = Effect.fn("IssuesToolkit.resolveTarget")(function* (
112 input: IssueTargetInput,
113 ) {
114 yield* McpInvocationContext.requireMcpCapability("issues");
115 if (input.url !== undefined) {
116 const preferred = input.projectId ?? (yield* callerThread())?.projectId;
117 const resolved = yield* issues.resolveUrl(input.url, preferred);
118 return { ...resolved, url: input.url } satisfies ResolvedTarget;
119 }
120 if (input.key === undefined) return yield* new IssueTargetIncompleteError();
121 const scope = yield* requireProjectScope(input.projectId, { key: input.key });
122 return {
123 ...scope,
124 key: input.key,
125 url: null,
126 writable: true,
127 } satisfies ResolvedTarget;
128 });
129
130 /** Without a URL when the issue was named by key and never read: an empty one is not reusable. */
131 const identityOf = (target: ResolvedTarget) => ({
132 projectId: target.projectId,
133 tracker: target.tracker,
134 host: target.host,
135 scope: target.scope,
136 key: target.key,
137 ...(target.url === null ? {} : { url: target.url }),
138 });
139
140 const refOf = (target: ResolvedTarget): IssueRef & { readonly host: string } => ({
141 projectId: target.projectId,
142 tracker: target.tracker,
143 host: target.host,
144 scope: target.scope,
145 key: target.key,
146 });
147
148 const readIssue = (target: ResolvedTarget) =>
149 target.issue === undefined ? issues.detail(refOf(target)) : Effect.succeed(target.issue);
150
151 /** A link needs the issue's URL, which a key-only reference does not carry; one read fills it. */
152 const linkFailure = <E>(cause: Cause.Cause<E>) =>
153 Cause.hasInterruptsOnly(cause)
154 ? Effect.failCause(cause as Cause.Cause<never>)
155 : Effect.fail(new IssueLinkFailedError({ cause }));
156
157 /** A tool that changes `threadId`, or the caller's own thread when it is omitted. */
158 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
159 handle: (params: P) => Effect.Effect<A, E, R>,
160 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
161
162 return {
163 list_issues: McpToolAccess.reads((input) =>
164 Effect.gen(function* () {
165 const { projectId } = yield* requireProjectScope(input.projectId);
166 const result = yield* issues.list({
167 projectId,
168 state: input.state ?? "open",
169 ...(input.query === undefined ? {} : { query: input.query }),
170 ...(input.limit === undefined ? {} : { limit: input.limit }),
171 ...(input.cursors === undefined ? {} : { cursors: input.cursors }),
172 });
173 return {
174 issues: result.entries.map((entry) => ({
175 projectId: entry.projectId,
176 tracker: entry.tracker,
177 host: entry.host,
178 scope: entry.scope,
179 key: entry.key,
180 url: entry.url,
181 displayKey: entry.displayKey,
182 title: entry.title,
183 state: entry.state,
184 author: entry.author?.login ?? null,
185 assignees: entry.assignees.map((actor) => actor.login),
186 labels: entry.labels.map((label) => label.name),
187 updatedAt: entry.updatedAt,
188 commentCount: entry.commentCount,
189 })),
190 nextCursors: result.nextCursors,
191 errors: result.errors.map((error) => ({
192 projectId: error.projectId,
193 message: error.message,
194 })),
195 };
196 }),
197 ),
198 read_issue: McpToolAccess.reads((input) =>
199 Effect.gen(function* () {
200 const target = yield* resolveTarget(input);
201 const detail = yield* readIssue(target);
202 return {
203 ...identityOf(target),
204 url: target.url ?? detail.url,
205 displayKey: detail.displayKey,
206 title: detail.title,
207 state: detail.state,
208 writable: detail.writable,
209 capabilities: detail.capabilities,
210 states: detail.states,
211 author: detail.author?.login ?? null,
212 assignees: detail.assignees.map((actor) => actor.login),
213 labels: detail.labels.map((label) => label.name),
214 createdAt: detail.createdAt,
215 updatedAt: detail.updatedAt,
216 closedAt: detail.closedAt,
217 body: detail.body,
218 comments: detail.comments.map((comment) => ({
219 id: comment.id,
220 author: comment.author?.login ?? null,
221 body: comment.body,
222 createdAt: comment.createdAt,
223 })),
224 commentsTruncated: detail.commentsCursor !== null,
225 linkedPullRequests: detail.linkedPullRequests.map((pullRequest) => ({
226 url: pullRequest.url,
227 title: pullRequest.title,
228 state: pullRequest.state,
229 closesIssue: pullRequest.closesIssue,
230 })),
231 };
232 }),
233 ),
234 create_issue: McpToolAccess.writesWithCapability((input) =>
235 Effect.gen(function* () {
236 const scope = yield* requireProjectScope(input.projectId, { scope: input.scope });
237 const created = yield* issues.create({
238 ...scope,
239 title: input.title,
240 body: input.body ?? "",
241 labels: input.labels ?? [],
242 assignees: input.assignees ?? [],
243 });
244 return {
245 ...scope,
246 key: created.key,
247 url: created.url,
248 displayKey: created.displayKey,
249 };
250 }),
251 ),
252 comment_on_issue: McpToolAccess.writesWithCapability((input) =>
253 Effect.gen(function* () {
254 const target = yield* resolveTarget(input);
255 yield* issues.comment({ ...refOf(target), body: input.body });
256 return identityOf(target);
257 }),
258 ),
259 set_issue_state: McpToolAccess.writesWithCapability((input) =>
260 Effect.gen(function* () {
261 const target = yield* resolveTarget(input);
262 yield* issues.setState({
263 ...refOf(target),
264 state: input.state,
265 });
266 return identityOf(target);
267 }),
268 ),
269 link_issue: writesThread((input) =>
270 Effect.gen(function* () {
271 const thread = yield* requireThread(input.threadId);
272 const target: ResolvedTarget = yield* resolveTarget({
273 ...input,
274 projectId: input.projectId ?? thread.projectId,
275 });
276 // Reading the issue proves it exists and names it for the thread's row.
277 const issue = target.issue ?? (yield* issues.linkMetadata(refOf(target)));
278 const url = target.url ?? issue.url;
279 const { alreadyLinked } = yield* threadIssues
280 .link({
281 threadId: thread.id,
282 ref: refOf(target),
283 url,
284 displayKey: issue.displayKey,
285 title: issue.title,
286 source: "agent",
287 })
288 .pipe(Effect.catchCause(linkFailure));
289 return { ...identityOf(target), url, alreadyLinked };
290 }),
291 ),
292 unlink_issue: writesThread((input) =>
293 Effect.gen(function* () {
294 const thread = yield* requireThread(input.threadId);
295 const target = yield* resolveTarget({
296 ...input,
297 projectId: input.projectId ?? thread.projectId,
298 });
299 const existing = (thread.issues ?? []).find((link) => threadIssueKeysEqual(link, target));
300 if (existing === undefined) return { ...identityOf(target), wasLinked: false };
301 const { wasLinked } = yield* threadIssues
302 .unlink({ threadId: thread.id, key: target })
303 .pipe(Effect.catchCause(linkFailure));
304 return { ...identityOf(target), url: existing.url, wasLinked };
305 }),
306 ),
307 list_thread_issues: McpToolAccess.reads((input) =>
308 requireThread(input.threadId).pipe(Effect.map(listThreadIssues)),
309 ),
310 } satisfies McpToolAccess.Handlers<typeof IssuesToolkit.tools>;
311});
312
313export const layer = McpToolAccess.toLayer(IssuesToolkit, make);