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