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

McpSessionRegistry.ts

249 lines9.4 KB

1import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Digest from "effect/crypto/Digest";
5import * as SecureRandom from "effect/crypto/SecureRandom";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as SynchronizedRef from "effect/SynchronizedRef";
9import { HttpServer } from "effect/http";
10import * as NetAddress from "effect/net/NetAddress";
11​
12import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
13import * as McpInvocationContext from "./McpInvocationContext.ts";
14import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
15import { routineSpan } from "@t3tools/shared/observability";
16​
17export interface McpCredentialRequest {
18 readonly threadId: ThreadId;
19 readonly providerInstanceId: ProviderInstanceId;
20 /** False omits the preview capability wherever the token is honored. Defaults to full access. */
21 readonly browserToolsAvailable?: boolean;
22 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
23 readonly subagent?: boolean;
25​
26export interface McpIssuedCredential {
27 readonly config: McpProviderSession.McpProviderSessionConfig;
29​
30export interface McpSessionRegistryShape {
31 readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
32 readonly resolve: (
33 rawToken: string,
34 ) => Effect.Effect<McpInvocationContext.McpThreadInvocationScope | undefined>;
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>;
40​
41export class McpSessionRegistry extends Context.Service<
42 McpSessionRegistry,
43 McpSessionRegistryShape
44>()("t3/mcp/McpSessionRegistry") {}
45​
46interface AliveMark {
47 readonly wallMs: number;
48 readonly monotonicMs: number;
50​
51interface CredentialRecord {
52 readonly tokenHash: string;
53 readonly scope: McpInvocationContext.McpThreadInvocationScope;
54 readonly lastAlive: AliveMark;
55 /** Set when a request finds the token idle; only `touch` clears it, whatever the clocks do. */
56 readonly expired: boolean;
58​
59interface RegistryState {
60 readonly records: ReadonlyMap<string, CredentialRecord>;
62​
63export interface McpSessionRegistryOptions {
64 readonly livenessWindowMs?: number;
65 /** Drives both the wall and monotonic readings. */
66 readonly now?: () => number;
68​
69/**
70 * `/mcp` is outside environment auth, so idle tokens stop authenticating.
71 * Keep expired records until explicit revocation: a trusted provider turn can
72 * refresh the token its subprocess still holds; MCP requests cannot.
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​
81// The larger elapsed reading wins: stepping the wall clock back cannot extend a token,
82// and wall time that passes while the host sleeps still counts.
83const idleMs = (since: AliveMark, now: AliveMark): number =>
84 Math.max(now.wallMs - since.wallMs, now.monotonicMs - since.monotonicMs);
85​
86const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string =>
87 NetAddress.isUnspecified(address)
88 ? "127.0.0.1"
89 : NetAddress.formatUrlHostString(NetAddress.formatIp(address));
90​
91const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
92 options: McpSessionRegistryOptions = {},
93) {
94 const random = yield* SecureRandom.SecureRandom;
95 const digest = yield* Digest.Digest;
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 { now } = options;
101 const currentAliveMark: Effect.Effect<AliveMark> = now
102 ? Effect.sync(() => {
103 const timestamp = now();
104 return { wallMs: timestamp, monotonicMs: timestamp };
105 })
106 : Effect.all({
107 wallMs: Clock.currentTimeMillis,
108 monotonicMs: Clock.monotonicTimeNanos.pipe(
109 Effect.map((nanos) => Number(nanos / 1_000_000n)),
110 ),
111 });
112 const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
113 const endpoint = NetAddress.isInetAddress(httpServer.address)
114 ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${httpServer.address.port}/mcp`
115 : "http://127.0.0.1/mcp";
116​
117 const hashToken = (token: string) =>
118 digest
119 .digest(Digest.sha256, new TextEncoder().encode(token))
120 .pipe(Effect.map(bytesToHex), Effect.orDie);
121​
122 const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
123 function* (request) {
124 const issuedAlive = yield* currentAliveMark;
125 const providerSessionId = yield* random.uuidV4();
126 const rawToken = yield* random.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
127 const tokenHash = yield* hashToken(rawToken);
128 const browserToolsAvailable = request.browserToolsAvailable ?? true;
129 const scope: McpInvocationContext.McpThreadInvocationScope = {
130 environmentId,
131 requestNamespace: providerSessionId,
132 thread: {
133 threadId: ThreadId.make(request.threadId),
134 providerSessionId,
135 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
136 subagent: request.subagent === true,
137 },
138 client: undefined,
139 capabilities: new Set<McpInvocationContext.McpCapability>([
140 "orchestration",
141 "worktree",
142 "pull-requests",
143 "issues",
144 ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])),
145 ]),
146 issuedAt: issuedAlive.wallMs,
147 };
148 yield* SynchronizedRef.update(state, ({ records }) => {
149 const next = new Map(records);
150 next.set(tokenHash, { tokenHash, scope, lastAlive: issuedAlive, expired: false });
151 return { records: next };
152 });
153 return {
154 config: {
155 environmentId,
156 threadId: scope.thread.threadId,
157 providerSessionId,
158 providerInstanceId: scope.thread.providerInstanceId,
159 endpoint,
160 authorizationHeader: `Bearer ${rawToken}`,
161 browserToolsAvailable: scope.capabilities.has("preview"),
162 capabilities: scope.capabilities,
163 },
164 };
165 },
166 );
167​
168 const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve", {
169 attributes: routineSpan,
170 })(function* (rawToken) {
171 if (rawToken.length === 0) return undefined;
172 const tokenHash = yield* hashToken(rawToken);
173 const alive = yield* currentAliveMark;
174 return yield* SynchronizedRef.modify(state, ({ records }) => {
175 const record = records.get(tokenHash);
176 if (!record || record.expired) return [undefined, { records }] as const;
177 if (idleMs(record.lastAlive, alive) > livenessWindowMs) {
178 const next = new Map(records);
179 next.set(tokenHash, { ...record, expired: true });
180 return [undefined, { records: next }] as const;
181 }
182 const next = new Map(records);
183 next.set(tokenHash, { ...record, lastAlive: alive });
184 return [record.scope, { records: next }] as const;
185 });
186 });
187​
188 const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
189 function* (threadId) {
190 const alive = yield* currentAliveMark;
191 yield* SynchronizedRef.update(state, ({ records }) => {
192 const next = new Map(records);
193 for (const [tokenHash, record] of records) {
194 if (record.scope.thread.threadId === threadId) {
195 next.set(tokenHash, { ...record, lastAlive: alive, expired: false });
196 }
197 }
198 return { records: next };
199 });
200 },
201 );
202​
203 const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
204 SynchronizedRef.update(state, ({ records }) => ({
205 records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
206 }));
207​
208 return McpSessionRegistry.of({
209 issue,
210 resolve,
211 touch,
212 revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
213 function* (providerSessionId) {
214 yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId);
215 },
216 ),
217 revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
218 yield* revokeWhere((record) => record.scope.thread.threadId === threadId);
219 }),
220 revokeAll: SynchronizedRef.set(state, { records: new Map() }),
221 });
222});
223​
224let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
225​
226const make = Effect.acquireRelease(
227 makeWithOptions().pipe(
228 Effect.tap((registry) =>
229 Effect.sync(() => {
230 activeMcpSessionRegistry = registry;
231 }),
232 ),
233 ),
234 (registry) =>
235 Effect.sync(() => {
236 if (activeMcpSessionRegistry === registry) {
237 activeMcpSessionRegistry = undefined;
238 }
239 }),
240);
241​
242export const layer = Layer.effect(McpSessionRegistry, make);
243​
244export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
245 activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
246​
247export const __testing = {
248 make: makeWithOptions,
249};