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