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