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

McpSessionRegistry.ts

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