Open History to see the last commit
1import type {
2 ProjectionRecordField,
3 ProjectionRecordFilter,
4} from "../orchestration-v2/ProjectionStore.ts";
5import {
6 CommandId,
7 type EnvironmentId,
8 isRuntimeModeAbove,
9 OrchestratorMcpFailure,
10 type ProjectId,
11 type ProviderInstanceId,
12 type ProviderInteractionMode,
13 type RuntimeMode,
14 ThreadId,
15 type OrchestrationV2ThreadShell,
16} from "@t3tools/contracts";
17import {
18 hasThreadLinks,
19 parseThreadLinkHref,
20 threadLinkCandidates,
21 threadLinkRefs,
22} from "@t3tools/shared/threadLinks";
23import { hasPendingBackgroundSubagent } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
24import * as SecureRandom from "effect/crypto/SecureRandom";
25import * as Effect from "effect/Effect";
26
27import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";
28import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
29import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
30import { fencingLinkOrigin } from "./linkOrigin.ts";
31import * as McpInvocationContext from "./McpInvocationContext.ts";
32
33const delegatedTaskPrefix = "thread:delegated-task:";
34
35const launchHash = /^[0-9a-f]{64}$/;
36
37const suggestedThreadId = (threadId: ThreadId) => {
38 if (launchHash.test(threadId)) return ThreadId.make(`mcp:launch:${threadId}`);
39 if (!threadId.startsWith(delegatedTaskPrefix)) return ThreadId.make(`mcp:${threadId}`);
40 const rest = threadId.slice(delegatedTaskPrefix.length);
41 // encodeURIComponent throws on lone surrogates, which a JSON string can carry.
42 if (!rest.isWellFormed()) return null;
43 const encoded = encodeURIComponent(rest);
44 return encoded === rest ? null : ThreadId.make(`${delegatedTaskPrefix}${encoded}`);
45};
46
47// A pasted link (bare, Markdown, or hosted) names its thread; only this environment's can be read here.
48const candidateThreadIds = (threadId: ThreadId, environmentId: EnvironmentId) => {
49 if (!hasThreadLinks(threadId)) {
50 const suggested = suggestedThreadId(threadId);
51 return suggested === null ? [] : [suggested];
52 }
53 const link = parseThreadLinkHref(threadId);
54 const refs =
55 link === null
56 ? threadLinkRefs(threadId, environmentId)
57 : threadLinkCandidates(link, environmentId);
58 return refs.filter((ref) => ref.environmentId === environmentId).map((ref) => ref.threadId);
59};
60
61/**
62 * Agents paste bare uuids for `mcp:<uuid>` threads, bare hashes for `mcp:launch:<hash>` threads, unencoded delegated-task ids, and thread links.
63 * The id is never rewritten, so permission checks keyed on it still hold; the miss
64 * only names a live thread the caller could read by its full id. Ids from another
65 * machine miss here too. The link hint is static: listing links probes peers.
66 */
67export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (
68 threads: Pick<ThreadManagement.ThreadManagementService["Service"], "getThreadShell">,
69 scope: McpInvocationContext.McpInvocationScope,
70 threadId: ThreadId,
71 message: string,
72) {
73 let suggested: ThreadId | null = null;
74 for (const candidate of candidateThreadIds(threadId, scope.environmentId)) {
75 const shell = yield* threads.getThreadShell(candidate).pipe(Effect.orElseSucceed(() => null));
76 if (shell !== null && shell.deletedAt === null) {
77 suggested = candidate;
78 break;
79 }
80 }
81 if (suggested !== null && hasThreadLinks(threadId)) {
82 return yield* new OrchestratorMcpFailure({
83 code: "thread_not_found",
84 message: `\`${threadId}\` is a thread link, not a thread id. Pass \`${suggested}\` instead.`,
85 });
86 }
87 const mcpHint = suggested === null ? "" : ` Did you mean \`${suggested}\`?`;
88 const caller =
89 scope.thread === undefined
90 ? null
91 : yield* threads.getThreadShell(scope.thread.threadId).pipe(Effect.orElseSucceed(() => null));
92 // A peer link's caller would be pointed at this machine's links, and a fenced one may not use them.
93 const linksHint =
94 scope.linkedEnvironments === false ||
95 scope.client?.linked === true ||
96 fencingLinkOrigin({ scope, caller: caller ?? undefined }) !== undefined
97 ? ""
98 : " 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.";
99 return yield* new OrchestratorMcpFailure({
100 code: "thread_not_found",
101 message: `${message}${mcpHint}${linksHint}`,
102 });
103});
104
105export const unavailable = () =>
106 new OrchestratorMcpFailure({
107 code: "orchestration_error",
108 message: "The operation could not be completed.",
109 });
110
111export const dispatchFailure = (
112 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
113) =>
114 error._tag === "ThreadManagementProviderInstanceDisabledError" ||
115 error._tag === "OrchestratorRuntimeModeAboveCeilingError" ||
116 error._tag === "OrchestratorProviderSelectionBusyError"
117 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
118 : (error._tag === "OrchestratorDispatchError" ||
119 error._tag === "OrchestratorCommandRejectedError") &&
120 typeof error.cause === "string" &&
121 error.cause.length > 0
122 ? new OrchestratorMcpFailure({
123 code: "orchestration_error",
124 message: Array.from(error.cause).slice(0, 1000).join(""),
125 })
126 : unavailable();
127
128export interface CallerLimits {
129 readonly runtimeMode: RuntimeMode;
130 readonly interactionMode: ProviderInteractionMode;
131}
132
133export interface Caller {
134 readonly scope: McpInvocationContext.McpInvocationScope;
135 readonly threads: ThreadManagement.ThreadManagementService["Service"];
136 readonly caller: OrchestrationV2ThreadShell | undefined;
137 readonly limits: CallerLimits;
138}
139
140export const readCaller = Effect.fn("mcp.readCaller")(function* () {
141 const scope = yield* McpInvocationContext.McpInvocationContext;
142 if (!scope.capabilities.has("orchestration")) {
143 return yield* new OrchestratorMcpFailure({
144 code: "capability_denied",
145 message: "This credential cannot control threads.",
146 });
147 }
148 return yield* loadCaller();
149});
150
151export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
152 const scope = yield* McpInvocationContext.McpInvocationContext;
153 const threads = yield* ThreadManagement.ThreadManagementService;
154 if (scope.thread === undefined) {
155 return {
156 scope,
157 threads,
158 caller: undefined,
159 limits: McpInvocationContext.clientModeCeiling(scope.client),
160 } satisfies Caller;
161 }
162 const caller = yield* threads
163 .getThreadShell(scope.thread.threadId)
164 .pipe(Effect.mapError(unavailable));
165 if (caller === null || caller.deletedAt !== null) {
166 return yield* new OrchestratorMcpFailure({
167 code: "thread_not_found",
168 message: "The calling thread was not found.",
169 });
170 }
171 return {
172 scope,
173 threads,
174 caller,
175 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
176 } satisfies Caller;
177});
178
179export const assertTargetWithinLimits = (
180 limits: CallerLimits,
181 target: Pick<OrchestrationV2ThreadShell, "id" | "runtimeMode" | "interactionMode">,
182) =>
183 resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
184 Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)),
185 Effect.asVoid,
186 Effect.mapError(
187 (error) =>
188 new OrchestratorMcpFailure({
189 code: error.code,
190 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.`,
191 }),
192 ),
193 );
194
195/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */
196export const isLiveCallerShell = (
197 shell: Pick<
198 OrchestrationV2ThreadShell,
199 "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"
200 > | null,
201 providerInstanceId: ProviderInstanceId | undefined,
202) =>
203 shell !== null &&
204 shell.archivedAt === null &&
205 shell.providerInstanceId === providerInstanceId &&
206 (shell.activeRunId !== null ||
207 hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, providerInstanceId));
208
209/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
210export function assertLiveCaller({ caller, scope }: Caller) {
211 if (caller === undefined) return Effect.void;
212 return isLiveCallerShell(caller, scope.thread?.providerInstanceId)
213 ? Effect.void
214 : Effect.fail(
215 new OrchestratorMcpFailure({
216 code: "parent_not_active",
217 message: "The calling provider no longer owns an active thread run.",
218 }),
219 );
220}
221
222export const assertFullAccess = (context: Caller, message: string) =>
223 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
224 ? Effect.void
225 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
226
227/**
228 * For work whose definition picks its own modes: the caller must hold the broadest modes a
229 * thread may run in here, full access or an administrator's ceiling below it.
230 */
231export const assertBroadestAccess = (context: Caller, what: string) => {
232 const broadest = context.scope.runtimeModeCeiling ?? "full-access";
233 return !isRuntimeModeAbove(broadest, context.limits.runtimeMode) &&
234 context.limits.interactionMode === "default"
235 ? Effect.void
236 : Effect.fail(
237 new OrchestratorMcpFailure({
238 code: "capability_denied",
239 message: `Only a caller with ${broadest}/default access can ${what}, because that work picks its own modes. This caller is limited to ${context.limits.runtimeMode}/${context.limits.interactionMode}.`,
240 }),
241 );
242};
243
244export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
245 projectId !== undefined
246 ? Effect.succeed(projectId)
247 : context.caller !== undefined
248 ? Effect.succeed(context.caller.projectId)
249 : Effect.fail(
250 new OrchestratorMcpFailure({
251 code: "target_required",
252 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
253 }),
254 );
255
256const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
257 threadId !== undefined
258 ? Effect.succeed(threadId)
259 : context.caller !== undefined
260 ? Effect.succeed(context.caller.id)
261 : Effect.fail(
262 new OrchestratorMcpFailure({
263 code: "target_required",
264 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
265 }),
266 );
267
268export const readThread = Effect.fn("mcp.readThread")(function* <
269 K extends ProjectionRecordField = never,
270>(threadId?: ThreadId, fields: ReadonlyArray<K> = [], filter?: ProjectionRecordFilter) {
271 const context = yield* readCaller();
272 const targetId = yield* resolveThreadId(context, threadId);
273 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
274 if (shell === null || shell.deletedAt !== null) {
275 return yield* threadNotFound(
276 context.threads,
277 context.scope,
278 targetId,
279 "The thread was not found.",
280 );
281 }
282 const projection = yield* context.threads
283 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
284 turnItemTypes: ["user_input_request"],
285 ...filter,
286 })
287 .pipe(
288 Effect.mapError((error) =>
289 error._tag === "ThreadManagementThreadNotFoundError"
290 ? new OrchestratorMcpFailure({
291 code: "thread_not_found",
292 message: "The thread was not found.",
293 })
294 : unavailable(),
295 ),
296 );
297 return { ...context, projection };
298});
299
300export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
301 const random = yield* SecureRandom.SecureRandom;
302 return CommandId.make(`mcp:${yield* random.uuidV4()}`);
303});