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

McpSessionRegistry.ts

255 lines9.6 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;
17 readonly capabilities: ReadonlySet<McpInvocationContext.McpCapability>;
19​
20export interface McpIssuedCredential {
21 readonly config: McpProviderSession.McpProviderSessionConfig;
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>;
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;
50​
51interface RegistryState {
52 readonly records: ReadonlyMap<string, CredentialRecord>;
54​
55export interface McpSessionRegistryOptions {
56 readonly livenessWindowMs?: number;
57 readonly now?: () => number;
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 ...request.capabilities,
135 ]),
136 issuedAt,
137 };
138 yield* SynchronizedRef.update(state, ({ records }) => {
139 const next = new Map(pruneDead(records, issuedAt));
140 next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
141 return { records: next };
142 });
143 return {
144 config: {
145 environmentId,
146 threadId: scope.threadId,
147 providerSessionId,
148 providerInstanceId: scope.providerInstanceId,
149 endpoint,
150 authorizationHeader: `Bearer ${rawToken}`,
151 capabilities: scope.capabilities,
152 },
153 };
154 },
155 );
156​
157 const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")(
158 function* (rawToken) {
159 if (rawToken.length === 0) return undefined;
160 const tokenHash = yield* hashToken(rawToken);
161 const timestamp = yield* currentTimeMillis;
162 return yield* SynchronizedRef.modify(state, ({ records }) => {
163 const current = pruneDead(records, timestamp);
164 const record = current.get(tokenHash);
165 if (!record) return [undefined, { records: current }] as const;
166 const next = new Map(current);
167 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
168 return [record.scope, { records: next }] as const;
169 });
170 },
171 );
172​
173 const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
174 function* (threadId) {
175 const timestamp = yield* currentTimeMillis;
176 yield* SynchronizedRef.update(state, ({ records }) => {
177 const current = pruneDead(records, timestamp);
178 const next = new Map(current);
179 for (const [tokenHash, record] of current) {
180 if (record.scope.threadId === threadId) {
181 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
182 }
183 }
184 return { records: next };
185 });
186 },
187 );
188​
189 const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
190 SynchronizedRef.update(state, ({ records }) => ({
191 records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
192 }));
193​
194 return McpSessionRegistry.of({
195 issue,
196 resolve,
197 touch,
198 revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
199 function* (providerSessionId) {
200 yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
201 },
202 ),
203 revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
204 yield* revokeWhere((record) => record.scope.threadId === threadId);
205 }),
206 revokeAll: SynchronizedRef.set(state, { records: new Map() }),
207 });
208});
209​
210let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
211​
212const make = Effect.acquireRelease(
213 makeWithOptions().pipe(
214 Effect.tap((registry) =>
215 Effect.sync(() => {
216 activeMcpSessionRegistry = registry;
217 }),
218 ),
219 ),
220 (registry) =>
221 Effect.sync(() => {
222 if (activeMcpSessionRegistry === registry) {
223 activeMcpSessionRegistry = undefined;
224 }
225 }),
226);
227​
228export const layer = Layer.effect(McpSessionRegistry, make);
229​
230export const issueActiveMcpCredential = (
231 request: McpCredentialRequest,
232): Effect.Effect<McpIssuedCredential | undefined> =>
233 activeMcpSessionRegistry
234 ? activeMcpSessionRegistry
235 .revokeThread(request.threadId)
236 .pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
237 : Effect.sync((): McpIssuedCredential | undefined => undefined);
238​
239/**
240 * Refreshes the liveness of a thread's MCP credential. Called on every provider
241 * turn so an active session is never mistaken for an abandoned one.
242 */
243export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
244 activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
245​
246export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
247 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
248​
249export const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
250 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
251​
252/** Exposed for tests. */
253export const __testing = {
254 make: makeWithOptions,
255};