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