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

PeerMcpClient.ts

278 lines10.4 KB

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