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

ThreadMetadataMcpService.ts

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