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