Open History to see the last commit
1import type {
2 ProjectionRecordField,
3 ProjectionRecordFilter,
4} from "../orchestration-v2/ProjectionStore.ts";
5import {
6 CommandId,
7 OrchestratorMcpFailure,
8 type ProjectId,
9 type ProviderInstanceId,
10 type ProviderInteractionMode,
11 type RuntimeMode,
12 ThreadId,
13 type OrchestrationV2ThreadShell,
14} from "@t3tools/contracts";
15import * as SecureRandom from "effect/crypto/SecureRandom";
16import * as Effect from "effect/Effect";
17
18import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";
19import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
20import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
21import * as McpInvocationContext from "./McpInvocationContext.ts";
22
23/**
24 * Threads an agent starts over MCP are `mcp:<uuid>`, and agents often paste the
25 * bare uuid. The id is never rewritten, so permission checks keyed on it still
26 * hold; the miss only names a live thread the caller could read by its full id.
27 */
28export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (
29 threads: Pick<ThreadManagement.ThreadManagementService["Service"], "getThreadShell">,
30 threadId: ThreadId,
31 message: string,
32) {
33 const prefixed = ThreadId.make(`mcp:${threadId}`);
34 const shell = yield* threads.getThreadShell(prefixed).pipe(Effect.orElseSucceed(() => null));
35 return yield* new OrchestratorMcpFailure({
36 code: "thread_not_found",
37 message:
38 shell === null || shell.deletedAt !== null
39 ? message
40 : `${message} Did you mean \`${prefixed}\`?`,
41 });
42});
43
44export const unavailable = () =>
45 new OrchestratorMcpFailure({
46 code: "orchestration_error",
47 message: "The operation could not be completed.",
48 });
49
50export const dispatchFailure = (
51 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
52) =>
53 error._tag === "ThreadManagementProviderInstanceDisabledError" ||
54 error._tag === "OrchestratorRuntimeModeAboveCeilingError" ||
55 error._tag === "OrchestratorProviderSelectionBusyError"
56 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
57 : (error._tag === "OrchestratorDispatchError" ||
58 error._tag === "OrchestratorCommandRejectedError") &&
59 typeof error.cause === "string" &&
60 error.cause.length > 0
61 ? new OrchestratorMcpFailure({
62 code: "orchestration_error",
63 message: Array.from(error.cause).slice(0, 1000).join(""),
64 })
65 : unavailable();
66
67export interface CallerLimits {
68 readonly runtimeMode: RuntimeMode;
69 readonly interactionMode: ProviderInteractionMode;
70}
71
72export interface Caller {
73 readonly scope: McpInvocationContext.McpInvocationScope;
74 readonly threads: ThreadManagement.ThreadManagementService["Service"];
75 readonly caller: OrchestrationV2ThreadShell | undefined;
76 readonly limits: CallerLimits;
77}
78
79export const readCaller = Effect.fn("mcp.readCaller")(function* () {
80 const scope = yield* McpInvocationContext.McpInvocationContext;
81 if (!scope.capabilities.has("orchestration")) {
82 return yield* new OrchestratorMcpFailure({
83 code: "capability_denied",
84 message: "This credential cannot control threads.",
85 });
86 }
87 return yield* loadCaller();
88});
89
90export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
91 const scope = yield* McpInvocationContext.McpInvocationContext;
92 const threads = yield* ThreadManagement.ThreadManagementService;
93 if (scope.thread === undefined) {
94 return {
95 scope,
96 threads,
97 caller: undefined,
98 limits: McpInvocationContext.clientModeCeiling(scope.client),
99 } satisfies Caller;
100 }
101 const caller = yield* threads
102 .getThreadShell(scope.thread.threadId)
103 .pipe(Effect.mapError(unavailable));
104 if (caller === null || caller.deletedAt !== null) {
105 return yield* new OrchestratorMcpFailure({
106 code: "thread_not_found",
107 message: "The calling thread was not found.",
108 });
109 }
110 return {
111 scope,
112 threads,
113 caller,
114 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
115 } satisfies Caller;
116});
117
118export const assertTargetWithinLimits = (
119 limits: CallerLimits,
120 target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
121) =>
122 resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
123 Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)),
124 Effect.asVoid,
125 );
126
127/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */
128export const isLiveCallerShell = (
129 shell: Pick<
130 OrchestrationV2ThreadShell,
131 "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"
132 > | null,
133 providerInstanceId: ProviderInstanceId | undefined,
134) =>
135 shell !== null &&
136 shell.archivedAt === null &&
137 shell.providerInstanceId === providerInstanceId &&
138 (shell.activeRunId !== null ||
139 (shell.pendingBackgroundTasks?.some(
140 (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,
141 ) ??
142 false));
143
144/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
145export function assertLiveCaller({ caller, scope }: Caller) {
146 if (caller === undefined) return Effect.void;
147 return isLiveCallerShell(caller, scope.thread?.providerInstanceId)
148 ? Effect.void
149 : Effect.fail(
150 new OrchestratorMcpFailure({
151 code: "parent_not_active",
152 message: "The calling provider no longer owns an active thread run.",
153 }),
154 );
155}
156
157export const assertFullAccess = (context: Caller, message: string) =>
158 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
159 ? Effect.void
160 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
161
162export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
163 projectId !== undefined
164 ? Effect.succeed(projectId)
165 : context.caller !== undefined
166 ? Effect.succeed(context.caller.projectId)
167 : Effect.fail(
168 new OrchestratorMcpFailure({
169 code: "target_required",
170 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
171 }),
172 );
173
174const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
175 threadId !== undefined
176 ? Effect.succeed(threadId)
177 : context.caller !== undefined
178 ? Effect.succeed(context.caller.id)
179 : Effect.fail(
180 new OrchestratorMcpFailure({
181 code: "target_required",
182 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
183 }),
184 );
185
186export const readThread = Effect.fn("mcp.readThread")(function* <
187 K extends ProjectionRecordField = never,
188>(threadId?: ThreadId, fields: ReadonlyArray<K> = [], filter?: ProjectionRecordFilter) {
189 const context = yield* readCaller();
190 const targetId = yield* resolveThreadId(context, threadId);
191 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
192 if (shell === null || shell.deletedAt !== null) {
193 return yield* threadNotFound(context.threads, targetId, "The thread was not found.");
194 }
195 const projection = yield* context.threads
196 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
197 turnItemTypes: ["user_input_request"],
198 ...filter,
199 })
200 .pipe(
201 Effect.mapError((error) =>
202 error._tag === "ThreadManagementThreadNotFoundError"
203 ? new OrchestratorMcpFailure({
204 code: "thread_not_found",
205 message: "The thread was not found.",
206 })
207 : unavailable(),
208 ),
209 );
210 return { ...context, projection };
211});
212
213export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
214 const random = yield* SecureRandom.SecureRandom;
215 return CommandId.make(`mcp:${yield* random.uuidV4()}`);
216});