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