The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | type EnvironmentId, |
| 3 | OrchestratorMcpFailure, |
| 4 | type PeerLinkError, |
| 5 | type ProviderInteractionMode, |
| 6 | type OrchestrationV2LinkedSender, |
| 7 | type RuntimeMode, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import * as Context from "effect/Context"; |
| 10 | import * as DateTime from "effect/DateTime"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import * as Option from "effect/Option"; |
| 14 | import * as Ref from "effect/Ref"; |
| 15 | import * as Result from "effect/Result"; |
| 16 | import * as Schema from "effect/Schema"; |
| 17 | import * as HttpBody from "effect/http/HttpBody"; |
| 18 | import * as HttpClient from "effect/http/HttpClient"; |
| 19 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 20 | |
| 21 | import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; |
| 22 | import * as PeerLinks from "./PeerLinks.ts"; |
| 23 | |
| 24 | /** The only MCP protocol version a T3 Code `/mcp` registers. */ |
| 25 | const PROTOCOL_VERSION = "2025-06-18"; |
| 26 | |
| 27 | /** A title can be any length; the header carrying it stays well under HTTP header limits. */ |
| 28 | const SENDER_TITLE_MAX_LENGTH = 200; |
| 29 | |
| 30 | /** The limits a call carries to the peer: the calling agent's modes here. */ |
| 31 | export interface PeerCallLimits { |
| 32 | readonly runtimeMode: RuntimeMode; |
| 33 | readonly interactionMode: ProviderInteractionMode; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Calls a linked environment's T3 MCP tools as this environment's outside |
| 38 | * agent. Each call carries the calling agent's limits in `T3-Mode-Limit`, so |
| 39 | * the peer enforces the narrower of those and the link's own access. |
| 40 | */ |
| 41 | export class PeerMcpClient extends Context.Service< |
| 42 | PeerMcpClient, |
| 43 | { |
| 44 | /** Calls `tool` on the peer and decodes its structured result with `success`. */ |
| 45 | readonly call: <S extends Schema.Decoder<unknown>>(input: { |
| 46 | readonly environmentId: EnvironmentId; |
| 47 | readonly tool: string; |
| 48 | readonly arguments: Record<string, unknown>; |
| 49 | readonly limits: PeerCallLimits; |
| 50 | /** The thread here the call is made for, sent as `T3-Sender-Thread`. */ |
| 51 | readonly sender?: OrchestrationV2LinkedSender; |
| 52 | readonly success: S; |
| 53 | }) => Effect.Effect<S["Type"], OrchestratorMcpFailure>; |
| 54 | } |
| 55 | >()("t3/peer/PeerMcpClient") {} |
| 56 | |
| 57 | const ToolCallResponse = Schema.Struct({ |
| 58 | result: Schema.optional( |
| 59 | Schema.Struct({ |
| 60 | content: Schema.Array( |
| 61 | Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) }), |
| 62 | ), |
| 63 | structuredContent: Schema.optional(Schema.Unknown), |
| 64 | isError: Schema.optional(Schema.Boolean), |
| 65 | }), |
| 66 | ), |
| 67 | error: Schema.optional(Schema.Struct({ code: Schema.Number, message: Schema.String })), |
| 68 | }); |
| 69 | const decodeToolCallResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(ToolCallResponse)); |
| 70 | const decodeFailure = Schema.decodeUnknownOption( |
| 71 | Schema.fromJsonString( |
| 72 | Schema.Struct({ code: OrchestratorMcpFailure.fields.code, message: Schema.String }), |
| 73 | ), |
| 74 | ); |
| 75 | |
| 76 | /** A peer link problem, as the agent that asked hears it. */ |
| 77 | const fromLinkError = (error: PeerLinkError) => |
| 78 | new OrchestratorMcpFailure({ |
| 79 | code: |
| 80 | error.reason === "unknown_link" |
| 81 | ? "invalid_request" |
| 82 | : error.reason === "expired" || error.reason === "incompatible" |
| 83 | ? "capability_denied" |
| 84 | : "orchestration_error", |
| 85 | message: error.message, |
| 86 | }); |
| 87 | |
| 88 | /** Not final, so a task already running there resumes once the beta is on there again. */ |
| 89 | const linkedEnvironmentsOffThere = new OrchestratorMcpFailure({ |
| 90 | code: "orchestration_error", |
| 91 | message: |
| 92 | "The linked environment has Linked environments turned off. Turn it on in its Settings → Labs.", |
| 93 | }); |
| 94 | |
| 95 | const stoppedAnswering = new OrchestratorMcpFailure({ |
| 96 | code: "orchestration_error", |
| 97 | message: "The linked environment stopped answering.", |
| 98 | }); |
| 99 | |
| 100 | /** The body of an MCP response: JSON, or a single server-sent event carrying JSON. */ |
| 101 | const responseJson = (contentType: string | undefined, text: string) => |
| 102 | contentType?.includes("text/event-stream") === true |
| 103 | ? text |
| 104 | .split("\n") |
| 105 | .filter((line) => line.startsWith("data:")) |
| 106 | .map((line) => line.slice("data:".length).trim()) |
| 107 | .join("") |
| 108 | : text; |
| 109 | |
| 110 | const make = Effect.gen(function* () { |
| 111 | const links = yield* PeerLinks.PeerLinks; |
| 112 | const httpClient = yield* HttpClient.HttpClient; |
| 113 | // One MCP session per peer and address, reused across calls. The peer keeps |
| 114 | // sessions in memory, so a restart there answers 404 and we start a new one. |
| 115 | const sessions = yield* Ref.make<ReadonlyMap<string, string>>(new Map()); |
| 116 | |
| 117 | const post = (url: string, token: string, body: unknown, headers: Record<string, string>) => |
| 118 | httpClient.execute( |
| 119 | HttpClientRequest.post(`${url}/mcp`).pipe( |
| 120 | HttpClientRequest.setHeaders({ |
| 121 | accept: "application/json, text/event-stream", |
| 122 | authorization: `Bearer ${token}`, |
| 123 | ...headers, |
| 124 | }), |
| 125 | HttpClientRequest.setBody(HttpBody.text(JSON.stringify(body), "application/json")), |
| 126 | ), |
| 127 | ); |
| 128 | |
| 129 | // A peer that renews a used link says when it now ends; one that does not sends nothing. |
| 130 | const recordLinkExpiry = ( |
| 131 | link: PeerLinks.ResolvedPeerLink["link"], |
| 132 | headers: Readonly<Record<string, string>>, |
| 133 | ) => |
| 134 | Option.match( |
| 135 | Option.filter( |
| 136 | Option.flatMap( |
| 137 | Option.fromNullishOr(headers[McpInvocationContext.LINK_EXPIRES_AT_HEADER]), |
| 138 | DateTime.make, |
| 139 | ), |
| 140 | (expiresAt) => !DateTime.Equivalence(expiresAt, link.expiresAt), |
| 141 | ), |
| 142 | { |
| 143 | onNone: () => Effect.void, |
| 144 | onSome: (expiresAt) => links.recordExpiry(link.environmentId, expiresAt), |
| 145 | }, |
| 146 | ); |
| 147 | |
| 148 | const openSession = Effect.fn("PeerMcpClient.openSession")( |
| 149 | function* ( |
| 150 | { link, url, token }: PeerLinks.ResolvedPeerLink, |
| 151 | limitHeader: Record<string, string>, |
| 152 | ) { |
| 153 | const initialized = yield* post( |
| 154 | url, |
| 155 | token, |
| 156 | { |
| 157 | jsonrpc: "2.0", |
| 158 | id: 0, |
| 159 | method: "initialize", |
| 160 | params: { |
| 161 | protocolVersion: PROTOCOL_VERSION, |
| 162 | capabilities: {}, |
| 163 | clientInfo: { name: "t3code-peer", version: "1" }, |
| 164 | }, |
| 165 | }, |
| 166 | limitHeader, |
| 167 | ); |
| 168 | const sessionId = initialized.headers["mcp-session-id"]; |
| 169 | if (initialized.status === 403) return yield* linkedEnvironmentsOffThere; |
| 170 | if (initialized.status !== 200 || sessionId === undefined) { |
| 171 | return yield* new OrchestratorMcpFailure({ |
| 172 | code: initialized.status === 401 ? "capability_denied" : "orchestration_error", |
| 173 | message: |
| 174 | initialized.status === 401 |
| 175 | ? "The linked environment no longer accepts this link. It may have been revoked there; link it again." |
| 176 | : `The linked environment refused to start an MCP session (HTTP ${initialized.status}).`, |
| 177 | }); |
| 178 | } |
| 179 | yield* recordLinkExpiry(link, initialized.headers); |
| 180 | yield* post( |
| 181 | url, |
| 182 | token, |
| 183 | { jsonrpc: "2.0", method: "notifications/initialized" }, |
| 184 | { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION }, |
| 185 | ); |
| 186 | return sessionId; |
| 187 | }, |
| 188 | // Only the handshake is bounded: a forwarded tool call may wait for minutes. |
| 189 | (effect, { url }) => Effect.timeout(effect, PeerLinks.probeTimeout(url)), |
| 190 | ); |
| 191 | |
| 192 | const call: PeerMcpClient["Service"]["call"] = Effect.fn("PeerMcpClient.call")( |
| 193 | function* (input) { |
| 194 | const resolved = yield* links |
| 195 | .resolve(input.environmentId) |
| 196 | .pipe(Effect.mapError(fromLinkError)); |
| 197 | const limitHeader = { |
| 198 | [McpInvocationContext.MODE_LIMIT_HEADER]: `${input.limits.runtimeMode}/${input.limits.interactionMode}`, |
| 199 | }; |
| 200 | const senderHeader = |
| 201 | input.sender === undefined |
| 202 | ? {} |
| 203 | : { |
| 204 | [McpInvocationContext.SENDER_THREAD_HEADER]: [ |
| 205 | input.sender.environmentId, |
| 206 | input.sender.threadId, |
| 207 | // Whole code points, so a cut never leaves half an emoji for encodeURIComponent. |
| 208 | Array.from(input.sender.title).slice(0, SENDER_TITLE_MAX_LENGTH).join(""), |
| 209 | ] |
| 210 | // encodeURIComponent throws on an unpaired surrogate, which a title can hold. |
| 211 | .map((part) => encodeURIComponent(part.toWellFormed())) |
| 212 | .join("/"), |
| 213 | }; |
| 214 | const sessionKey = `${input.environmentId} ${resolved.url}`; |
| 215 | const callOnce = (sessionId: string) => |
| 216 | post( |
| 217 | resolved.url, |
| 218 | resolved.token, |
| 219 | { |
| 220 | jsonrpc: "2.0", |
| 221 | id: 1, |
| 222 | method: "tools/call", |
| 223 | params: { name: input.tool, arguments: input.arguments }, |
| 224 | }, |
| 225 | { |
| 226 | ...limitHeader, |
| 227 | ...senderHeader, |
| 228 | "mcp-session-id": sessionId, |
| 229 | "mcp-protocol-version": PROTOCOL_VERSION, |
| 230 | }, |
| 231 | ); |
| 232 | const existing = (yield* Ref.get(sessions)).get(sessionKey); |
| 233 | const sessionId = existing ?? (yield* openSession(resolved, limitHeader)); |
| 234 | // The initialized session outlives a tool request, including a long wait or cancellation. |
| 235 | if (existing === undefined) { |
| 236 | yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, sessionId)); |
| 237 | } |
| 238 | let response = yield* callOnce(sessionId); |
| 239 | if (response.status === 404) { |
| 240 | const renewed = yield* openSession(resolved, limitHeader); |
| 241 | yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, renewed)); |
| 242 | response = yield* callOnce(renewed); |
| 243 | } |
| 244 | if (response.status === 401) { |
| 245 | return yield* new OrchestratorMcpFailure({ |
| 246 | code: "capability_denied", |
| 247 | message: |
| 248 | "The linked environment no longer accepts this link. It may have been revoked there; link it again.", |
| 249 | }); |
| 250 | } |
| 251 | if (response.status === 403) return yield* linkedEnvironmentsOffThere; |
| 252 | if (response.status !== 200) { |
| 253 | return yield* new OrchestratorMcpFailure({ |
| 254 | code: "orchestration_error", |
| 255 | message: `The linked environment answered HTTP ${response.status}.`, |
| 256 | }); |
| 257 | } |
| 258 | yield* recordLinkExpiry(resolved.link, response.headers); |
| 259 | const body = yield* decodeToolCallResponse( |
| 260 | responseJson(response.headers["content-type"], yield* response.text), |
| 261 | ).pipe( |
| 262 | Effect.mapError( |
| 263 | () => |
| 264 | new OrchestratorMcpFailure({ |
| 265 | code: "orchestration_error", |
| 266 | message: "The linked environment answered in an unexpected shape.", |
| 267 | }), |
| 268 | ), |
| 269 | ); |
| 270 | if (body.error !== undefined) { |
| 271 | return Result.fail( |
| 272 | new OrchestratorMcpFailure({ code: "invalid_request", message: body.error.message }), |
| 273 | ); |
| 274 | } |
| 275 | if (body.result === undefined) { |
| 276 | return yield* new OrchestratorMcpFailure({ |
| 277 | code: "invalid_request", |
| 278 | message: "The linked environment returned no result.", |
| 279 | }); |
| 280 | } |
| 281 | const text = body.result.content.map((part) => part.text ?? "").join(""); |
| 282 | if (body.result.isError === true) { |
| 283 | // A refusal keeps the peer's own code, so the agent sees why it was refused. |
| 284 | const refused = decodeFailure(text); |
| 285 | return Result.fail( |
| 286 | refused._tag === "Some" |
| 287 | ? new OrchestratorMcpFailure({ |
| 288 | code: refused.value.code, |
| 289 | message: refused.value.message, |
| 290 | }) |
| 291 | : new OrchestratorMcpFailure({ |
| 292 | code: "orchestration_error", |
| 293 | message: text || "The linked environment refused the call.", |
| 294 | }), |
| 295 | ); |
| 296 | } |
| 297 | const success = Schema.fromJsonString(input.success); |
| 298 | return yield* Schema.decodeEffect(success)(text).pipe( |
| 299 | Effect.map(Result.succeed), |
| 300 | Effect.mapError( |
| 301 | () => |
| 302 | new OrchestratorMcpFailure({ |
| 303 | code: "orchestration_error", |
| 304 | message: |
| 305 | "The linked environment's answer did not match this version. Update both environments.", |
| 306 | }), |
| 307 | ), |
| 308 | ); |
| 309 | }, |
| 310 | (effect, input) => |
| 311 | effect.pipe( |
| 312 | Effect.tapError((error) => |
| 313 | links.recordOutcome(input.environmentId, { error: error.message }), |
| 314 | ), |
| 315 | // A refusal is still an answer: the link works, so only this call fails. |
| 316 | Effect.tap(() => links.recordOutcome(input.environmentId, { error: null })), |
| 317 | // Recorded above with the transport's own message; the agent hears it plainly. |
| 318 | Effect.catchTags({ |
| 319 | HttpClientError: () => Effect.fail(stoppedAnswering), |
| 320 | TimeoutError: () => Effect.fail(stoppedAnswering), |
| 321 | }), |
| 322 | Effect.flatMap(Effect.fromResult), |
| 323 | ), |
| 324 | ); |
| 325 | |
| 326 | return PeerMcpClient.of({ call }); |
| 327 | }); |
| 328 | |
| 329 | export const layer = Layer.effect(PeerMcpClient, make); |