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
25export const dispatchFailure = (
26 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
27) =>
28 error._tag === "ThreadManagementProviderInstanceDisabledError"
29 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
30 : (error._tag === "OrchestratorDispatchError" ||
31 error._tag === "OrchestratorCommandRejectedError") &&
32 typeof error.cause === "string" &&
33 error.cause.length > 0
34 ? new OrchestratorMcpFailure({
35 code: "orchestration_error",
36 message: Array.from(error.cause).slice(0, 1000).join(""),
37 })
38 : unavailable();
39
40export interface CallerLimits {
41 readonly runtimeMode: RuntimeMode;
42 readonly interactionMode: ProviderInteractionMode;
43}
44
45export interface Caller {
46 readonly scope: McpInvocationContext.McpInvocationScope;
47 readonly threads: ThreadManagement.ThreadManagementService["Service"];
48 readonly caller: OrchestrationV2ThreadShell | undefined;
49 readonly limits: CallerLimits;
50}
51
52export const readCaller = Effect.fn("mcp.readCaller")(function* () {
53 const scope = yield* McpInvocationContext.McpInvocationContext;
54 if (!scope.capabilities.has("orchestration")) {
55 return yield* new OrchestratorMcpFailure({
56 code: "capability_denied",
57 message: "This credential cannot control threads.",
58 });
59 }
60 return yield* loadCaller();
61});
62
63export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
64 const scope = yield* McpInvocationContext.McpInvocationContext;
65 const threads = yield* ThreadManagement.ThreadManagementService;
66 if (scope.thread === undefined) {
67 return {
68 scope,
69 threads,
70 caller: undefined,
71 limits: {
72 runtimeMode: McpInvocationContext.clientRuntimeModeCeiling(scope.client),
73 interactionMode: "default",
74 },
75 } satisfies Caller;
76 }
77 const caller = yield* threads
78 .getThreadShell(scope.thread.threadId)
79 .pipe(Effect.mapError(unavailable));
80 if (caller === null || caller.deletedAt !== null) {
81 return yield* new OrchestratorMcpFailure({
82 code: "thread_not_found",
83 message: "The calling thread was not found.",
84 });
85 }
86 return {
87 scope,
88 threads,
89 caller,
90 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
91 } satisfies Caller;
92});
93
94export const assertTargetWithinLimits = (
95 limits: CallerLimits,
96 target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
97) =>
98 OrchestrationMcp.resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
99 Effect.andThen(
100 OrchestrationMcp.resolveInteractionMode(limits.interactionMode, target.interactionMode),
101 ),
102 Effect.asVoid,
103 );
104
105/**
106 * A thread caller acts only while it owns a live run, or a background
107 * subagent that run started, of a thread that is not archived, so a provider
108 * token that outlived its session cannot act. An OAuth client has no run; its
109 * session and ceiling are its authority.
110 */
111export function assertLiveCaller({ caller, scope }: Caller) {
112 if (caller === undefined) return Effect.void;
113 return OrchestrationMcp.isLiveCallerShell(caller, scope.thread?.providerInstanceId)
114 ? Effect.void
115 : Effect.fail(
116 new OrchestratorMcpFailure({
117 code: "parent_not_active",
118 message: "The calling provider no longer owns an active thread run.",
119 }),
120 );
121}
122
123export const assertFullAccess = (context: Caller, message: string) =>
124 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
125 ? Effect.void
126 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
127
128export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
129 projectId !== undefined
130 ? Effect.succeed(projectId)
131 : context.caller !== undefined
132 ? Effect.succeed(context.caller.projectId)
133 : Effect.fail(
134 new OrchestratorMcpFailure({
135 code: "target_required",
136 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
137 }),
138 );
139
140const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
141 threadId !== undefined
142 ? Effect.succeed(threadId)
143 : context.caller !== undefined
144 ? Effect.succeed(context.caller.id)
145 : Effect.fail(
146 new OrchestratorMcpFailure({
147 code: "target_required",
148 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
149 }),
150 );
151
152export const readThread = Effect.fn("mcp.readThread")(function* <
153 K extends ProjectionRecordField = never,
154>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
155 const context = yield* readCaller();
156 const targetId = yield* resolveThreadId(context, threadId);
157 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
158 if (shell === null || shell.deletedAt !== null) {
159 return yield* new OrchestratorMcpFailure({
160 code: "thread_not_found",
161 message: "The thread was not found.",
162 });
163 }
164 const projection = yield* context.threads
165 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
166 turnItemTypes: ["user_input_request"],
167 })
168 .pipe(
169 Effect.mapError((error) =>
170 error._tag === "ThreadManagementThreadNotFoundError"
171 ? new OrchestratorMcpFailure({
172 code: "thread_not_found",
173 message: "The thread was not found.",
174 })
175 : unavailable(),
176 ),
177 );
178 return { ...context, projection };
179});
180
181export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
182 const crypto = yield* Crypto.Crypto;
183 return CommandId.make(`mcp:${yield* crypto.randomUUIDv4().pipe(Effect.orDie)}`);
184});