Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpSessionRegistry.ts

250 lines9.4 KB

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