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