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

ThreadMetadataMcpService.ts

260 lines8.5 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";
19import { assertTargetWithinLimits } from "./threadAccess.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 });
34​
35function errorMessage(error: unknown): string {
36 return error instanceof Error ? error.message : String(error);
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);
46​
47function stablePart(value: string): string {
48 return encodeURIComponent(value);
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 );
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 }
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 };
134​
135const make = Effect.gen(function* () {
136 const crypto = yield* Crypto.Crypto;
137 const threadManagement = yield* ThreadManagementService.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 threadId = input.threadId ?? scope.thread?.threadId;
151 if (threadId === undefined) {
152 return yield* failure(
153 "target_required",
154 "Pass threadId: this MCP client is not running inside a T3 thread.",
155 );
156 }
157 const shell = yield* threadManagement
158 .getThreadShell(threadId)
159 .pipe(
160 Effect.mapError((error) =>
161 failure(
162 "orchestration_error",
163 `Unable to locate thread ${threadId}: ${errorMessage(error)}`,
164 ),
165 ),
166 );
167 if (shell === null || shell.deletedAt !== null) {
168 return yield* failure("thread_not_found", `Thread ${threadId} was not found.`);
169 }
170 // Another thread may only be changed if it runs within the caller's own modes.
171 if (threadId !== scope.thread?.threadId) {
172 const limits =
173 scope.thread === undefined
174 ? {
175 runtimeMode: scope.client?.runtimeModeCeiling ?? ("approval-required" as const),
176 interactionMode: "default" as const,
177 }
178 : yield* threadManagement.getThreadShell(scope.thread.threadId).pipe(
179 Effect.mapError((error) =>
180 failure(
181 "orchestration_error",
182 `Unable to locate calling thread: ${errorMessage(error)}`,
183 ),
184 ),
185 Effect.flatMap((caller) =>
186 caller === null
187 ? Effect.fail(failure("thread_not_found", "The calling thread was not found."))
188 : // Like every other cross-thread write, a thread caller needs its live run.
189 caller.archivedAt !== null ||
190 caller.activeRunId === null ||
191 caller.providerInstanceId !== scope.thread?.providerInstanceId
192 ? Effect.fail(
193 failure(
194 "parent_not_active",
195 "The calling provider no longer owns an active thread run.",
196 ),
197 )
198 : Effect.succeed({
199 runtimeMode: caller.runtimeMode,
200 interactionMode: caller.interactionMode,
201 }),
202 ),
203 );
204 yield* assertTargetWithinLimits(limits, shell);
205 }
206 const target = yield* threadManagement
207 .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [])
208 .pipe(Effect.mapError(threadLookupFailure));
209 const requestKey =
210 input.clientRequestId === undefined
211 ? yield* crypto.randomUUIDv4.pipe(Effect.orDie)
212 : input.clientRequestId;
213 const updateCommandId = commandId({
214 scope,
215 threadId,
216 action: input.action,
217 requestKey,
218 });
219 const dispatched = yield* threadManagement
220 .dispatch(
221 metadataCommand({
222 commandId: updateCommandId,
223 threadId,
224 projectId: target.thread.projectId,
225 update: input,
226 }),
227 )
228 .pipe(
229 Effect.mapError((error) =>
230 failure(
231 "orchestration_error",
232 `Unable to ${input.action} for thread ${threadId}: ${errorMessage(error)}`,
233 ),
234 ),
235 );
236 const metadataEvent = dispatched.storedEvents.find(
237 (stored) => stored.event.type === "thread.metadata-updated",
238 );
239 if (metadataEvent === undefined || metadataEvent.event.type !== "thread.metadata-updated") {
240 return yield* failure(
241 "orchestration_error",
242 `Thread ${threadId} metadata update completed without a resultant state.`,
243 );
244 }
245 return resultFromThread({
246 action: input.action,
247 commandId: updateCommandId,
248 sequence: dispatched.sequence,
249 thread: metadataEvent.event.payload,
250 });
251 });
252​
253 return ThreadMetadataMcpService.of({ update });
254});
255​
256export const layer: Layer.Layer<
257 ThreadMetadataMcpService,
258 never,
259 Crypto.Crypto | ThreadManagementService.ThreadManagementService
260> = Layer.effect(ThreadMetadataMcpService, make);