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

ThreadMetadataMcpService.ts

199 lines6.8 KB

1import {
2 CommandId,
3 McpCapabilityUnavailableError,
4 ThreadId,
5 ThreadMetadataMcpAction,
6 type OrchestrationCommand,
7 type OrchestrationThreadShell,
8 type ThreadMetadataMcpUpdateInput,
9 type ThreadMetadataMcpUpdateResult,
10} from "@t3tools/contracts";
11import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
12import {
13 legacyThreadPullRequestKey,
14 resolveThreadCurrentPullRequestLink,
15} from "@t3tools/shared/threadPullRequests";
16import * as Context from "effect/Context";
17import * as Crypto from "effect/Crypto";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schema from "effect/Schema";
22​
23import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
24import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
25import * as McpInvocationContext from "./McpInvocationContext.ts";
26​
27export class ThreadMetadataThreadNotFoundError extends Schema.TaggedError<ThreadMetadataThreadNotFoundError>()(
28 "ThreadMetadataThreadNotFoundError",
29 { threadId: ThreadId },
30) {
31 override get message(): string {
32 return "Thread not found in the calling project.";
33 }
35​
36export class ThreadMetadataUpdateFailedError extends Schema.TaggedError<ThreadMetadataUpdateFailedError>()(
37 "ThreadMetadataUpdateFailedError",
38 { threadId: ThreadId, action: ThreadMetadataMcpAction, cause: Schema.Defect() },
39) {
40 override get message(): string {
41 return "Could not update thread metadata.";
42 }
44​
45export class ThreadMetadataPullRequestMismatchError extends Schema.TaggedError<ThreadMetadataPullRequestMismatchError>()(
46 "ThreadMetadataPullRequestMismatchError",
47 { threadId: ThreadId },
48) {
49 override get message(): string {
50 return "Pull request repository and number must match its URL.";
51 }
53​
54export class ThreadMetadataMcpService extends Context.Service<
55 ThreadMetadataMcpService,
56 {
57 readonly update: (
58 input: ThreadMetadataMcpUpdateInput,
59 ) => Effect.Effect<
60 ThreadMetadataMcpUpdateResult,
61 | ThreadMetadataThreadNotFoundError
62 | ThreadMetadataUpdateFailedError
63 | ThreadMetadataPullRequestMismatchError
64 | McpCapabilityUnavailableError,
65 McpInvocationContext.McpInvocationContext
66 >;
67 }
68>()("t3/mcp/ThreadMetadataMcpService") {}
69​
70/** Main stores multiple PR links; preserve unrelated links when adapting v2's single-link actions. */
71function metadataCommand(
72 commandId: CommandId,
73 target: OrchestrationThreadShell,
74 input: ThreadMetadataMcpUpdateInput,
75): OrchestrationCommand {
76 const base = { commandId, threadId: target.id };
77 switch (input.action) {
78 case "rename":
79 return { ...base, type: "thread.meta.update", title: input.title! };
80 case "regenerate_title":
81 return { ...base, type: "thread.meta.update", regenerateTitle: true };
82 case "link_pull_request":
83 return {
84 ...base,
85 type: "thread.pull-request.link",
86 ...legacyThreadPullRequestKey(input.pullRequest!),
87 url: input.pullRequest!.url,
88 source: "agent",
89 };
90 case "unlink_pull_request": {
91 const current = resolveThreadCurrentPullRequestLink(target.pullRequests);
92 return current === null
93 ? // Record a receipt even for an empty unlink so a retry cannot remove a later link.
94 { ...base, type: "thread.meta.update" }
95 : {
96 ...base,
97 type: "thread.pull-request.unlink",
98 host: current.host,
99 repository: current.repository,
100 number: current.number,
101 };
102 }
103 }
105​
106export const make = Effect.gen(function* () {
107 const crypto = yield* Crypto.Crypto;
108 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
109 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
110​
111 const update = Effect.fn("ThreadMetadataMcpService.update")(function* (
112 input: ThreadMetadataMcpUpdateInput,
113 ) {
114 const scope = yield* McpInvocationContext.requireMcpCapability("thread-metadata");
115 const threadId = input.threadId ?? scope.threadId;
116 const getThread = Effect.fn("ThreadMetadataMcpService.getThread")(function* (id: ThreadId) {
117 const thread = yield* snapshots.getThreadShellById(id).pipe(
118 Effect.mapError(
119 (cause) =>
120 new ThreadMetadataUpdateFailedError({
121 threadId: id,
122 action: input.action,
123 cause,
124 }),
125 ),
126 );
127 if (Option.isNone(thread)) {
128 return yield* new ThreadMetadataThreadNotFoundError({ threadId: id });
129 }
130 return thread.value;
131 });
132 const parent = yield* getThread(scope.threadId);
133 const target = threadId === scope.threadId ? parent : yield* getThread(threadId);
134 if (target.projectId !== parent.projectId) {
135 return yield* new ThreadMetadataThreadNotFoundError({ threadId });
136 }
137 if (input.action === "link_pull_request" && input.pullRequest !== undefined) {
138 const parsed = parseChangeRequestUrl(input.pullRequest.url);
139 if (
140 parsed !== null &&
141 (parsed.repository !== input.pullRequest.repository.toLowerCase() ||
142 parsed.number !== input.pullRequest.number)
143 ) {
144 return yield* new ThreadMetadataPullRequestMismatchError({ threadId });
145 }
146 }
147 const requestKey = input.clientRequestId ?? (yield* crypto.randomUUIDv4.pipe(Effect.orDie));
148 const commandId = CommandId.make(
149 [
150 "command",
151 "mcp",
152 scope.providerSessionId,
153 "thread-update",
154 threadId,
155 input.action,
156 requestKey,
157 ]
158 .map(encodeURIComponent)
159 .join(":"),
160 );
161 const { sequence } = yield* engine.dispatch(metadataCommand(commandId, target, input)).pipe(
162 Effect.mapError(
163 (cause) =>
164 new ThreadMetadataUpdateFailedError({
165 threadId,
166 action: input.action,
167 cause,
168 }),
169 ),
170 );
171​
172 // Main receipts return a sequence, not v2's complete thread event. Return the
173 // current saved metadata even on retries, while preserving the original receipt.
174 const saved = yield* getThread(threadId);
175 const linked = resolveThreadCurrentPullRequestLink(saved.pullRequests);
176 return {
177 threadId,
178 action: input.action,
179 commandId,
180 sequence,
181 title: saved.title,
182 titleRegeneration: saved.titleRegeneration ?? null,
183 linkedPullRequest:
184 linked === null
185 ? null
186 : {
187 projectId: saved.projectId,
188 repository: linked.repository,
189 number: linked.number,
190 url: linked.url,
191 },
192 updatedAt: saved.updatedAt,
193 } satisfies ThreadMetadataMcpUpdateResult;
194 });
195​
196 return ThreadMetadataMcpService.of({ update });
197});
198​
199export const layer = Layer.effect(ThreadMetadataMcpService, make);