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

PeerMcpClient.ts

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