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