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 {
18 ThreadManagementError,
19 ThreadManagementService,
20} from "../orchestration-v2/ThreadManagementService.ts";
21import type { McpInvocationScope } from "./McpInvocationContext.ts";
22
23export class ThreadMetadataMcpService extends Context.Service<
24 ThreadMetadataMcpService,
25 {
26 readonly update: (
27 scope: McpInvocationScope,
28 input: ThreadMetadataMcpUpdateInput,
29 ) => Effect.Effect<ThreadMetadataMcpUpdateResult, OrchestratorMcpFailure>;
30 }
31>()("t3/mcp/ThreadMetadataMcpService") {}
32
33function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
34 return new OrchestratorMcpFailure({ code, message });
35}
36
37function errorMessage(error: unknown): string {
38 return error instanceof Error ? error.message : String(error);
39}
40
41function threadLookupFailure(error: ThreadManagementError): 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.providerSessionId),
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: OrchestrationV2AppThread;
116}): ThreadMetadataMcpUpdateResult {
117 return {
118 threadId: input.thread.id,
119 action: input.action,
120 commandId: input.commandId,
121 sequence: input.sequence,
122 title: input.thread.title,
123 titleRegeneration:
124 input.thread.titleRegeneration === undefined || input.thread.titleRegeneration === null
125 ? null
126 : {
127 requestId: input.thread.titleRegeneration.requestId,
128 startedAt: DateTime.formatIso(input.thread.titleRegeneration.startedAt),
129 },
130 linkedPullRequest: input.thread.linkedPullRequest ?? null,
131 updatedAt: DateTime.formatIso(input.thread.updatedAt),
132 };
133}
134
135const make = Effect.gen(function* () {
136 const crypto = yield* Crypto.Crypto;
137 const threadManagement = yield* ThreadManagementService;
138
139 const update = Effect.fn("ThreadMetadataMcpService.update")(function* (
140 scope: McpInvocationScope,
141 input: ThreadMetadataMcpUpdateInput,
142 ) {
143 if (!scope.capabilities.has("orchestration")) {
144 return yield* failure(
145 "capability_denied",
146 "This MCP credential does not grant orchestration capabilities.",
147 );
148 }
149
150 const parentShell = yield* threadManagement
151 .getThreadShell(scope.threadId)
152 .pipe(
153 Effect.mapError((error) =>
154 failure(
155 "orchestration_error",
156 `Unable to locate calling thread ${scope.threadId}: ${errorMessage(error)}`,
157 ),
158 ),
159 );
160 if (parentShell === null) {
161 return yield* failure("thread_not_found", `Calling thread ${scope.threadId} was not found.`);
162 }
163 const parent = yield* threadManagement
164 .getThreadProjection(scope.threadId)
165 .pipe(
166 Effect.mapError((error) =>
167 failure(
168 "orchestration_error",
169 `Unable to read calling thread ${scope.threadId}: ${errorMessage(error)}`,
170 ),
171 ),
172 );
173 const threadId = input.threadId ?? scope.threadId;
174 const target =
175 threadId === scope.threadId
176 ? parent
177 : yield* threadManagement
178 .getProjectThread({ projectId: parent.thread.projectId, threadId })
179 .pipe(Effect.mapError(threadLookupFailure));
180 const requestKey =
181 input.clientRequestId === undefined
182 ? yield* crypto.randomUUIDv4.pipe(Effect.orDie)
183 : input.clientRequestId;
184 const updateCommandId = commandId({
185 scope,
186 threadId,
187 action: input.action,
188 requestKey,
189 });
190 const dispatched = yield* threadManagement
191 .dispatch(
192 metadataCommand({
193 commandId: updateCommandId,
194 threadId,
195 projectId: target.thread.projectId,
196 update: input,
197 }),
198 )
199 .pipe(
200 Effect.mapError((error) =>
201 failure(
202 "orchestration_error",
203 `Unable to ${input.action} for thread ${threadId}: ${errorMessage(error)}`,
204 ),
205 ),
206 );
207 const metadataEvent = dispatched.storedEvents.find(
208 (stored) => stored.event.type === "thread.metadata-updated",
209 );
210 if (metadataEvent === undefined || metadataEvent.event.type !== "thread.metadata-updated") {
211 return yield* failure(
212 "orchestration_error",
213 `Thread ${threadId} metadata update completed without a resultant state.`,
214 );
215 }
216 return resultFromThread({
217 action: input.action,
218 commandId: updateCommandId,
219 sequence: dispatched.sequence,
220 thread: metadataEvent.event.payload,
221 });
222 });
223
224 return ThreadMetadataMcpService.of({ update });
225});
226
227export const layer: Layer.Layer<
228 ThreadMetadataMcpService,
229 never,
230 Crypto.Crypto | ThreadManagementService
231> = Layer.effect(ThreadMetadataMcpService, make);