Open History to see the last commit
1import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as SynchronizedRef from "effect/SynchronizedRef";
8import { HttpServer } from "effect/http";
9import * as NetAddress from "effect/net/NetAddress";
10
11import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
12import * as McpInvocationContext from "./McpInvocationContext.ts";
13import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
14
15export interface McpCredentialRequest {
16 readonly threadId: ThreadId;
17 readonly providerInstanceId: ProviderInstanceId;
18 /**
19 * When false, the credential is minted without the "preview" capability so
20 * the user's choice to withhold agent browser access holds everywhere the
21 * token is honored (#7083). Defaults to full access.
22 */
23 readonly browserToolsAvailable?: boolean;
24 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
25}
26
27export interface McpIssuedCredential {
28 readonly config: McpProviderSession.McpProviderSessionConfig;
29}
30
31export interface McpSessionRegistryShape {
32 readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
33 readonly resolve: (
34 rawToken: string,
35 ) => Effect.Effect<McpInvocationContext.McpThreadInvocationScope | undefined>;
36 readonly touch: (threadId: ThreadId) => Effect.Effect<void>;
37 readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
38 readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
39 readonly revokeAll: Effect.Effect<void>;
40}
41
42export class McpSessionRegistry extends Context.Service<
43 McpSessionRegistry,
44 McpSessionRegistryShape
45>()("t3/mcp/McpSessionRegistry") {}
46
47interface CredentialRecord {
48 readonly tokenHash: string;
49 readonly scope: McpInvocationContext.McpThreadInvocationScope;
50 readonly lastAliveAt: number;
51}
52
53interface RegistryState {
54 readonly records: ReadonlyMap<string, CredentialRecord>;
55}
56
57export interface McpSessionRegistryOptions {
58 readonly livenessWindowMs?: number;
59 readonly now?: () => number;
60}
61
62/**
63 * The bound matters because `/mcp` is mounted outside the environment auth
64 * stack and is reachable on whatever host the server binds to, so this token is
65 * the only thing guarding the `t3-code` toolkits on a remote-reachable server.
66 */
67const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
68
69const bytesToHex = (bytes: Uint8Array): string =>
70 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
71
72const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
73
74const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string =>
75 NetAddress.isUnspecified(address)
76 ? "127.0.0.1"
77 : NetAddress.formatUrlHostString(NetAddress.formatIp(address));
78
79const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
80 options: McpSessionRegistryOptions = {},
81) {
82 const crypto = yield* Crypto.Crypto;
83 const environment = yield* ServerEnvironment.ServerEnvironment;
84 const environmentId = yield* environment.getEnvironmentId;
85 const httpServer = yield* HttpServer.HttpServer;
86 const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
87 const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
88 const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
89 const endpoint = NetAddress.isInetAddress(httpServer.address)
90 ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${httpServer.address.port}/mcp`
91 : "http://127.0.0.1/mcp";
92
93 const hashToken = (token: string) =>
94 crypto
95 .digest("SHA-256", new TextEncoder().encode(token))
96 .pipe(Effect.map(bytesToHex), Effect.orDie);
97
98 const pruneDead = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
99 const next = new Map(
100 Array.from(records).filter(
101 ([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs,
102 ),
103 );
104 return next.size === records.size ? records : next;
105 };
106
107 const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
108 function* (request) {
109 const issuedAt = yield* currentTimeMillis;
110 const providerSessionId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
111 const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
112 const tokenHash = yield* hashToken(rawToken);
113 const browserToolsAvailable = request.browserToolsAvailable ?? true;
114 const scope: McpInvocationContext.McpThreadInvocationScope = {
115 environmentId,
116 requestNamespace: providerSessionId,
117 thread: {
118 threadId: ThreadId.make(request.threadId),
119 providerSessionId,
120 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
121 },
122 client: undefined,
123 capabilities: new Set<McpInvocationContext.McpCapability>([
124 "orchestration",
125 "worktree",
126 "pull-requests",
127 ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])),
128 ]),
129 issuedAt,
130 };
131 yield* SynchronizedRef.update(state, ({ records }) => {
132 const next = new Map(pruneDead(records, issuedAt));
133 next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
134 return { records: next };
135 });
136 return {
137 config: {
138 environmentId,
139 threadId: scope.thread.threadId,
140 providerSessionId,
141 providerInstanceId: scope.thread.providerInstanceId,
142 endpoint,
143 authorizationHeader: `Bearer ${rawToken}`,
144 browserToolsAvailable: scope.capabilities.has("preview"),
145 capabilities: scope.capabilities,
146 },
147 };
148 },
149 );
150
151 const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")(
152 function* (rawToken) {
153 if (rawToken.length === 0) return undefined;
154 const tokenHash = yield* hashToken(rawToken);
155 const timestamp = yield* currentTimeMillis;
156 return yield* SynchronizedRef.modify(state, ({ records }) => {
157 const current = pruneDead(records, timestamp);
158 const record = current.get(tokenHash);
159 if (!record) return [undefined, { records: current }] as const;
160 const next = new Map(current);
161 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
162 return [record.scope, { records: next }] as const;
163 });
164 },
165 );
166
167 const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
168 function* (threadId) {
169 const timestamp = yield* currentTimeMillis;
170 yield* SynchronizedRef.update(state, ({ records }) => {
171 const current = pruneDead(records, timestamp);
172 const next = new Map(current);
173 for (const [tokenHash, record] of current) {
174 if (record.scope.thread.threadId === threadId) {
175 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
176 }
177 }
178 return { records: next };
179 });
180 },
181 );
182
183 const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
184 SynchronizedRef.update(state, ({ records }) => ({
185 records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
186 }));
187
188 return McpSessionRegistry.of({
189 issue,
190 resolve,
191 touch,
192 revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
193 function* (providerSessionId) {
194 yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId);
195 },
196 ),
197 revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
198 yield* revokeWhere((record) => record.scope.thread.threadId === threadId);
199 }),
200 revokeAll: SynchronizedRef.set(state, { records: new Map() }),
201 });
202});
203
204let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
205
206const make = Effect.acquireRelease(
207 makeWithOptions().pipe(
208 Effect.tap((registry) =>
209 Effect.sync(() => {
210 activeMcpSessionRegistry = registry;
211 }),
212 ),
213 ),
214 (registry) =>
215 Effect.sync(() => {
216 if (activeMcpSessionRegistry === registry) {
217 activeMcpSessionRegistry = undefined;
218 }
219 }),
220);
221
222export const layer = Layer.effect(McpSessionRegistry, make);
223
224export const issueActiveMcpCredential = (
225 request: McpCredentialRequest,
226): Effect.Effect<McpIssuedCredential | undefined> =>
227 activeMcpSessionRegistry
228 ? activeMcpSessionRegistry
229 .revokeThread(request.threadId)
230 .pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
231 : Effect.undefined;
232
233export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
234 activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
235
236const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
237 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
238
239const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
240 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
241
242export const __testing = {
243 make: makeWithOptions,
244};