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";
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}
18
19export interface McpIssuedCredential {
20 readonly config: McpProviderSession.McpProviderSessionConfig;
21 readonly expiresAt: number;
22}
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 readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
30 readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
31 readonly revokeAll: Effect.Effect<void>;
32}
33
34export class McpSessionRegistry extends Context.Service<
35 McpSessionRegistry,
36 McpSessionRegistryShape
37>()("t3/mcp/McpSessionRegistry") {}
38
39interface CredentialRecord {
40 readonly tokenHash: string;
41 readonly scope: McpInvocationContext.McpInvocationScope;
42 readonly lastUsedAt: number;
43}
44
45interface RegistryState {
46 readonly records: ReadonlyMap<string, CredentialRecord>;
47}
48
49export interface McpSessionRegistryOptions {
50 readonly idleTimeoutMs?: number;
51 readonly maximumLifetimeMs?: number;
52 readonly now?: () => number;
53}
54
55const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
56const DEFAULT_MAXIMUM_LIFETIME_MS = 8 * 60 * 60 * 1_000;
57
58const bytesToHex = (bytes: Uint8Array): string =>
59 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
60
61const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
62
63const getHttpMcpEndpointHost = (hostname: string): string => {
64 const normalized = hostname.toLowerCase();
65 const endpointHostname =
66 normalized === "0.0.0.0" || normalized === "::" || normalized === "[::]"
67 ? "127.0.0.1"
68 : hostname;
69 return endpointHostname.includes(":") && !endpointHostname.startsWith("[")
70 ? `[${endpointHostname}]`
71 : endpointHostname;
72};
73
74const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
75 options: McpSessionRegistryOptions = {},
76) {
77 const crypto = yield* Crypto.Crypto;
78 const environment = yield* ServerEnvironment.ServerEnvironment;
79 const environmentId = yield* environment.getEnvironmentId;
80 const httpServer = yield* HttpServer.HttpServer;
81 const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
82 const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
83 const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
84 const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
85 const endpoint =
86 httpServer.address._tag === "TcpAddress"
87 ? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
88 : "http://127.0.0.1/mcp";
89
90 const hashToken = (token: string) =>
91 crypto
92 .digest("SHA-256", new TextEncoder().encode(token))
93 .pipe(Effect.map(bytesToHex), Effect.orDie);
94
95 const pruneExpired = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
96 const next = new Map(
97 Array.from(records).filter(
98 ([, record]) =>
99 timestamp <= record.scope.expiresAt && timestamp - record.lastUsedAt <= idleTimeoutMs,
100 ),
101 );
102 return next.size === records.size ? records : next;
103 };
104
105 const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
106 function* (request) {
107 const issuedAt = yield* currentTimeMillis;
108 const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
109 const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
110 const tokenHash = yield* hashToken(rawToken);
111 const expiresAt = issuedAt + maximumLifetimeMs;
112 const scope: McpInvocationContext.McpInvocationScope = {
113 environmentId,
114 threadId: ThreadId.make(request.threadId),
115 providerSessionId,
116 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
117 capabilities: new Set(["preview"]),
118 issuedAt,
119 expiresAt,
120 };
121 yield* SynchronizedRef.update(state, ({ records }) => {
122 const next = new Map(pruneExpired(records, issuedAt));
123 next.set(tokenHash, { tokenHash, scope, lastUsedAt: issuedAt });
124 return { records: next };
125 });
126 return {
127 config: {
128 environmentId,
129 threadId: scope.threadId,
130 providerSessionId,
131 providerInstanceId: scope.providerInstanceId,
132 endpoint,
133 authorizationHeader: `Bearer ${rawToken}`,
134 },
135 expiresAt,
136 };
137 },
138 );
139
140 const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")(
141 function* (rawToken) {
142 if (rawToken.length === 0) return undefined;
143 const tokenHash = yield* hashToken(rawToken);
144 const timestamp = yield* currentTimeMillis;
145 return yield* SynchronizedRef.modify(state, ({ records }) => {
146 const current = pruneExpired(records, timestamp);
147 const record = current.get(tokenHash);
148 if (!record) return [undefined, { records: current }] as const;
149 const next = new Map(current);
150 next.set(tokenHash, { ...record, lastUsedAt: timestamp });
151 return [record.scope, { records: next }] as const;
152 });
153 },
154 );
155
156 const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
157 SynchronizedRef.update(state, ({ records }) => ({
158 records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
159 }));
160
161 return McpSessionRegistry.of({
162 issue,
163 resolve,
164 revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
165 function* (providerSessionId) {
166 yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
167 },
168 ),
169 revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
170 yield* revokeWhere((record) => record.scope.threadId === threadId);
171 }),
172 revokeAll: SynchronizedRef.set(state, { records: new Map() }),
173 });
174});
175
176let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
177
178const make = Effect.acquireRelease(
179 makeWithOptions().pipe(
180 Effect.tap((registry) =>
181 Effect.sync(() => {
182 activeMcpSessionRegistry = registry;
183 }),
184 ),
185 ),
186 (registry) =>
187 Effect.sync(() => {
188 if (activeMcpSessionRegistry === registry) {
189 activeMcpSessionRegistry = undefined;
190 }
191 }),
192);
193
194export const layer = Layer.effect(McpSessionRegistry, make);
195
196export const issueActiveMcpCredential = (
197 request: McpCredentialRequest,
198): Effect.Effect<McpIssuedCredential | undefined> =>
199 activeMcpSessionRegistry
200 ? activeMcpSessionRegistry
201 .revokeThread(request.threadId)
202 .pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
203 : Effect.sync((): McpIssuedCredential | undefined => undefined);
204
205export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
206 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
207
208export const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
209 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
210
211/** Exposed for tests. */
212export const __testing = {
213 make: makeWithOptions,
214};