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

McpSessionRegistry.ts

218 lines8.1 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/http";
9import * as NetAddress from "effect/net/NetAddress";
10​
11import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
12import * as McpInvocationContext from "./McpInvocationContext.ts";
13import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
14​
15export interface McpCredentialRequest {
16 readonly threadId: ThreadId;
17 readonly providerInstanceId: ProviderInstanceId;
18 /** False omits the preview capability wherever the token is honored. Defaults to full access. */
19 readonly browserToolsAvailable?: boolean;
20 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
21 readonly subagent?: boolean;
23​
24export interface McpIssuedCredential {
25 readonly config: McpProviderSession.McpProviderSessionConfig;
27​
28export interface McpSessionRegistryShape {
29 readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
30 readonly resolve: (
31 rawToken: string,
32 ) => Effect.Effect<McpInvocationContext.McpThreadInvocationScope | undefined>;
33 readonly touch: (threadId: ThreadId) => Effect.Effect<void>;
34 readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
35 readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
36 readonly revokeAll: Effect.Effect<void>;
38​
39export class McpSessionRegistry extends Context.Service<
40 McpSessionRegistry,
41 McpSessionRegistryShape
42>()("t3/mcp/McpSessionRegistry") {}
43​
44interface CredentialRecord {
45 readonly tokenHash: string;
46 readonly scope: McpInvocationContext.McpThreadInvocationScope;
47 readonly lastAliveAt: number;
49​
50interface RegistryState {
51 readonly records: ReadonlyMap<string, CredentialRecord>;
53​
54export interface McpSessionRegistryOptions {
55 readonly livenessWindowMs?: number;
56 readonly now?: () => number;
58​
59/**
60 * `/mcp` is outside environment auth, so idle tokens stop authenticating.
61 * Keep expired records until explicit revocation: a trusted provider turn can
62 * refresh the token its subprocess still holds; MCP requests cannot.
63 */
64const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
65​
66const bytesToHex = (bytes: Uint8Array): string =>
67 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
68​
69const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
70​
71const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string =>
72 NetAddress.isUnspecified(address)
73 ? "127.0.0.1"
74 : NetAddress.formatUrlHostString(NetAddress.formatIp(address));
75​
76const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
77 options: McpSessionRegistryOptions = {},
78) {
79 const crypto = yield* Crypto.Crypto;
80 const environment = yield* ServerEnvironment.ServerEnvironment;
81 const environmentId = yield* environment.getEnvironmentId;
82 const httpServer = yield* HttpServer.HttpServer;
83 const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
84 const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
85 const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
86 const endpoint = NetAddress.isInetAddress(httpServer.address)
87 ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${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 issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
96 function* (request) {
97 const issuedAt = yield* currentTimeMillis;
98 const providerSessionId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
99 const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
100 const tokenHash = yield* hashToken(rawToken);
101 const browserToolsAvailable = request.browserToolsAvailable ?? true;
102 const scope: McpInvocationContext.McpThreadInvocationScope = {
103 environmentId,
104 requestNamespace: providerSessionId,
105 thread: {
106 threadId: ThreadId.make(request.threadId),
107 providerSessionId,
108 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
109 subagent: request.subagent === true,
110 },
111 client: undefined,
112 capabilities: new Set<McpInvocationContext.McpCapability>([
113 "orchestration",
114 "worktree",
115 "pull-requests",
116 ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])),
117 ]),
118 issuedAt,
119 };
120 yield* SynchronizedRef.update(state, ({ records }) => {
121 const next = new Map(records);
122 next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
123 return { records: next };
124 });
125 return {
126 config: {
127 environmentId,
128 threadId: scope.thread.threadId,
129 providerSessionId,
130 providerInstanceId: scope.thread.providerInstanceId,
131 endpoint,
132 authorizationHeader: `Bearer ${rawToken}`,
133 browserToolsAvailable: scope.capabilities.has("preview"),
134 capabilities: scope.capabilities,
135 },
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 record = records.get(tokenHash);
147 if (!record || timestamp - record.lastAliveAt > livenessWindowMs) {
148 return [undefined, { records }] as const;
149 }
150 const next = new Map(records);
151 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
152 return [record.scope, { records: next }] as const;
153 });
154 },
155 );
156​
157 const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
158 function* (threadId) {
159 const timestamp = yield* currentTimeMillis;
160 yield* SynchronizedRef.update(state, ({ records }) => {
161 const next = new Map(records);
162 for (const [tokenHash, record] of records) {
163 if (record.scope.thread.threadId === threadId) {
164 next.set(tokenHash, { ...record, lastAliveAt: timestamp });
165 }
166 }
167 return { records: next };
168 });
169 },
170 );
171​
172 const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
173 SynchronizedRef.update(state, ({ records }) => ({
174 records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
175 }));
176​
177 return McpSessionRegistry.of({
178 issue,
179 resolve,
180 touch,
181 revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
182 function* (providerSessionId) {
183 yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId);
184 },
185 ),
186 revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
187 yield* revokeWhere((record) => record.scope.thread.threadId === threadId);
188 }),
189 revokeAll: SynchronizedRef.set(state, { records: new Map() }),
190 });
191});
192​
193let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
194​
195const make = Effect.acquireRelease(
196 makeWithOptions().pipe(
197 Effect.tap((registry) =>
198 Effect.sync(() => {
199 activeMcpSessionRegistry = registry;
200 }),
201 ),
202 ),
203 (registry) =>
204 Effect.sync(() => {
205 if (activeMcpSessionRegistry === registry) {
206 activeMcpSessionRegistry = undefined;
207 }
208 }),
209);
210​
211export const layer = Layer.effect(McpSessionRegistry, make);
212​
213export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
214 activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
215​
216export const __testing = {
217 make: makeWithOptions,
218};