Open History to see the last commit
1import type { ProjectionRecordField } from "../orchestration-v2/ProjectionStore.ts";
2import {
3 CommandId,
4 OrchestratorMcpFailure,
5 type ProjectId,
6 type ProviderInteractionMode,
7 type RuntimeMode,
8 type ThreadId,
9 type OrchestrationV2ThreadShell,
10} from "@t3tools/contracts";
11import * as Crypto from "effect/Crypto";
12import * as Effect from "effect/Effect";
13
14import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
15import * as OrchestrationMcp from "./OrchestratorMcpService.ts";
16import * as McpInvocationContext from "./McpInvocationContext.ts";
17
18export const unavailable = () =>
19 new OrchestratorMcpFailure({
20 code: "orchestration_error",
21 message: "The operation could not be completed.",
22 });
23
24/**
25 * The most a caller may hand to the threads it targets. A thread caller is
26 * capped by its own thread's modes; an OAuth client by the ceiling chosen
27 * when it was approved.
28 */
29export interface CallerLimits {
30 readonly runtimeMode: RuntimeMode;
31 readonly interactionMode: ProviderInteractionMode;
32}
33
34export interface Caller {
35 readonly scope: McpInvocationContext.McpInvocationScope;
36 readonly threads: ThreadManagement.ThreadManagementService["Service"];
37 /** The calling thread, absent for a client signed in from outside T3. */
38 readonly caller: OrchestrationV2ThreadShell | undefined;
39 readonly limits: CallerLimits;
40}
41
42export const readCaller = Effect.fn("mcp.readCaller")(function* () {
43 const scope = yield* McpInvocationContext.McpInvocationContext;
44 if (!scope.capabilities.has("orchestration")) {
45 return yield* new OrchestratorMcpFailure({
46 code: "capability_denied",
47 message: "This credential cannot control threads.",
48 });
49 }
50 const threads = yield* ThreadManagement.ThreadManagementService;
51 if (scope.thread === undefined) {
52 return {
53 scope,
54 threads,
55 caller: undefined,
56 limits: {
57 runtimeMode: scope.client?.runtimeModeCeiling ?? "approval-required",
58 interactionMode: "default",
59 },
60 } satisfies Caller;
61 }
62 const caller = yield* threads
63 .getThreadShell(scope.thread.threadId)
64 .pipe(Effect.mapError(unavailable));
65 if (caller === null || caller.deletedAt !== null) {
66 return yield* new OrchestratorMcpFailure({
67 code: "thread_not_found",
68 message: "The calling thread was not found.",
69 });
70 }
71 return {
72 scope,
73 threads,
74 caller,
75 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
76 } satisfies Caller;
77});
78
79/**
80 * A caller may change another thread only if that thread runs within the
81 * caller's own modes. Its own thread is always within them.
82 */
83export const assertTargetWithinLimits = (
84 limits: CallerLimits,
85 target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
86) =>
87 OrchestrationMcp.resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
88 Effect.andThen(
89 OrchestrationMcp.resolveInteractionMode(limits.interactionMode, target.interactionMode),
90 ),
91 Effect.asVoid,
92 );
93
94function assertLiveCaller({ caller, scope }: Caller) {
95 if (caller === undefined) return Effect.void;
96 return caller.archivedAt !== null ||
97 caller.activeRunId === null ||
98 caller.providerInstanceId !== scope.thread?.providerInstanceId
99 ? Effect.fail(
100 new OrchestratorMcpFailure({
101 code: "parent_not_active",
102 message: "The calling provider no longer owns an active thread run.",
103 }),
104 )
105 : Effect.void;
106}
107
108/**
109 * Mutations from a thread need that thread's live run, so an agent whose turn
110 * ended cannot keep acting. An OAuth client has no run; its session and
111 * ceiling are its authority.
112 */
113export const readMutationCaller = Effect.fn("mcp.readMutationCaller")(function* () {
114 const context = yield* readCaller();
115 yield* assertLiveCaller(context);
116 return context;
117});
118
119/**
120 * Actions that change the environment itself (projects, preferences, launching
121 * outside a project) need full access: a thread caller in full-access/default
122 * mode, or a client approved with a full-access ceiling.
123 */
124export const readFullAccessCaller = Effect.fn("mcp.readFullAccessCaller")(function* (
125 message: string,
126) {
127 const context = yield* readMutationCaller();
128 if (
129 (context.caller !== undefined && context.caller.archivedAt !== null) ||
130 context.limits.runtimeMode !== "full-access" ||
131 context.limits.interactionMode !== "default"
132 ) {
133 return yield* new OrchestratorMcpFailure({ code: "capability_denied", message });
134 }
135 return context;
136});
137
138/** A target project: the one passed, else the calling thread's. */
139export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
140 projectId !== undefined
141 ? Effect.succeed(projectId)
142 : context.caller !== undefined
143 ? Effect.succeed(context.caller.projectId)
144 : Effect.fail(
145 new OrchestratorMcpFailure({
146 code: "target_required",
147 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
148 }),
149 );
150
151/** A target thread: the one passed, else the calling thread. */
152const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
153 threadId !== undefined
154 ? Effect.succeed(threadId)
155 : context.caller !== undefined
156 ? Effect.succeed(context.caller.id)
157 : Effect.fail(
158 new OrchestratorMcpFailure({
159 code: "target_required",
160 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
161 }),
162 );
163
164/** Load a target thread anywhere in the environment; an omitted id means the calling thread. */
165export const readThread = Effect.fn("mcp.readThread")(function* <
166 K extends ProjectionRecordField = never,
167>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
168 const context = yield* readCaller();
169 const targetId = yield* resolveThreadId(context, threadId);
170 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
171 if (shell === null || shell.deletedAt !== null) {
172 return yield* new OrchestratorMcpFailure({
173 code: "thread_not_found",
174 message: "The thread was not found.",
175 });
176 }
177 const projection = yield* context.threads
178 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
179 turnItemTypes: ["user_input_request"],
180 })
181 .pipe(
182 Effect.mapError((error) =>
183 error._tag === "ThreadManagementThreadNotFoundError"
184 ? new OrchestratorMcpFailure({
185 code: "thread_not_found",
186 message: "The thread was not found.",
187 })
188 : unavailable(),
189 ),
190 );
191 return { ...context, projection };
192});
193
194export const readWritableThread = Effect.fn("mcp.readWritableThread")(function* <
195 K extends ProjectionRecordField = never,
196>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
197 const context = yield* readThread(threadId, fields);
198 yield* assertLiveCaller(context);
199 yield* assertTargetWithinLimits(context.limits, context.projection.thread);
200 return context;
201});
202
203export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
204 const crypto = yield* Crypto.Crypto;
205 return CommandId.make(`mcp:${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}`);
206});