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 Digest from "effect/crypto/Digest";
5import * as SecureRandom from "effect/crypto/SecureRandom";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as SynchronizedRef from "effect/SynchronizedRef";
9import { HttpServer } from "effect/http";
10import * as NetAddress from "effect/net/NetAddress";
11
12import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
13import * as McpInvocationContext from "./McpInvocationContext.ts";
14import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
15
16export interface McpCredentialRequest {
17 readonly threadId: ThreadId;
18 readonly providerInstanceId: ProviderInstanceId;
19 /** False omits the preview capability wherever the token is honored. Defaults to full access. */
20 readonly browserToolsAvailable?: boolean;
21 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
22 readonly subagent?: boolean;
23}
24
25export interface McpIssuedCredential {
26 readonly config: McpProviderSession.McpProviderSessionConfig;
27}
28
29export interface McpSessionRegistryShape {
30 readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
31 readonly resolve: (
32 rawToken: string,
33 ) => Effect.Effect<McpInvocationContext.McpThreadInvocationScope | undefined>;
34 readonly touch: (threadId: ThreadId) => Effect.Effect<void>;
35 readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
36 readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
37 readonly revokeAll: Effect.Effect<void>;
38}
39
40export class McpSessionRegistry extends Context.Service<
41 McpSessionRegistry,
42 McpSessionRegistryShape
43>()("t3/mcp/McpSessionRegistry") {}
44
45interface CredentialRecord {
46 readonly tokenHash: string;
47 readonly scope: McpInvocationContext.McpThreadInvocationScope;
48 readonly lastAliveAt: number;
49}
50
51interface RegistryState {
52 readonly records: ReadonlyMap<string, CredentialRecord>;
53}
54
55export interface McpSessionRegistryOptions {
56 readonly livenessWindowMs?: number;
57 readonly now?: () => number;
58}
59
60/**
61 * `/mcp` is outside environment auth, so idle tokens stop authenticating.
62 * Keep expired records until explicit revocation: a trusted provider turn can
63 * refresh the token its subprocess still holds; MCP requests cannot.
64 */
65const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
66
67const bytesToHex = (bytes: Uint8Array): string =>
68 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
69
70const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
71
72const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string =>
73 NetAddress.isUnspecified(address)
74 ? "127.0.0.1"
75 : NetAddress.formatUrlHostString(NetAddress.formatIp(address));
76
77const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
78 options: McpSessionRegistryOptions = {},
79) {
80 const random = yield* SecureRandom.SecureRandom;
81 const digest = yield* Digest.Digest;
82 const environment = yield* ServerEnvironment.ServerEnvironment;
83 const environmentId = yield* environment.getEnvironmentId;
84 const httpServer = yield* HttpServer.HttpServer;
85 const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
86 const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
87 const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
88 const endpoint = NetAddress.isInetAddress(httpServer.address)
89 ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${httpServer.address.port}/mcp`
90 : "http://127.0.0.1/mcp";
91
92 const hashToken = (token: string) =>
93 digest
94 .digest(Digest.sha256, new TextEncoder().encode(token))
95 .pipe(Effect.map(bytesToHex), Effect.orDie);
96
97 const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
98 function* (request) {
99 const issuedAt = yield* currentTimeMillis;
100 const providerSessionId = yield* random.uuidV4();
101 const rawToken = yield* random.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
102 const tokenHash = yield* hashToken(rawToken);
103 const browserToolsAvailable = request.browserToolsAvailable ?? true;
104 const scope: McpInvocationContext.McpThreadInvocationScope = {
105 environmentId,
106 requestNamespace: providerSessionId,
107 thread: {
108 threadId: ThreadId.make(request.threadId),
109 providerSessionId,
110 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
111 subagent: request.subagent === true,
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
218export const __testing = {
219 make: makeWithOptions,
220};