Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerMcpClient.ts

397 lines16.2 KB

1import {
2 type EnvironmentId,
3 OrchestratorMcpFailure,
4 type PeerLinkError,
5 type ProviderInteractionMode,
6 type OrchestrationV2LinkedSender,
7 type RuntimeMode,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Ref from "effect/Ref";
15import * as Result from "effect/Result";
16import * as Schema from "effect/Schema";
17import * as HttpBody from "effect/http/HttpBody";
18import * as HttpClient from "effect/http/HttpClient";
19import * as HttpClientRequest from "effect/http/HttpClientRequest";
20​
21import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
22import * as PeerLinks from "./PeerLinks.ts";
23​
24/** The only MCP protocol version a T3 Code `/mcp` registers. */
25const PROTOCOL_VERSION = "2025-06-18";
26​
27/** A title can be any length; the header carrying it stays well under HTTP header limits. */
28const SENDER_TITLE_MAX_LENGTH = 200;
29​
30/** The limits a call carries to the peer: the calling agent's modes here. */
31export interface PeerCallLimits {
32 readonly runtimeMode: RuntimeMode;
33 readonly interactionMode: ProviderInteractionMode;
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 */
41export 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​
57const 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});
69const decodeToolCallResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(ToolCallResponse));
70const decodeFailure = Schema.decodeUnknownOption(
71 Schema.fromJsonString(
72 Schema.Struct({ code: OrchestratorMcpFailure.fields.code, message: Schema.String }),
73 ),
74);
75​
76const NOTHING_SENT =
77 "The call did not run there. Retry once in a moment; if it fails again, tell the user instead of retrying.";
78const OUTCOME_UNKNOWN =
79 "The call may still have run there. Retry a read once. Do not repeat a send or launch unless reading there shows it did not arrive; if you cannot tell, tell the user the outcome is unknown.";
80​
81/**
82 * A lost transport, as the agent that asked hears it: what kind of failure it
83 * was, whether the call can have run there, and whether to retry. All stay
84 * `orchestration_error`, which `RemoteDelegation` already follows again.
85 */
86export const transportFailure = {
87 /** No address answered as this peer, so the token never left. */
88 unreachable: (didNotAnswer: string) =>
89 new OrchestratorMcpFailure({
90 code: "orchestration_error",
91 message: `${didNotAnswer} It may be offline or asleep, or its address may have changed, and the call did not run there. Retrying right away rarely helps: go on with other work and try again later, or tell the user it is unreachable.`,
92 }),
93 /** The peer answered the reachability check, then no session started. */
94 sessionNotStarted: new OrchestratorMcpFailure({
95 code: "orchestration_error",
96 message: `The linked environment answered a reachability check, then did not start a session. It may be waking up or restarting. ${NOTHING_SENT}`,
97 }),
98 /** The tool request left and no reply came back. */
99 replyLost: new OrchestratorMcpFailure({
100 code: "orchestration_error",
101 message: `The connection to the linked environment dropped before its reply arrived. ${OUTCOME_UNKNOWN}`,
102 }),
103 /** A 5xx is mostly a tunnel or proxy speaking for a peer behind it, such as Cloudflare's 524. */
104 gateway: (status: number, toolRequestSent: boolean) =>
105 new OrchestratorMcpFailure({
106 code: "orchestration_error",
107 message: `The linked environment's address answered HTTP ${status} instead of T3 Code. That is usually a tunnel or proxy in front of it reporting that T3 Code there is down, restarting, or took too long. ${toolRequestSent ? OUTCOME_UNKNOWN : NOTHING_SENT}`,
108 }),
109};
110​
111/** The handshake's own transport failure, kept apart from one after the tool request left. */
112class PeerSessionNotStarted extends Schema.TaggedError<PeerSessionNotStarted>()(
113 "PeerSessionNotStarted",
114 { cause: Schema.Defect() },
115) {}
116​
117/** A 5xx from the peer's address, which says nothing lasting about the link. */
118class PeerGatewayError extends Schema.TaggedError<PeerGatewayError>()("PeerGatewayError", {
119 status: Schema.Number,
120 toolRequestSent: Schema.Boolean,
121}) {}
122​
123/** A peer link problem, as the agent that asked hears it. */
124const fromLinkError = (error: PeerLinkError) =>
125 error.reason === "unreachable"
126 ? transportFailure.unreachable(error.message)
127 : new OrchestratorMcpFailure({
128 code:
129 error.reason === "unknown_link"
130 ? "invalid_request"
131 : error.reason === "expired" || error.reason === "incompatible"
132 ? "capability_denied"
133 : "orchestration_error",
134 message: error.message,
135 });
136​
137/** Not final, so a task already running there resumes once the beta is on there again. */
138const linkedEnvironmentsOffThere = new OrchestratorMcpFailure({
139 code: "orchestration_error",
140 message:
141 "The linked environment has Linked environments turned off. Turn it on in its Settings → Labs.",
142});
143​
144/** The body of an MCP response: JSON, or a single server-sent event carrying JSON. */
145const responseJson = (contentType: string | undefined, text: string) =>
146 contentType?.includes("text/event-stream") === true
147 ? text
148 .split("\n")
149 .filter((line) => line.startsWith("data:"))
150 .map((line) => line.slice("data:".length).trim())
151 .join("")
152 : text;
153​
154const make = Effect.gen(function* () {
155 const links = yield* PeerLinks.PeerLinks;
156 const httpClient = yield* HttpClient.HttpClient;
157 // One MCP session per peer and address, reused across calls. The peer keeps
158 // sessions in memory, so a restart there answers 404 and we start a new one.
159 const sessions = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
160​
161 const post = (url: string, token: string, body: unknown, headers: Record<string, string>) =>
162 httpClient.execute(
163 HttpClientRequest.post(`${url}/mcp`).pipe(
164 HttpClientRequest.setHeaders({
165 accept: "application/json, text/event-stream",
166 authorization: `Bearer ${token}`,
167 ...headers,
168 }),
169 HttpClientRequest.setBody(HttpBody.text(JSON.stringify(body), "application/json")),
170 ),
171 );
172​
173 // A peer that renews a used link says when it now ends; one that does not sends nothing.
174 const recordLinkExpiry = (
175 link: PeerLinks.ResolvedPeerLink["link"],
176 headers: Readonly<Record<string, string>>,
177 ) =>
178 Option.match(
179 Option.filter(
180 Option.flatMap(
181 Option.fromNullishOr(headers[McpInvocationContext.LINK_EXPIRES_AT_HEADER]),
182 DateTime.make,
183 ),
184 (expiresAt) => !DateTime.Equivalence(expiresAt, link.expiresAt),
185 ),
186 {
187 onNone: () => Effect.void,
188 onSome: (expiresAt) => links.recordExpiry(link.environmentId, expiresAt),
189 },
190 );
191​
192 const openSession = Effect.fn("PeerMcpClient.openSession")(
193 function* (
194 { link, url, token }: PeerLinks.ResolvedPeerLink,
195 limitHeader: Record<string, string>,
196 ) {
197 const initialized = yield* post(
198 url,
199 token,
200 {
201 jsonrpc: "2.0",
202 id: 0,
203 method: "initialize",
204 params: {
205 protocolVersion: PROTOCOL_VERSION,
206 capabilities: {},
207 clientInfo: { name: "t3code-peer", version: "1" },
208 },
209 },
210 limitHeader,
211 );
212 const sessionId = initialized.headers["mcp-session-id"];
213 if (initialized.status === 403) return yield* linkedEnvironmentsOffThere;
214 if (initialized.status >= 500) {
215 return yield* new PeerGatewayError({ status: initialized.status, toolRequestSent: false });
216 }
217 if (initialized.status !== 200 || sessionId === undefined) {
218 return yield* new OrchestratorMcpFailure({
219 code: initialized.status === 401 ? "capability_denied" : "orchestration_error",
220 message:
221 initialized.status === 401
222 ? "The linked environment no longer accepts this link. It may have been revoked there; link it again."
223 : `The linked environment refused to start an MCP session (HTTP ${initialized.status}).`,
224 });
225 }
226 yield* recordLinkExpiry(link, initialized.headers);
227 const notified = yield* post(
228 url,
229 token,
230 { jsonrpc: "2.0", method: "notifications/initialized" },
231 { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION },
232 );
233 if (notified.status >= 500) {
234 return yield* new PeerGatewayError({ status: notified.status, toolRequestSent: false });
235 }
236 return sessionId;
237 },
238 // Only the handshake is bounded: a forwarded tool call may wait for minutes.
239 (effect, { url }) =>
240 effect.pipe(
241 Effect.timeout(PeerLinks.probeTimeout(url)),
242 Effect.catchTags({
243 HttpClientError: (cause) => Effect.fail(new PeerSessionNotStarted({ cause })),
244 TimeoutError: (cause) => Effect.fail(new PeerSessionNotStarted({ cause })),
245 }),
246 ),
247 );
248​
249 const call: PeerMcpClient["Service"]["call"] = Effect.fn("PeerMcpClient.call")(
250 function* (input) {
251 const resolved = yield* links.resolve(input.environmentId);
252 const limitHeader = {
253 [McpInvocationContext.MODE_LIMIT_HEADER]: `${input.limits.runtimeMode}/${input.limits.interactionMode}`,
254 };
255 const senderHeader =
256 input.sender === undefined
257 ? {}
258 : {
259 [McpInvocationContext.SENDER_THREAD_HEADER]: [
260 input.sender.environmentId,
261 input.sender.threadId,
262 // Whole code points, so a cut never leaves half an emoji for encodeURIComponent.
263 Array.from(input.sender.title).slice(0, SENDER_TITLE_MAX_LENGTH).join(""),
264 ]
265 // encodeURIComponent throws on an unpaired surrogate, which a title can hold.
266 .map((part) => encodeURIComponent(part.toWellFormed()))
267 .join("/"),
268 };
269 const sessionKey = `${input.environmentId} ${resolved.url}`;
270 const callOnce = (sessionId: string) =>
271 post(
272 resolved.url,
273 resolved.token,
274 {
275 jsonrpc: "2.0",
276 id: 1,
277 method: "tools/call",
278 params: { name: input.tool, arguments: input.arguments },
279 },
280 {
281 ...limitHeader,
282 ...senderHeader,
283 "mcp-session-id": sessionId,
284 "mcp-protocol-version": PROTOCOL_VERSION,
285 },
286 );
287 const existing = (yield* Ref.get(sessions)).get(sessionKey);
288 const sessionId = existing ?? (yield* openSession(resolved, limitHeader));
289 // The initialized session outlives a tool request, including a long wait or cancellation.
290 if (existing === undefined) {
291 yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, sessionId));
292 }
293 let response = yield* callOnce(sessionId);
294 if (response.status === 404) {
295 const renewed = yield* openSession(resolved, limitHeader);
296 yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, renewed));
297 response = yield* callOnce(renewed);
298 }
299 if (response.status === 401) {
300 return yield* new OrchestratorMcpFailure({
301 code: "capability_denied",
302 message:
303 "The linked environment no longer accepts this link. It may have been revoked there; link it again.",
304 });
305 }
306 if (response.status === 403) return yield* linkedEnvironmentsOffThere;
307 if (response.status >= 500) {
308 return yield* new PeerGatewayError({ status: response.status, toolRequestSent: true });
309 }
310 if (response.status !== 200) {
311 return yield* new OrchestratorMcpFailure({
312 code: "orchestration_error",
313 message: `The linked environment answered HTTP ${response.status}.`,
314 });
315 }
316 yield* recordLinkExpiry(resolved.link, response.headers);
317 const body = yield* decodeToolCallResponse(
318 responseJson(response.headers["content-type"], yield* response.text),
319 ).pipe(
320 Effect.mapError(
321 () =>
322 new OrchestratorMcpFailure({
323 code: "orchestration_error",
324 message: "The linked environment answered in an unexpected shape.",
325 }),
326 ),
327 );
328 if (body.error !== undefined) {
329 return Result.fail(
330 new OrchestratorMcpFailure({ code: "invalid_request", message: body.error.message }),
331 );
332 }
333 if (body.result === undefined) {
334 return yield* new OrchestratorMcpFailure({
335 code: "orchestration_error",
336 message: "The linked environment returned no result.",
337 });
338 }
339 const text = body.result.content.map((part) => part.text ?? "").join("");
340 if (body.result.isError === true) {
341 // A refusal keeps the peer's own code, so the agent sees why it was refused.
342 const refused = decodeFailure(text);
343 return Result.fail(
344 refused._tag === "Some"
345 ? new OrchestratorMcpFailure({
346 code: refused.value.code,
347 message: refused.value.message,
348 })
349 : new OrchestratorMcpFailure({
350 code: "orchestration_error",
351 message: text || "The linked environment refused the call.",
352 }),
353 );
354 }
355 const success = Schema.fromJsonString(input.success);
356 return yield* Schema.decodeEffect(success)(text).pipe(
357 Effect.map(Result.succeed),
358 Effect.mapError(
359 () =>
360 new OrchestratorMcpFailure({
361 code: "orchestration_error",
362 message:
363 "The linked environment's answer did not match this version. Update both environments.",
364 }),
365 ),
366 );
367 },
368 (effect, input) =>
369 effect.pipe(
370 Effect.tapError((error) =>
371 // Listing checks again whether the peer answers, so a stored
372 // "did not answer" would only outlast the peer waking up.
373 error._tag === "HttpClientError" ||
374 error._tag === "PeerSessionNotStarted" ||
375 error._tag === "PeerGatewayError" ||
376 (error._tag === "PeerLinkError" && error.reason === "unreachable")
377 ? Effect.void
378 : links.recordOutcome(input.environmentId, { error: error.message }),
379 ),
380 // A refusal is still an answer: the link works, so only this call fails.
381 Effect.tap(() => links.recordOutcome(input.environmentId, { error: null })),
382 Effect.catchTags({
383 PeerLinkError: (error) => Effect.fail(fromLinkError(error)),
384 PeerSessionNotStarted: () => Effect.fail(transportFailure.sessionNotStarted),
385 PeerGatewayError: (error) =>
386 Effect.fail(transportFailure.gateway(error.status, error.toolRequestSent)),
387 // Past the handshake, so the tool request left before the transport dropped.
388 HttpClientError: () => Effect.fail(transportFailure.replyLost),
389 }),
390 Effect.flatMap(Effect.fromResult),
391 ),
392 );
393​
394 return PeerMcpClient.of({ call });
395});
396​
397export const layer = Layer.effect(PeerMcpClient, make);