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

PeerMcpClient.ts

253 lines9.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 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;
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/** The body of an MCP response: JSON, or a single server-sent event carrying JSON. */
80const responseJson = (contentType: string | undefined, text: string) =>
81 contentType?.includes("text/event-stream") === true
82 ? text
83 .split("\n")
84 .filter((line) => line.startsWith("data:"))
85 .map((line) => line.slice("data:".length).trim())
86 .join("")
87 : text;
88​
89const make = Effect.gen(function* () {
90 const links = yield* PeerLinks.PeerLinks;
91 const httpClient = yield* HttpClient.HttpClient;
92 // One MCP session per peer and address, reused across calls. The peer keeps
93 // sessions in memory, so a restart there answers 404 and we start a new one.
94 const sessions = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
95​
96 const post = (url: string, token: string, body: unknown, headers: Record<string, string>) =>
97 httpClient.execute(
98 HttpClientRequest.post(`${url}/mcp`).pipe(
99 HttpClientRequest.setHeaders({
100 accept: "application/json, text/event-stream",
101 authorization: `Bearer ${token}`,
102 ...headers,
103 }),
104 HttpClientRequest.setBody(HttpBody.text(JSON.stringify(body), "application/json")),
105 ),
106 );
107​
108 const openSession = Effect.fn("PeerMcpClient.openSession")(function* (
109 url: string,
110 token: string,
111 limitHeader: Record<string, string>,
112 ) {
113 const initialized = yield* post(
114 url,
115 token,
116 {
117 jsonrpc: "2.0",
118 id: 0,
119 method: "initialize",
120 params: {
121 protocolVersion: PROTOCOL_VERSION,
122 capabilities: {},
123 clientInfo: { name: "t3code-peer", version: "1" },
124 },
125 },
126 limitHeader,
127 );
128 const sessionId = initialized.headers["mcp-session-id"];
129 if (initialized.status !== 200 || sessionId === undefined) {
130 return yield* new OrchestratorMcpFailure({
131 code: initialized.status === 401 ? "capability_denied" : "orchestration_error",
132 message:
133 initialized.status === 401
134 ? "The linked environment no longer accepts this link. It may have been revoked there; link it again."
135 : `The linked environment refused to start an MCP session (HTTP ${initialized.status}).`,
136 });
137 }
138 yield* post(
139 url,
140 token,
141 { jsonrpc: "2.0", method: "notifications/initialized" },
142 { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION },
143 );
144 return sessionId;
145 });
146​
147 const call: PeerMcpClient["Service"]["call"] = Effect.fn("PeerMcpClient.call")(
148 function* (input) {
149 const resolved = yield* links
150 .resolve(input.environmentId)
151 .pipe(Effect.mapError(fromLinkError));
152 const limitHeader = {
153 [McpInvocationContext.MODE_LIMIT_HEADER]: `${input.limits.runtimeMode}/${input.limits.interactionMode}`,
154 };
155 const sessionKey = `${input.environmentId} ${resolved.url}`;
156 const callOnce = (sessionId: string) =>
157 post(
158 resolved.url,
159 resolved.token,
160 {
161 jsonrpc: "2.0",
162 id: 1,
163 method: "tools/call",
164 params: { name: input.tool, arguments: input.arguments },
165 },
166 { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION },
167 );
168 const existing = (yield* Ref.get(sessions)).get(sessionKey);
169 const sessionId = existing ?? (yield* openSession(resolved.url, resolved.token, limitHeader));
170 let response = yield* callOnce(sessionId);
171 if (response.status === 404) {
172 const renewed = yield* openSession(resolved.url, resolved.token, limitHeader);
173 yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, renewed));
174 response = yield* callOnce(renewed);
175 } else if (existing === undefined) {
176 yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, sessionId));
177 }
178 if (response.status === 401) {
179 return yield* new OrchestratorMcpFailure({
180 code: "capability_denied",
181 message:
182 "The linked environment no longer accepts this link. It may have been revoked there; link it again.",
183 });
184 }
185 if (response.status !== 200) {
186 return yield* new OrchestratorMcpFailure({
187 code: "orchestration_error",
188 message: `The linked environment answered HTTP ${response.status}.`,
189 });
190 }
191 const body = yield* decodeToolCallResponse(
192 responseJson(response.headers["content-type"], yield* response.text),
193 ).pipe(
194 Effect.mapError(
195 () =>
196 new OrchestratorMcpFailure({
197 code: "orchestration_error",
198 message: "The linked environment answered in an unexpected shape.",
199 }),
200 ),
201 );
202 if (body.error !== undefined || body.result === undefined) {
203 return yield* new OrchestratorMcpFailure({
204 code: "invalid_request",
205 message: body.error?.message ?? "The linked environment returned no result.",
206 });
207 }
208 const text = body.result.content.map((part) => part.text ?? "").join("");
209 if (body.result.isError === true) {
210 // A refusal keeps the peer's own code, so the agent sees why it was refused.
211 const refused = decodeFailure(text);
212 return yield* refused._tag === "Some"
213 ? new OrchestratorMcpFailure({ code: refused.value.code, message: refused.value.message })
214 : new OrchestratorMcpFailure({
215 code: "orchestration_error",
216 message: text || "The linked environment refused the call.",
217 });
218 }
219 const success = Schema.fromJsonString(input.success);
220 return yield* Schema.decodeEffect(success)(text).pipe(
221 Effect.mapError(
222 () =>
223 new OrchestratorMcpFailure({
224 code: "orchestration_error",
225 message:
226 "The linked environment's answer did not match this version. Update both environments.",
227 }),
228 ),
229 );
230 },
231 (effect, input) =>
232 effect.pipe(
233 Effect.tapError((error) =>
234 links.recordOutcome(input.environmentId, { error: error.message }),
235 ),
236 Effect.tap(() => links.recordOutcome(input.environmentId, { error: null })),
237 // Recorded above with the transport's own message; the agent hears it plainly.
238 Effect.catchTags({
239 HttpClientError: () =>
240 Effect.fail(
241 new OrchestratorMcpFailure({
242 code: "orchestration_error",
243 message: "The linked environment stopped answering.",
244 }),
245 ),
246 }),
247 ),
248 );
249​
250 return PeerMcpClient.of({ call });
251});
252​
253export const layer = Layer.effect(PeerMcpClient, make);