The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { ProviderInstanceId, ThreadId } from "@t3tools/contracts"; |
| 2 | import * as Clock from "effect/Clock"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Digest from "effect/crypto/Digest"; |
| 5 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as SynchronizedRef from "effect/SynchronizedRef"; |
| 9 | import { HttpServer } from "effect/http"; |
| 10 | import * as NetAddress from "effect/net/NetAddress"; |
| 11 | |
| 12 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 13 | import * as McpInvocationContext from "./McpInvocationContext.ts"; |
| 14 | import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; |
| 15 | |
| 16 | export 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 | |
| 25 | export interface McpIssuedCredential { |
| 26 | readonly config: McpProviderSession.McpProviderSessionConfig; |
| 27 | } |
| 28 | |
| 29 | export 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 | |
| 40 | export class McpSessionRegistry extends Context.Service< |
| 41 | McpSessionRegistry, |
| 42 | McpSessionRegistryShape |
| 43 | >()("t3/mcp/McpSessionRegistry") {} |
| 44 | |
| 45 | interface AliveMark { |
| 46 | readonly wallMs: number; |
| 47 | readonly monotonicMs: number; |
| 48 | } |
| 49 | |
| 50 | interface CredentialRecord { |
| 51 | readonly tokenHash: string; |
| 52 | readonly scope: McpInvocationContext.McpThreadInvocationScope; |
| 53 | readonly lastAlive: AliveMark; |
| 54 | /** Set when a request finds the token idle; only `touch` clears it, whatever the clocks do. */ |
| 55 | readonly expired: boolean; |
| 56 | } |
| 57 | |
| 58 | interface RegistryState { |
| 59 | readonly records: ReadonlyMap<string, CredentialRecord>; |
| 60 | } |
| 61 | |
| 62 | export interface McpSessionRegistryOptions { |
| 63 | readonly livenessWindowMs?: number; |
| 64 | /** Drives both the wall and monotonic readings. */ |
| 65 | readonly now?: () => number; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * `/mcp` is outside environment auth, so idle tokens stop authenticating. |
| 70 | * Keep expired records until explicit revocation: a trusted provider turn can |
| 71 | * refresh the token its subprocess still holds; MCP requests cannot. |
| 72 | */ |
| 73 | const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000; |
| 74 | |
| 75 | const bytesToHex = (bytes: Uint8Array): string => |
| 76 | Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); |
| 77 | |
| 78 | const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url"); |
| 79 | |
| 80 | // The larger elapsed reading wins: stepping the wall clock back cannot extend a token, |
| 81 | // and wall time that passes while the host sleeps still counts. |
| 82 | const idleMs = (since: AliveMark, now: AliveMark): number => |
| 83 | Math.max(now.wallMs - since.wallMs, now.monotonicMs - since.monotonicMs); |
| 84 | |
| 85 | const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string => |
| 86 | NetAddress.isUnspecified(address) |
| 87 | ? "127.0.0.1" |
| 88 | : NetAddress.formatUrlHostString(NetAddress.formatIp(address)); |
| 89 | |
| 90 | const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( |
| 91 | options: McpSessionRegistryOptions = {}, |
| 92 | ) { |
| 93 | const random = yield* SecureRandom.SecureRandom; |
| 94 | const digest = yield* Digest.Digest; |
| 95 | const environment = yield* ServerEnvironment.ServerEnvironment; |
| 96 | const environmentId = yield* environment.getEnvironmentId; |
| 97 | const httpServer = yield* HttpServer.HttpServer; |
| 98 | const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() }); |
| 99 | const { now } = options; |
| 100 | const currentAliveMark: Effect.Effect<AliveMark> = now |
| 101 | ? Effect.sync(() => { |
| 102 | const timestamp = now(); |
| 103 | return { wallMs: timestamp, monotonicMs: timestamp }; |
| 104 | }) |
| 105 | : Effect.all({ |
| 106 | wallMs: Clock.currentTimeMillis, |
| 107 | monotonicMs: Clock.monotonicTimeNanos.pipe( |
| 108 | Effect.map((nanos) => Number(nanos / 1_000_000n)), |
| 109 | ), |
| 110 | }); |
| 111 | const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS; |
| 112 | const endpoint = NetAddress.isInetAddress(httpServer.address) |
| 113 | ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${httpServer.address.port}/mcp` |
| 114 | : "http://127.0.0.1/mcp"; |
| 115 | |
| 116 | const hashToken = (token: string) => |
| 117 | digest |
| 118 | .digest(Digest.sha256, new TextEncoder().encode(token)) |
| 119 | .pipe(Effect.map(bytesToHex), Effect.orDie); |
| 120 | |
| 121 | const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")( |
| 122 | function* (request) { |
| 123 | const issuedAlive = yield* currentAliveMark; |
| 124 | const providerSessionId = yield* random.uuidV4(); |
| 125 | const rawToken = yield* random.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie); |
| 126 | const tokenHash = yield* hashToken(rawToken); |
| 127 | const browserToolsAvailable = request.browserToolsAvailable ?? true; |
| 128 | const scope: McpInvocationContext.McpThreadInvocationScope = { |
| 129 | environmentId, |
| 130 | requestNamespace: providerSessionId, |
| 131 | thread: { |
| 132 | threadId: ThreadId.make(request.threadId), |
| 133 | providerSessionId, |
| 134 | providerInstanceId: ProviderInstanceId.make(request.providerInstanceId), |
| 135 | subagent: request.subagent === true, |
| 136 | }, |
| 137 | client: undefined, |
| 138 | capabilities: new Set<McpInvocationContext.McpCapability>([ |
| 139 | "orchestration", |
| 140 | "worktree", |
| 141 | "pull-requests", |
| 142 | "issues", |
| 143 | ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])), |
| 144 | ]), |
| 145 | issuedAt: issuedAlive.wallMs, |
| 146 | }; |
| 147 | yield* SynchronizedRef.update(state, ({ records }) => { |
| 148 | const next = new Map(records); |
| 149 | next.set(tokenHash, { tokenHash, scope, lastAlive: issuedAlive, expired: false }); |
| 150 | return { records: next }; |
| 151 | }); |
| 152 | return { |
| 153 | config: { |
| 154 | environmentId, |
| 155 | threadId: scope.thread.threadId, |
| 156 | providerSessionId, |
| 157 | providerInstanceId: scope.thread.providerInstanceId, |
| 158 | endpoint, |
| 159 | authorizationHeader: `Bearer ${rawToken}`, |
| 160 | browserToolsAvailable: scope.capabilities.has("preview"), |
| 161 | capabilities: scope.capabilities, |
| 162 | }, |
| 163 | }; |
| 164 | }, |
| 165 | ); |
| 166 | |
| 167 | const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")( |
| 168 | function* (rawToken) { |
| 169 | if (rawToken.length === 0) return undefined; |
| 170 | const tokenHash = yield* hashToken(rawToken); |
| 171 | const alive = yield* currentAliveMark; |
| 172 | return yield* SynchronizedRef.modify(state, ({ records }) => { |
| 173 | const record = records.get(tokenHash); |
| 174 | if (!record || record.expired) return [undefined, { records }] as const; |
| 175 | if (idleMs(record.lastAlive, alive) > livenessWindowMs) { |
| 176 | const next = new Map(records); |
| 177 | next.set(tokenHash, { ...record, expired: true }); |
| 178 | return [undefined, { records: next }] as const; |
| 179 | } |
| 180 | const next = new Map(records); |
| 181 | next.set(tokenHash, { ...record, lastAlive: alive }); |
| 182 | return [record.scope, { records: next }] as const; |
| 183 | }); |
| 184 | }, |
| 185 | ); |
| 186 | |
| 187 | const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")( |
| 188 | function* (threadId) { |
| 189 | const alive = yield* currentAliveMark; |
| 190 | yield* SynchronizedRef.update(state, ({ records }) => { |
| 191 | const next = new Map(records); |
| 192 | for (const [tokenHash, record] of records) { |
| 193 | if (record.scope.thread.threadId === threadId) { |
| 194 | next.set(tokenHash, { ...record, lastAlive: alive, expired: false }); |
| 195 | } |
| 196 | } |
| 197 | return { records: next }; |
| 198 | }); |
| 199 | }, |
| 200 | ); |
| 201 | |
| 202 | const revokeWhere = (predicate: (record: CredentialRecord) => boolean) => |
| 203 | SynchronizedRef.update(state, ({ records }) => ({ |
| 204 | records: new Map(Array.from(records).filter(([, record]) => !predicate(record))), |
| 205 | })); |
| 206 | |
| 207 | return McpSessionRegistry.of({ |
| 208 | issue, |
| 209 | resolve, |
| 210 | touch, |
| 211 | revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")( |
| 212 | function* (providerSessionId) { |
| 213 | yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId); |
| 214 | }, |
| 215 | ), |
| 216 | revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) { |
| 217 | yield* revokeWhere((record) => record.scope.thread.threadId === threadId); |
| 218 | }), |
| 219 | revokeAll: SynchronizedRef.set(state, { records: new Map() }), |
| 220 | }); |
| 221 | }); |
| 222 | |
| 223 | let activeMcpSessionRegistry: McpSessionRegistryShape | undefined; |
| 224 | |
| 225 | const make = Effect.acquireRelease( |
| 226 | makeWithOptions().pipe( |
| 227 | Effect.tap((registry) => |
| 228 | Effect.sync(() => { |
| 229 | activeMcpSessionRegistry = registry; |
| 230 | }), |
| 231 | ), |
| 232 | ), |
| 233 | (registry) => |
| 234 | Effect.sync(() => { |
| 235 | if (activeMcpSessionRegistry === registry) { |
| 236 | activeMcpSessionRegistry = undefined; |
| 237 | } |
| 238 | }), |
| 239 | ); |
| 240 | |
| 241 | export const layer = Layer.effect(McpSessionRegistry, make); |
| 242 | |
| 243 | export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> => |
| 244 | activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void; |
| 245 | |
| 246 | export const __testing = { |
| 247 | make: makeWithOptions, |
| 248 | }; |