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

ThreadMetadataMcpService.ts

234 lines7.2 KB

1import {
2 CommandId,
3 OrchestratorMcpFailure,
4 type OrchestrationV2AppThread,
5 type OrchestrationV2Command,
6 type ThreadMetadataMcpAction,
7 type ThreadMetadataMcpUpdateInput,
8 type ThreadMetadataMcpUpdateResult,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as Crypto from "effect/Crypto";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16​
17import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
18import type { McpInvocationScope } from "./McpInvocationContext.ts";
19​
20export class ThreadMetadataMcpService extends Context.Service<
21 ThreadMetadataMcpService,
22 {
23 readonly update: (
24 scope: McpInvocationScope,
25 input: ThreadMetadataMcpUpdateInput,
26 ) => Effect.Effect<ThreadMetadataMcpUpdateResult, OrchestratorMcpFailure>;
27 }
28>()("t3/mcp/ThreadMetadataMcpService") {}
29​
30function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
31 return new OrchestratorMcpFailure({ code, message });
33​
34function errorMessage(error: unknown): string {
35 return error instanceof Error ? error.message : String(error);
37​
38function threadLookupFailure(
39 error: ThreadManagementService.ThreadManagementError,
40): OrchestratorMcpFailure {
41 return error._tag === "ThreadManagementThreadNotFoundError"
42 ? failure("thread_not_found", error.message)
43 : failure("orchestration_error", error.message);
45​
46function stablePart(value: string): string {
47 return encodeURIComponent(value);
49​
50function commandId(input: {
51 readonly scope: McpInvocationScope;
52 readonly threadId: ThreadId;
53 readonly action: ThreadMetadataMcpAction;
54 readonly requestKey: string;
55}): CommandId {
56 return CommandId.make(
57 [
58 "command",
59 "mcp",
60 stablePart(input.scope.requestNamespace),
61 "thread-update",
62 stablePart(input.threadId),
63 stablePart(input.action),
64 stablePart(input.requestKey),
65 ].join(":"),
66 );
68​
69function metadataCommand(input: {
70 readonly commandId: CommandId;
71 readonly threadId: ThreadId;
72 readonly projectId: OrchestrationV2AppThread["projectId"];
73 readonly update: ThreadMetadataMcpUpdateInput;
74}): Extract<OrchestrationV2Command, { readonly type: "thread.metadata.update" }> {
75 switch (input.update.action) {
76 case "rename":
77 return {
78 type: "thread.metadata.update",
79 commandId: input.commandId,
80 threadId: input.threadId,
81 title: input.update.title!,
82 };
83 case "regenerate_title":
84 return {
85 type: "thread.metadata.update",
86 commandId: input.commandId,
87 threadId: input.threadId,
88 regenerateTitle: true,
89 };
90 case "link_pull_request":
91 return {
92 type: "thread.metadata.update",
93 commandId: input.commandId,
94 threadId: input.threadId,
95 linkedPullRequest: {
96 projectId: input.projectId,
97 ...input.update.pullRequest!,
98 },
99 };
100 case "unlink_pull_request":
101 return {
102 type: "thread.metadata.update",
103 commandId: input.commandId,
104 threadId: input.threadId,
105 linkedPullRequest: null,
106 };
107 }
109​
110function resultFromThread(input: {
111 readonly action: ThreadMetadataMcpAction;
112 readonly commandId: CommandId;
113 readonly sequence: number;
114 readonly thread: Pick<
115 OrchestrationV2AppThread,
116 "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt"
117 >;
118}): ThreadMetadataMcpUpdateResult {
119 return {
120 threadId: input.thread.id,
121 action: input.action,
122 commandId: input.commandId,
123 sequence: input.sequence,
124 title: input.thread.title,
125 titleRegeneration:
126 input.thread.titleRegeneration === undefined || input.thread.titleRegeneration === null
127 ? null
128 : {
129 requestId: input.thread.titleRegeneration.requestId,
130 startedAt: DateTime.formatIso(input.thread.titleRegeneration.startedAt),
131 },
132 linkedPullRequest: input.thread.linkedPullRequest ?? null,
133 updatedAt: DateTime.formatIso(input.thread.updatedAt),
134 };
136​
137const make = Effect.gen(function* () {
138 const crypto = yield* Crypto.Crypto;
139 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
140​
141 const update = Effect.fn("ThreadMetadataMcpService.update")(function* (
142 scope: McpInvocationScope,
143 input: ThreadMetadataMcpUpdateInput,
144 ) {
145 if (!scope.capabilities.has("orchestration")) {
146 return yield* failure(
147 "capability_denied",
148 "This MCP credential does not grant orchestration capabilities.",
149 );
150 }
151​
152 const threadId = input.threadId ?? scope.thread?.threadId;
153 if (threadId === undefined) {
154 return yield* failure(
155 "target_required",
156 "Pass threadId: this MCP client is not running inside a T3 thread.",
157 );
158 }
159 const shell = yield* threadManagement
160 .getThreadShell(threadId)
161 .pipe(
162 Effect.mapError((error) =>
163 failure(
164 "orchestration_error",
165 `Unable to locate thread ${threadId}: ${errorMessage(error)}`,
166 ),
167 ),
168 );
169 if (shell === null || shell.deletedAt !== null) {
170 return yield* failure("thread_not_found", `Thread ${threadId} was not found.`);
171 }
172 const target = yield* threadManagement
173 .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [])
174 .pipe(Effect.mapError(threadLookupFailure));
175 const requestKey =
176 input.clientRequestId === undefined
177 ? yield* crypto.randomUUIDv4().pipe(Effect.orDie)
178 : input.clientRequestId;
179 const updateCommandId = commandId({
180 scope,
181 threadId,
182 action: input.action,
183 requestKey,
184 });
185 const dispatched = yield* threadManagement
186 .dispatch(
187 metadataCommand({
188 commandId: updateCommandId,
189 threadId,
190 projectId: target.thread.projectId,
191 update: input,
192 }),
193 )
194 .pipe(
195 Effect.mapError((error) =>
196 failure(
197 "orchestration_error",
198 `Unable to ${input.action} for thread ${threadId}: ${errorMessage(error)}`,
199 ),
200 ),
201 );
202 const metadataEvent = dispatched.storedEvents.find(
203 (stored) => stored.event.type === "thread.metadata-updated",
204 );
205 // A retried commandId replays the stored events of the first dispatch;
206 // compaction may have deleted them by then, so answer from the projection.
207 const thread =
208 metadataEvent?.event.type === "thread.metadata-updated"
209 ? metadataEvent.event.payload
210 : yield* threadManagement
211 .getThreadShell(threadId)
212 .pipe(Effect.mapError((error) => failure("orchestration_error", errorMessage(error))));
213 if (thread === null) {
214 return yield* failure(
215 "orchestration_error",
216 `Thread ${threadId} metadata update completed without a resultant state.`,
217 );
218 }
219 return resultFromThread({
220 action: input.action,
221 commandId: updateCommandId,
222 sequence: dispatched.sequence,
223 thread,
224 });
225 });
226​
227 return ThreadMetadataMcpService.of({ update });
228});
229​
230export const layer: Layer.Layer<
231 ThreadMetadataMcpService,
232 never,
233 Crypto.Crypto | ThreadManagementService.ThreadManagementService
234> = Layer.effect(ThreadMetadataMcpService, make);