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 of a thread that is not
107 * archived, so a provider token that outlived its session cannot act. An
108 * OAuth client has no run; its session and ceiling are its authority.
109 */
110export function assertLiveCaller({ caller, scope }: Caller) {
111 if (caller === undefined) return Effect.void;
112 return caller.archivedAt !== null ||
113 caller.activeRunId === null ||
114 caller.providerInstanceId !== scope.thread?.providerInstanceId
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 : Effect.void;
122}
123
124export const assertFullAccess = (context: Caller, message: string) =>
125 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
126 ? Effect.void
127 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
128
129export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
130 projectId !== undefined
131 ? Effect.succeed(projectId)
132 : context.caller !== undefined
133 ? Effect.succeed(context.caller.projectId)
134 : Effect.fail(
135 new OrchestratorMcpFailure({
136 code: "target_required",
137 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
138 }),
139 );
140
141const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
142 threadId !== undefined
143 ? Effect.succeed(threadId)
144 : context.caller !== undefined
145 ? Effect.succeed(context.caller.id)
146 : Effect.fail(
147 new OrchestratorMcpFailure({
148 code: "target_required",
149 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
150 }),
151 );
152
153export const readThread = Effect.fn("mcp.readThread")(function* <
154 K extends ProjectionRecordField = never,
155>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
156 const context = yield* readCaller();
157 const targetId = yield* resolveThreadId(context, threadId);
158 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
159 if (shell === null || shell.deletedAt !== null) {
160 return yield* new OrchestratorMcpFailure({
161 code: "thread_not_found",
162 message: "The thread was not found.",
163 });
164 }
165 const projection = yield* context.threads
166 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
167 turnItemTypes: ["user_input_request"],
168 })
169 .pipe(
170 Effect.mapError((error) =>
171 error._tag === "ThreadManagementThreadNotFoundError"
172 ? new OrchestratorMcpFailure({
173 code: "thread_not_found",
174 message: "The thread was not found.",
175 })
176 : unavailable(),
177 ),
178 );
179 return { ...context, projection };
180});
181
182export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
183 const crypto = yield* Crypto.Crypto;
184 return CommandId.make(`mcp:${yield* crypto.randomUUIDv4().pipe(Effect.orDie)}`);
185});