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