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

McpSessionRegistry.ts

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