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