@devries-cameron20 / t3code Mirror · read-only / commits / ea957b5cab
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 16:00 UTC

fix(server): give MCP clients an absolute attachment upload URL (#35907)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Luca D'Orso committed Nov 14, 2026 at 00:54 UTC ea957b5cab373f584e5f0f960055b0a15eaacdce
5 files changed +120 -5
apps/server/src/mcp/McpHttpServer.test.ts
+104 -1
@@ -27,11 +27,13 @@ import * as Schema from "effect/Schema";
27 import * as Stream from "effect/Stream";
28 import * as Tracer from "effect/Tracer";
29 import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
30 -import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
30 +import { HttpBody, HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/http";
31 +import * as NetAddress from "effect/net/NetAddress";
32
33 import * as ProjectService from "../project/ProjectService.ts";
34 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
35 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
36 +import * as AssetSigner from "../assets/AssetSigner.ts";
37 import * as DocumentText from "../provider/DocumentText.ts";
38 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
39 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
@@ -1385,6 +1387,107 @@ it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected cr
1387 );
1388 });
1389
1390 +it.effect("gives outside clients an upload URL on the origin their request reached", () =>
1391 + Effect.scoped(
1392 + Effect.gen(function* () {
1393 + const token = "outsideClientToken";
1394 + const scope: McpInvocationContext.McpInvocationScope = {
1395 + environmentId,
1396 + requestNamespace: `client:${token}`,
1397 + thread: undefined,
1398 + client: { sessionId: token, label: "Hosted agent", access: "full-access" },
1399 + capabilities: new Set(["orchestration"]),
1400 + issuedAt: 1,
1401 + };
1402 + const serverLayer = McpHttpServer.layerMcpTransport(
1403 + McpHttpServer.layerAttachmentToolkit,
1404 + ).pipe(
1405 + Layer.provide(ServerSettings.layerTest()),
1406 + Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1407 + Layer.provide(
1408 + Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1409 + resolve: () => Effect.undefined,
1410 + }),
1411 + ),
1412 + // Signs in the way an OAuth client such as a hosted ChatGPT app does.
1413 + Layer.provide(
1414 + Layer.succeed(McpHttpServer.McpClientAuthenticator)({
1415 + authenticate: (request) =>
1416 + Effect.succeed(
1417 + request.headers.authorization === `Bearer ${token}` ? scope : undefined,
1418 + ),
1419 + }),
1420 + ),
1421 + Layer.provide(
1422 + AssetSigner.layer.pipe(
1423 + Layer.provideMerge(ServerSecretStore.layer),
1424 + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-upload-" })),
1425 + Layer.provideMerge(DocumentText.layer),
1426 + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1427 + ),
1428 + ),
1429 + );
1430 + yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1431 + Layer.build,
1432 + );
1433 + const httpClient = yield* HttpClient.HttpClient;
1434 + const prepareUpload = (proxyHeaders: Record<string, string>) =>
1435 + Effect.gen(function* () {
1436 + const headers = {
1437 + accept: "application/json, text/event-stream",
1438 + authorization: `Bearer ${token}`,
1439 + ...proxyHeaders,
1440 + };
1441 + const initialize = yield* httpClient.post("/mcp", {
1442 + headers,
1443 + body: HttpBody.text(
1444 + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1445 + "application/json",
1446 + ),
1447 + });
1448 + const response = yield* httpClient.post("/mcp", {
1449 + headers: {
1450 + ...headers,
1451 + "mcp-session-id": initialize.headers["mcp-session-id"]!,
1452 + "mcp-protocol-version": "2025-06-18",
1453 + },
1454 + body: HttpBody.text(
1455 + JSON.stringify({
1456 + jsonrpc: "2.0",
1457 + id: 2,
1458 + method: "tools/call",
1459 + params: {
1460 + name: "t3_attachment_prepare_upload",
1461 + arguments: {
1462 + upload: {
1463 + type: "image",
1464 + name: "shot.png",
1465 + mimeType: "image/png",
1466 + sizeBytes: 6,
1467 + },
1468 + },
1469 + },
1470 + }),
1471 + "application/json",
1472 + ),
1473 + });
1474 + const body = (yield* response.json) as {
1475 + result: { structuredContent: { uploadUrl: string } };
1476 + };
1477 + return body.result.structuredContent;
1478 + });
1479 +
1480 + const direct = yield* prepareUpload({});
1481 + const { address } = yield* HttpServer.HttpServer;
1482 + if (!NetAddress.isInetAddress(address)) throw new Error("Expected a TCP test server");
1483 + expect(new URL(direct.uploadUrl).origin).toBe(`http://127.0.0.1:${address.port}`);
1484 +
1485 + const proxied = yield* prepareUpload({ "x-forwarded-proto": "https" });
1486 + expect(new URL(proxied.uploadUrl).protocol).toBe("https:");
1487 + }),
1488 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1489 +);
1490 +
1491 it.effect("hides tools for links and refuses another environment while the beta is off", () =>
1492 Effect.scoped(
1493 Effect.gen(function* () {
apps/server/src/mcp/McpHttpServer.ts
+2 -1
@@ -274,7 +274,8 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
274 const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling);
275 const linkedEnvironments = yield* linksEnabled;
276 if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff;
277 - return { ...limited, linkedEnvironments };
277 + const origin = Option.getOrUndefined(Option.map(requestUrl(request), (url) => url.origin));
278 + return { ...limited, linkedEnvironments, origin };
279 });
280 // Untraced: a span here would wrap the tool call; the HTTP server span already covers it.
281 return Effect.fnUntraced(function* (httpEffect) {
apps/server/src/mcp/McpInvocationContext.ts
+5
@@ -141,6 +141,11 @@ export interface McpInvocationScope {
141 readonly client: McpClientCaller | undefined;
142 /** False while the Linked environments beta is off here; `/mcp` reads it per request. */
143 readonly linkedEnvironments?: boolean;
144 + /**
145 + * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot
146 + * see the URL they were configured with, so links they must fetch carry it. Unset in-process.
147 + */
148 + readonly origin?: string | undefined;
149 }
150
151 /**
apps/server/src/mcp/toolkits/attachment/handlers.ts
+4 -1
@@ -62,7 +62,10 @@ export const layer = McpToolAccess.toLayer(
62 if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
63 }
64 uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
65 - return result;
65 + const { origin } = yield* McpInvocationContext.McpInvocationContext;
66 + return origin === undefined
67 + ? result
68 + : { ...result, uploadUrl: `${origin}${result.relativeUrl}` };
69 }),
70 { linkedCallers: "allowed" },
71 ),
apps/server/src/mcp/toolkits/attachment/tools.ts
+5 -2
@@ -34,9 +34,12 @@ const shared = {
34 const AttachmentUploadTool = Tool.make("t3_attachment_prepare_upload", {
35 ...shared,
36 description:
37 - "Get an upload URL. POST the file's exact bytes to `relativeUrl` on this MCP server's HTTP origin, then send via `t3_thread_send_attachments` with the returned `attachmentId`.",
37 + "Get an upload URL. POST the file's exact bytes to `uploadUrl` (else this server's `relativeUrl`), then send via `t3_thread_send_attachments` with the returned `attachmentId`.",
38 parameters: Schema.Struct({ upload: AttachmentCreateUploadUrlInput }),
39 - success: AttachmentCreateUploadUrlResult,
39 + success: Schema.Struct({
40 + ...AttachmentCreateUploadUrlResult.fields,
41 + uploadUrl: Schema.optionalKey(Schema.String),
42 + }),
43 }).annotate(Tool.Destructive, true);
44 const AttachmentDiscardTool = Tool.make("t3_attachment_discard", {
45 ...shared,