Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions apps/server/src/mcp/bridge/T3ToolBridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,8 @@ it("publishes unique tools with reference-free object-root input schemas", () =>
"t3_thread_launch",
"link_pull_request",
"html_render",
"t3_attachment_prepare_upload",
"t3_thread_send_attachments",
]) {
assert.include(names, name);
}
Expand All @@ -285,12 +287,7 @@ it("publishes unique tools with reference-free object-root input schemas", () =>
T3ToolBridge.T3_TOOL_CATALOG.find((entry) => entry.name === name)?.readOnly;
assert.strictEqual(readOnly("read_pull_request_guide"), true);
assert.strictEqual(readOnly("write_pull_request_guides"), false);
for (const name of [
"preview_open",
"device_list",
"t3_attachment_prepare_upload",
"html_preview",
]) {
for (const name of ["preview_open", "device_list", "html_preview"]) {
assert.notInclude(names, name);
}
});
Expand Down
9 changes: 5 additions & 4 deletions apps/server/src/mcp/bridge/T3ToolBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import * as PullRequestsToolkitHandlers from "../toolkits/pullRequests/handlers.
import { PullRequestsToolkit } from "../toolkits/pullRequests/tools.ts";
import * as ThreadToolkitHandlers from "../toolkits/thread/handlers.ts";
import { ThreadToolkit } from "../toolkits/thread/tools.ts";
import * as AttachmentToolkitHandlers from "../toolkits/attachment/handlers.ts";
import { AttachmentToolkit } from "../toolkits/attachment/tools.ts";
import * as EnvironmentToolkitHandlers from "../toolkits/environment/handlers.ts";
import { EnvironmentToolkit } from "../toolkits/environment/tools.ts";
import * as ProjectToolkitHandlers from "../toolkits/project/handlers.ts";
Expand All @@ -47,13 +49,11 @@ import {
} from "./FileBridge.ts";
import { type T3ToolBinding, t3ToolFailure } from "./T3ToolDispatch.ts";

