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/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
106export function assertLiveCaller({ caller, scope }: Caller) {
107 if (caller === undefined) return Effect.void;
108 return OrchestrationMcp.isLiveCallerShell(caller, scope.thread?.providerInstanceId)
109 ? Effect.void
110 : Effect.fail(
111 new OrchestratorMcpFailure({
112 code: "parent_not_active",
113 message: "The calling provider no longer owns an active thread run.",
114 }),
115 );
116}
117
118export const assertFullAccess = (context: Caller, message: string) =>
119 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
120 ? Effect.void
121 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
122
123export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
124 projectId !== undefined
125 ? Effect.succeed(projectId)
126 : context.caller !== undefined
127 ? Effect.succeed(context.caller.projectId)
128 : Effect.fail(
129 new OrchestratorMcpFailure({
130 code: "target_required",
131 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
132 }),
133 );
134
135const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
136 threadId !== undefined
137 ? Effect.succeed(threadId)
138 : context.caller !== undefined
139 ? Effect.succeed(context.caller.id)
140 : Effect.fail(
141 new OrchestratorMcpFailure({
142 code: "target_required",
143 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
144 }),
145 );
146
147export const readThread = Effect.fn("mcp.readThread")(function* <
148 K extends ProjectionRecordField = never,
149>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
150 const context = yield* readCaller();
151 const targetId = yield* resolveThreadId(context, threadId);
152 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
153 if (shell === null || shell.deletedAt !== null) {
154 return yield* OrchestrationMcp.threadNotFound(
155 context.threads,
156 targetId,
157 "The thread was not found.",
158 );
159 }
160 const projection = yield* context.threads
161 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
162 turnItemTypes: ["user_input_request"],
163 })
164 .pipe(
165 Effect.mapError((error) =>
166 error._tag === "ThreadManagementThreadNotFoundError"
167 ? new OrchestratorMcpFailure({
168 code: "thread_not_found",
169 message: "The thread was not found.",
170 })
171 : unavailable(),
172 ),
173 );
174 return { ...context, projection };
175});
176
177export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
178 const crypto = yield* Crypto.Crypto;
179 return CommandId.make(`mcp:${yield* crypto.randomUUIDv4().pipe(Effect.orDie)}`);
180});