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/unstable/http";
9
10import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
11import * as McpInvocationContext from "./McpInvocationContext.ts";
12import * as McpProviderSession from "./McpProviderSession.ts";
13
14export interface McpCredentialRequest {
15 readonly threadId: ThreadId;
16 readonly providerInstanceId: ProviderInstanceId;
17 /**
18 * When false, the credential is minted without the "preview" capability so
19 * the user's choice to withhold agent browser access holds everywhere the
20 * token is honored (#7083). Defaults to full access.
21 */
22 readonly browserToolsAvailable?: boolean;
23 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
24}
25
26export interface McpIssuedCredential {
27 readonly config: McpProviderSession.McpProviderSessionConfig;
28}
29
30export interface McpSessionRegistryShape {
31 readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
32 readonly resolve: (
33 rawToken: string,
34 ) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
35 /**
36 * Records a sign of life for every credential bound to `threadId`. Provider
37 * turns call this so that a session which is plainly alive keeps its
38 * credential even when it goes a long time without touching an MCP tool.
39 */
40 readonly touch: (threadId: ThreadId) => Effect.Effect<void>;
41 readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
42 readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
43 readonly revokeAll: Effect.Effect<void>;
44}
45
46export class McpSessionRegistry extends Context.Service<
47 McpSessionRegistry,
48 McpSessionRegistryShape
49>()("t3/mcp/McpSessionRegistry") {}
50
51interface CredentialRecord {
52 readonly tokenHash: string;
53 readonly scope: McpInvocationContext.McpInvocationScope;
54 readonly lastAliveAt: number;
55}
56
57interface RegistryState {
58 readonly records: ReadonlyMap<string, CredentialRecord>;
59}
60
61export interface McpSessionRegistryOptions {
62 readonly livenessWindowMs?: number;
63 readonly now?: () => number;
64}
65
66/**
67 * How long a credential outlives the last sign of life from its provider
68 * session.
69 *
70 * Liveness is refreshed both by MCP traffic and by `touch` on every provider
71 * turn, so a session that is still doing work never expires no matter how long
72 * it goes between browser tool calls. This window therefore only bounds
73 * credentials whose session died without a clean stop — the normal paths
74 * (`stopSession`, `stopAll`) revoke eagerly and do not wait for it.
75 *
76 * The bound matters because `/mcp` is mounted outside the environment auth
77 * stack and is reachable on whatever host the server binds to, so this token is
78 * the only thing guarding the `t3-code` toolkits on a remote-reachable server.
79 */
80const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
81
82const bytesToHex = (bytes: Uint8Array): string =>
83 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
84
85const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
86
87const getHttpMcpEndpointHost = (hostname: string): string => {
88 const normalized = hostname.toLowerCase();
89 const endpointHostname =
90 normalized === "0.0.0.0" || normalized === "::" || normalized === "[::]"
91 ? "127.0.0.1"
92 : hostname;
93 return endpointHostname.includes(":") && !endpointHostname.startsWith("[")
94 ? `[${endpointHostname}]`
95 : endpointHostname;
96};
97
98const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
99 options: McpSessionRegistryOptions = {},
100) {
101 const crypto = yield* Crypto.Crypto;
102 const environment = yield* ServerEnvironment.ServerEnvironment;
103 const environmentId = yield* environment.getEnvironmentId;
104 const httpServer = yield* HttpServer.HttpServer;
105 const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
106 const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
107 const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
108 const endpoint =
109 httpServer.address._tag === "TcpAddress"
110 ? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
111 : "http://127.0.0.1/mcp";
112
113 const hashToken = (token: string) =>
114 crypto
115 .digest("SHA-256", new TextEncoder().encode(token))
116 .pipe(Effect.map(bytesToHex), Effect.orDie);
117
118 const pruneDead = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
119 const next = new Map(
120 Array.from(records).filter(
121 ([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs,
122 ),
123 );
124 return next.size === records.size ? records : next;
125 };
126
127 const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
128 function* (request) {
129 const issuedAt = yield* currentTimeMillis;
130 const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
131 const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
132 const tokenHash = yield* hashToken(rawToken);
133 const browserToolsAvailable = request.browserToolsAvailable ?? true;
134 const scope: McpInvocationContext.McpInvocationScope = {
135 environmentId,
136 threadId: ThreadId.make(request.threadId),
137 providerSessionId,
138 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
139 capabilities: new Set<McpInvocationContext.McpCapability>([
140 "orchestration",
141 "worktree",
142 "pull-requests",
143 ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])),
144 ]),
145 issuedAt,
146 };
147 yield* SynchronizedRef.update(state, ({ records }) => {
148 const next = new Map(pruneDead(records, issuedAt));
149 next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
150 return { records: next };
151 });
152 return {
153 config: {
154 environmentId,
155 threadId: scope.threadId,
156 providerSessionId,
157 providerInstanceId: scope.providerInstanceId,
158 endpoint,
159 authorizationHeader: `Bearer ${rawToken}`,
160 browserToolsAvailable: scope.capabilities.has("preview"),
161 capabilities: scope.capabilities,
162 },
163 };
164 },
165 );
166
167 const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")(
168 function* (rawToken) {
169 if (rawToken.length === 0) return undefined;
170 const tokenHash = yield* hashToken(rawToken);
171 const timestamp = yield* currentTimeMillis;
172 return yield* SynchronizedRef.modify(state, ({ records }) => {
173 const current = pruneDead(records, timestamp);
174 const record = current.get(tokenHash);
175 if (!record) return [undefined, { records: current }] as const;
176 const next = new Map(current);
177 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
178 return [record.scope, { records: next }] as const;
179 });
180 },
181 );
182
183 const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
184 function* (threadId) {
185 const timestamp = yield* currentTimeMillis;
186 yield* SynchronizedRef.update(state, ({ records }) => {
187 const current = pruneDead(records, timestamp);
188 const next = new Map(current);
189 for (const [tokenHash, record] of current) {
190 if (record.scope.threadId === threadId) {
191 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
192 }
193 }
194 return { records: next };
195 });
196 },
197 );
198
199 const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
200 SynchronizedRef.update(state, ({ records }) => ({
201 records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
202 }));
203
204 return McpSessionRegistry.of({
205 issue,
206 resolve,
207 touch,
208 revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
209 function* (providerSessionId) {
210 yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
211 },
212 ),
213 revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
214 yield* revokeWhere((record) => record.scope.threadId === threadId);
215 }),
216 revokeAll: SynchronizedRef.set(state, { records: new Map() }),
217 });
218});
219
220let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
221
222const make = Effect.acquireRelease(
223 makeWithOptions().pipe(
224 Effect.tap((registry) =>
225 Effect.sync(() => {
226 activeMcpSessionRegistry = registry;
227 }),
228 ),
229 ),
230 (registry) =>
231 Effect.sync(() => {
232 if (activeMcpSessionRegistry === registry) {
233 activeMcpSessionRegistry = undefined;
234 }
235 }),
236);
237
238export const layer = Layer.effect(McpSessionRegistry, make);
239
240export const issueActiveMcpCredential = (
241 request: McpCredentialRequest,
242): Effect.Effect<McpIssuedCredential | undefined> =>
243 activeMcpSessionRegistry
244 ? activeMcpSessionRegistry
245 .revokeThread(request.threadId)
246 .pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
247 : Effect.sync((): McpIssuedCredential | undefined => undefined);
248
249/**
250 * Refreshes the liveness of a thread's MCP credential. Called on every provider
251 * turn so an active session is never mistaken for an abandoned one.
252 */
253export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
254 activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
255
256const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
257 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
258
259const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
260 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
261
262/** Exposed for tests. */
263export const __testing = {
264 make: makeWithOptions,
265};