/**
* Upstream's toolkits the bridge carries. Preview, device, attachment uploads, and `html_preview`
* stay out.
*/
/** Upstream's toolkits the bridge carries. Preview, device, and `html_preview` stay out. */
const BridgedToolkit = Toolkit.merge(
OrchestratorToolkit,
ThreadToolkit,
AttachmentToolkit,
ProjectToolkit,
EnvironmentToolkit,
WorktreeToolkit,
Expand All @@ -68,6 +68,7 @@ const BridgedHandlersLive = Layer.mergeAll(
Layer.provide(ThreadMetadataMcpService.layer),
),
McpToolAccess.HandlersLayer.layer(ThreadToolkitHandlers.layer),
McpToolAccess.HandlersLayer.layer(AttachmentToolkitHandlers.layer),
McpToolAccess.HandlersLayer.layer(ProjectToolkitHandlers.layer),
McpToolAccess.HandlersLayer.layer(EnvironmentToolkitHandlers.layer),
McpToolAccess.HandlersLayer.layer(WorktreeToolkitHandlers.layer).pipe(
Expand Down
153 changes: 153 additions & 0 deletions apps/server/src/mcp/toolkits/attachment/handlers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Coder: upstream's attachment cases from `toolkits/core.test.ts`, which runs them through its MCP
// server; here they call the toolkit as the file bridge does.
// @effect-diagnostics nodeBuiltinImport:off -- the test writes the workspace file an agent uploads.
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";

import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import {
ChatImageAttachment,
EnvironmentId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";

import * as ServerSecretStore from "../../../auth/ServerSecretStore.ts";
import * as ServerConfig from "../../../config.ts";
import * as DocumentText from "../../../provider/DocumentText.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
import * as AttachmentHandlers from "./handlers.ts";
import { McpAttachmentInput } from "./input.ts";
import { AttachmentToolkit } from "./tools.ts";

const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput);

const threadId = ThreadId.make("mcp-core-thread");
const scope: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("mcp-core-environment"),
requestNamespace: "mcp-core-session",
thread: {
threadId,
providerSessionId: "mcp-core-session",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
issuedAt: 0,
capabilities: new Set(["orchestration"]),
};

it.effect("resolves reused attachment references from stored metadata", () =>
Effect.gen(function* () {
const stored = ChatImageAttachment.make({
type: "image",
id: "owned-image",
name: "original.png",
mimeType: "image/png",
sizeBytes: 12,
source: {
kind: "snap-shot",
capturedAt: "2026-09-10T00:00:00.000Z",
appName: "Terminal",
windowTitle: "Test",
accessibility: { format: "flat-text", text: "Stored context", truncated: false },
},
});
const forged = yield* decodeMcpAttachmentInput({
type: "image",
id: stored.id,
name: "changed.jpg",
mimeType: "image/jpeg",
sizeBytes: 99,
});
const result = yield* AttachmentHandlers.resolveAttachmentReferences([forged], [stored]);
expect(result).toEqual([stored]);
const failure = yield* AttachmentHandlers.resolveAttachmentReferences(
[{ ...forged, id: "other-image" }],
[stored],
).pipe(Effect.flip);
expect(failure.code).toBe("invalid_request");
}),
);

it.effect("only the caller that prepared a pending upload can discard it", () =>
Effect.gen(function* () {
const toolkit = yield* AttachmentToolkit.pipe(
Effect.provide(McpToolAccess.HandlersLayer.layer(AttachmentHandlers.layer)),
);
const call = (
name: keyof typeof AttachmentToolkit.tools,
args: Record<string, unknown>,
invocation: McpInvocationContext.McpInvocationScope,
) =>
toolkit
.handle(name, args as never)
.pipe(
Effect.flatMap(Stream.runLast),
Effect.map(Option.getOrThrow),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
);
// Coder: the upload names a workspace file instead of a URL the caller POSTs to.
const directory = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mcp-attachment-file-")),
);
yield* Effect.addFinalizer(() =>
Effect.promise(() => NodeFSP.rm(directory, { recursive: true, force: true })),
);
const path = NodePath.join(directory, "shot.png");
yield* Effect.promise(() => NodeFSP.writeFile(path, Uint8Array.of(1, 2, 3, 4)));

const prepared = yield* call(
"t3_attachment_prepare_upload",
{ upload: { name: "shot.png", mimeType: "image/png", sizeBytes: 4 }, path },
scope,
);
expect(prepared.isFailure).toBe(false);
const { attachmentId } = prepared.encodedResult as { readonly attachmentId: string };
const config = yield* ServerConfig.ServerConfig;
const staged = yield* Effect.promise(() =>
NodeFSP.readFile(NodePath.join(config.attachmentsDir, `${attachmentId}.png`)),
);
expect([...staged]).toEqual([1, 2, 3, 4]);
const otherThread = {
...scope,
requestNamespace: "other-session",
thread: { ...scope.thread!, threadId: ThreadId.make("other-thread") },
};

const refused = yield* call("t3_attachment_discard", { attachmentId }, otherThread);
expect(refused.isFailure).toBe(true);
expect(refused.encodedResult).toMatchObject({ code: "invalid_request" });

yield* TestClock.adjust(24 * 60 * 60 * 1000 + 5 * 60_000);
yield* call(
"t3_attachment_prepare_upload",
{ upload: { name: "later.png", mimeType: "image/png", sizeBytes: 4 }, path },
scope,
);

const discarded = yield* call(
"t3_attachment_discard",
{ attachmentId },
{ ...scope, requestNamespace: "mcp-core-session-2" },
);
expect(discarded.isFailure).toBe(false);
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(McpToolAccessTestkit.liveThreadsLayer, ServerSecretStore.layer).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-attachment-" })),
Layer.provideMerge(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
),
),
),
);
186 changes: 186 additions & 0 deletions apps/server/src/mcp/toolkits/attachment/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import {
ATTACHMENT_UPLOAD_URL_TTL_MS,
type ChatAttachment,
MessageId,
OrchestratorMcpFailure,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as Upload from "../../../assets/AttachmentUpload.ts";
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import { newCommandId, readThread, unavailable } from "../../threadAccess.ts";
import { AttachmentToolkit } from "./tools.ts";

export function resolveAttachmentReferences(
requested: ReadonlyArray<ChatAttachment>,
stored: ReadonlyArray<ChatAttachment>,
) {
const owned = new Map(stored.map((attachment) => [attachment.id, attachment]));
return Effect.forEach(requested, (attachment) => {
const canonical = Claims.attachmentIsPendingUpload(attachment)
? attachment
: owned.get(attachment.id);
return canonical === undefined
? Effect.fail(
new OrchestratorMcpFailure({
code: "invalid_request",
message: "Attachments must be pending uploads or already belong to the target thread.",
}),
)
: Effect.succeed(canonical);
});
}

const invalidUpload = (message: string) =>
new OrchestratorMcpFailure({ code: "invalid_request", message });

/**
* Coder: stores the file at `filePath` as the pending upload `relativeUrl` names, as upstream's
* upload route stores a POSTed body. The agent shares the workspace filesystem, so bytes never
* pass through the bridge's bounded request files.
*/
const storeWorkspaceFile = Effect.fn("AttachmentHandlers.storeWorkspaceFile")(function* (
relativeUrl: string,
filePath: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
if (!(yield* Path.Path).isAbsolute(filePath)) {
return yield* invalidUpload("`path` must be an absolute workspace path.");
}
const info = yield* fileSystem
.stat(filePath)
.pipe(Effect.mapError(() => invalidUpload(`No readable file at ${filePath}.`)));
if (info.type !== "File") {
return yield* invalidUpload(`${filePath} is not a regular file.`);
}
const claims = yield* Upload.validateAttachmentUploadToken(
relativeUrl.slice(`${Upload.ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length),
);
if (claims === null) return yield* unavailable();
if (Number(info.size) !== claims.sizeBytes) {
return yield* invalidUpload(
`${filePath} is ${Number(info.size)} bytes, but upload.sizeBytes is ${claims.sizeBytes}.`,
);
}
// A read error ends the body early, which the store reports as a size mismatch.
const stored = yield* Upload.storeAttachmentUpload(
claims,
fileSystem
.stream(filePath, { bytesToRead: claims.sizeBytes })
.pipe(Stream.catch(() => Stream.empty)),
);
if (!stored.ok) {
return yield* new OrchestratorMcpFailure({
code: "orchestration_error",
message: stored.detail,
});
}
});

/** The 24-hour sweep starts at upload completion, possibly one upload-URL lifetime after issue. */
const UPLOAD_OWNER_TTL_MS = 24 * 60 * 60 * 1000 + ATTACHMENT_UPLOAD_URL_TTL_MS;

const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(
Effect.map((scope) => scope.thread?.threadId ?? scope.requestNamespace),
);

export const layer = McpToolAccess.toLayer(
AttachmentToolkit,
Effect.sync(() => {
const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();
return {
// A pending upload belongs to its caller until a send claims it, so
// linked callers may stage the uploads their own sends need.
t3_attachment_prepare_upload: McpToolAccess.writes(
(input) =>
Effect.gen(function* () {
// Coder: a call another workspace forwards names a file in that workspace, not here.
if ((yield* McpInvocationContext.McpInvocationContext).client?.linked === true) {
return yield* invalidUpload(
"Attachments cannot be uploaded from a linked workspace. Upload and send them from a thread in this workspace.",
);
}
const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
Effect.mapError(unavailable),
);
// Coder: stage the workspace file through the upload route's own validation and store.
yield* storeWorkspaceFile(result.relativeUrl, input.path);
const now = yield* Clock.currentTimeMillis;
for (const [id, entry] of uploadOwners) {
if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
}
uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
// Coder: the upload is already stored, so no URL goes back.
return { attachmentId: result.attachmentId };
}),
{ linkedCallers: "allowed" },
),
t3_attachment_discard: McpToolAccess.writes(
(input) =>
Effect.gen(function* () {
if (uploadOwners.get(input.attachmentId)?.owner !== (yield* uploadOwner)) {
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "Only the caller that prepared a pending upload can discard it.",
});
}
yield* Upload.deletePendingAttachment(input.attachmentId);
uploadOwners.delete(input.attachmentId);
return {};
}),
{ linkedCallers: "allowed" },
),
t3_thread_send_attachments: McpToolAccess.writesThreads(
(input) => [input.threadId],
(input) =>
Effect.gen(function* () {
const { caller, projection } = yield* readThread(input.threadId, ["messages"]);
if (projection.thread.archivedAt !== null)
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "Unarchive the target thread before sending attachments.",
});
const attachments = yield* resolveAttachmentReferences(
input.attachments,
projection.messages.flatMap((message) => message.attachments),
);
const commandId = yield* newCommandId();
const messageId = MessageId.make(commandId);
const result = yield* ThreadMessageIntake.sendToThread({
projectId: projection.thread.projectId,
threadId: projection.thread.id,
commandId,
messageId,
...(caller === undefined ? {} : { senderThreadId: caller.id }),
text: input.message ?? "",
attachments,
mode: "auto",
createdBy: "agent",
creationSource: "mcp",
}).pipe(
Effect.mapError((error) =>
error._tag === "AttachmentClaimError"
? new OrchestratorMcpFailure({
code: "orchestration_error",
message: error.message,
})
: unavailable(),
),
);
return {
threadId: projection.thread.id,
messageId,
runId: result.run.id,
status: result.run.status,
};
}),
),
};
}),
);
Loading