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 ProviderInteractionMode,
7 type RuntimeMode,
8 type ThreadId,
9 type OrchestrationV2ThreadShell,
10} from "@t3tools/contracts";
11import * as Crypto from "effect/Crypto";
12import * as Effect from "effect/Effect";
13
14import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";
15import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
16import * as OrchestrationMcp from "./OrchestratorMcpService.ts";
17import * as McpInvocationContext from "./McpInvocationContext.ts";
18
19export const unavailable = () =>
20 new OrchestratorMcpFailure({
21 code: "orchestration_error",
22 message: "The operation could not be completed.",
23 });
24
25/** Decider string rejections are public; wrapped storage and hydration causes are not. */
26export const dispatchFailure = (error: OrchestratorV2Error) =>
27 (error._tag === "OrchestratorDispatchError" ||
28 error._tag === "OrchestratorCommandRejectedError") &&
29 typeof error.cause === "string" &&
30 error.cause.length > 0
31 ? new OrchestratorMcpFailure({
32 code: "orchestration_error",
33 message: Array.from(error.cause).slice(0, 1000).join(""),
34 })
35 : unavailable();
36
37/**
38 * The most a caller may hand to the threads it targets. A thread caller is
39 * capped by its own thread's modes; an OAuth client by the ceiling chosen
40 * when it was approved.
41 */
42export interface CallerLimits {
43 readonly runtimeMode: RuntimeMode;
44 readonly interactionMode: ProviderInteractionMode;
45}
46
47export interface Caller {
48 readonly scope: McpInvocationContext.McpInvocationScope;
49 readonly threads: ThreadManagement.ThreadManagementService["Service"];
50 /** The calling thread, absent for a client signed in from outside T3. */
51 readonly caller: OrchestrationV2ThreadShell | undefined;
52 readonly limits: CallerLimits;
53}
54
55export const readCaller = Effect.fn("mcp.readCaller")(function* () {
56 const scope = yield* McpInvocationContext.McpInvocationContext;
57 if (!scope.capabilities.has("orchestration")) {
58 return yield* new OrchestratorMcpFailure({
59 code: "capability_denied",
60 message: "This credential cannot control threads.",
61 });
62 }
63 return yield* loadCaller();
64});
65
66/**
67 * The caller and its limits, whichever tools its credential grants. Tools
68 * check their own capability; `McpToolAccess` uses this for every tool.
69 */
70export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
71 const scope = yield* McpInvocationContext.McpInvocationContext;
72 const threads = yield* ThreadManagement.ThreadManagementService;
73 if (scope.thread === undefined) {
74 return {
75 scope,
76 threads,
77 caller: undefined,
78 limits: {
79 runtimeMode: McpInvocationContext.clientRuntimeModeCeiling(scope.client),
80 interactionMode: "default",
81 },
82 } satisfies Caller;
83 }
84 const caller = yield* threads
85 .getThreadShell(scope.thread.threadId)
86 .pipe(Effect.mapError(unavailable));
87 if (caller === null || caller.deletedAt !== null) {
88 return yield* new OrchestratorMcpFailure({
89 code: "thread_not_found",
90 message: "The calling thread was not found.",
91 });
92 }
93 return {
94 scope,
95 threads,
96 caller,
97 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
98 } satisfies Caller;
99});
100
101/**
102 * A caller may change another thread only if that thread runs within the
103 * caller's own modes. Its own thread is always within them.
104 */
105export const assertTargetWithinLimits = (
106 limits: CallerLimits,
107 target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
108) =>
109 OrchestrationMcp.resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
110 Effect.andThen(
111 OrchestrationMcp.resolveInteractionMode(limits.interactionMode, target.interactionMode),
112 ),
113 Effect.asVoid,
114 );
115
116/**
117 * A thread caller acts only while it owns a live run of a thread that is not
118 * archived, so a provider token that outlived its session cannot act. An
119 * OAuth client has no run; its session and ceiling are its authority.
120 */
121export function assertLiveCaller({ caller, scope }: Caller) {
122 if (caller === undefined) return Effect.void;
123 return caller.archivedAt !== null ||
124 caller.activeRunId === null ||
125 caller.providerInstanceId !== scope.thread?.providerInstanceId
126 ? Effect.fail(
127 new OrchestratorMcpFailure({
128 code: "parent_not_active",
129 message: "The calling provider no longer owns an active thread run.",
130 }),
131 )
132 : Effect.void;
133}
134
135/**
136 * Actions that change the environment itself (projects, preferences) need full
137 * access: a thread caller in full-access/default mode, or a client approved
138 * with a full-access ceiling.
139 */
140export const assertFullAccess = (context: Caller, message: string) =>
141 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
142 ? Effect.void
143 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
144
145/** A target project: the one passed, else the calling thread's. */
146export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
147 projectId !== undefined
148 ? Effect.succeed(projectId)
149 : context.caller !== undefined
150 ? Effect.succeed(context.caller.projectId)
151 : Effect.fail(
152 new OrchestratorMcpFailure({
153 code: "target_required",
154 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
155 }),
156 );
157
158/** A target thread: the one passed, else the calling thread. */
159const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
160 threadId !== undefined
161 ? Effect.succeed(threadId)
162 : context.caller !== undefined
163 ? Effect.succeed(context.caller.id)
164 : Effect.fail(
165 new OrchestratorMcpFailure({
166 code: "target_required",
167 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
168 }),
169 );
170
171/** Load a target thread anywhere in the environment; an omitted id means the calling thread. */
172export const readThread = Effect.fn("mcp.readThread")(function* <
173 K extends ProjectionRecordField = never,
174>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
175 const context = yield* readCaller();
176 const targetId = yield* resolveThreadId(context, threadId);
177 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
178 if (shell === null || shell.deletedAt !== null) {
179 return yield* new OrchestratorMcpFailure({
180 code: "thread_not_found",
181 message: "The thread was not found.",
182 });
183 }
184 const projection = yield* context.threads
185 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
186 turnItemTypes: ["user_input_request"],
187 })
188 .pipe(
189 Effect.mapError((error) =>
190 error._tag === "ThreadManagementThreadNotFoundError"
191 ? new OrchestratorMcpFailure({
192 code: "thread_not_found",
193 message: "The thread was not found.",
194 })
195 : unavailable(),
196 ),
197 );
198 return { ...context, projection };
199});
200
201export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
202 const crypto = yield* Crypto.Crypto;
203 return CommandId.make(`mcp:${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}`);
204});