diff --git a/apps/server/src/mcp/bridge/T3ToolBridge.test.ts b/apps/server/src/mcp/bridge/T3ToolBridge.test.ts index f6c9a7dee214..76be8acd522f 100644 --- a/apps/server/src/mcp/bridge/T3ToolBridge.test.ts +++ b/apps/server/src/mcp/bridge/T3ToolBridge.test.ts @@ -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); } @@ -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); } }); diff --git a/apps/server/src/mcp/bridge/T3ToolBridge.ts b/apps/server/src/mcp/bridge/T3ToolBridge.ts index 5b527b78c1e8..e045fa716dbd 100644 --- a/apps/server/src/mcp/bridge/T3ToolBridge.ts +++ b/apps/server/src/mcp/bridge/T3ToolBridge.ts @@ -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"; @@ -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, @@ -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( diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.test.ts b/apps/server/src/mcp/toolkits/attachment/handlers.test.ts new file mode 100644 index 000000000000..6db7d3a7f0c6 --- /dev/null +++ b/apps/server/src/mcp/toolkits/attachment/handlers.test.ts @@ -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, + 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))), + ), + ), + ), +); diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.ts new file mode 100644 index 000000000000..f7b2a00886e3 --- /dev/null +++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts @@ -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, + stored: ReadonlyArray, +) { + 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(); + 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, + }; + }), + ), + }; + }), +); diff --git a/apps/server/src/mcp/toolkits/attachment/tools.ts b/apps/server/src/mcp/toolkits/attachment/tools.ts new file mode 100644 index 000000000000..63038a6f71ee --- /dev/null +++ b/apps/server/src/mcp/toolkits/attachment/tools.ts @@ -0,0 +1,82 @@ +import { McpAttachmentInput } from "./input.ts"; +import { + AttachmentCreateUploadUrlInput, + AttachmentCreateUploadUrlResult, + AttachmentDeleteInput, + MessageId, + RunId, + ThreadId, + OrchestrationV2RunStatus, + OrchestratorMcpFailure, + TrimmedNonEmptyString, +} from "@t3tools/contracts"; +import * as Crypto from "effect/Crypto"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Struct from "effect/Struct"; +import { Tool, Toolkit } from "effect/ai"; +import * as ServerSecretStore from "../../../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../../../config.ts"; +import * as DocumentText from "../../../provider/DocumentText.ts"; +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +const shared = { + failure: OrchestratorMcpFailure, + failureMode: "return" as const, + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ServerConfig.ServerConfig, + ServerSecretStore.ServerSecretStore, + FileSystem.FileSystem, + Crypto.Crypto, + ], +}; +// Coder: no MCP HTTP origin to POST to, so the upload names a workspace file the helper stages in +// process; it needs storage's services and returns no URL. +const AttachmentUploadTool = Tool.make("t3_attachment_prepare_upload", { + ...shared, + dependencies: [...shared.dependencies, Path.Path, DocumentText.DocumentText], + description: + "Upload a workspace file: `path` is its absolute path and `upload.sizeBytes` its exact size. Then send via `t3_thread_send_attachments` with the returned `attachmentId`.", + parameters: Schema.Struct({ + upload: AttachmentCreateUploadUrlInput, + path: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)), + }), + success: AttachmentCreateUploadUrlResult.mapFields(Struct.pick(["attachmentId"])), +}).annotate(Tool.Destructive, true); +const AttachmentDiscardTool = Tool.make("t3_attachment_discard", { + ...shared, + description: "Discard a pending upload (not a sent attachment).", + parameters: AttachmentDeleteInput, + success: Schema.Struct({}), +}).annotate(Tool.Destructive, true); +const AttachmentSendTool = Tool.make("t3_thread_send_attachments", { + ...shared, + dependencies: [...shared.dependencies, DocumentText.DocumentText], + description: + "Send uploaded attachments as a new message to a thread. No retry key. Target modes cannot exceed yours. Success does not mean the provider read them or finished.", + parameters: Schema.Struct({ + threadId: Schema.optional(ThreadId), + message: Schema.optional(Schema.String.check(Schema.isMaxLength(120000))), + attachments: Schema.Array(McpAttachmentInput).check( + Schema.isMinLength(1), + Schema.isMaxLength(8), + ), + }), + success: Schema.Struct({ + threadId: ThreadId, + messageId: MessageId, + runId: RunId, + status: OrchestrationV2RunStatus, + }), +}) + .annotate(Tool.Destructive, true) + .annotate(Tool.OpenWorld, true); +export const AttachmentToolkit = Toolkit.make( + AttachmentUploadTool, + AttachmentDiscardTool, + AttachmentSendTool, +); diff --git a/docs/internals/coder-only.md b/docs/internals/coder-only.md index e190b46b95f8..2bc0d019048f 100644 --- a/docs/internals/coder-only.md +++ b/docs/internals/coder-only.md @@ -122,11 +122,16 @@ removed once it is older than `STALE_CALL_MS`. If a bridge cannot be created, turns run without T3 tools. Workspace processes run as the same OS user; these directories are not an isolation boundary between mutually untrusted agents. -The bridge carries upstream's orchestrator, thread, project, environment, worktree, pull-request, -and `html_render` toolkits. The pull-request tools accept only merge requests on a GitLab host that a -workspace project uses; project clones go through the same GitLab-only repository service as the -browser. Preview, device, attachment-upload, and `html_preview` toolkits are not carried, and -neither is upstream's MCP HTTP server. +The bridge carries upstream's orchestrator, thread, attachment, project, environment, worktree, +pull-request, and `html_render` toolkits. The pull-request tools accept only merge requests on a +GitLab host that a workspace project uses; project clones go through the same GitLab-only repository +service as the browser. With no HTTP origin to upload to, `t3_attachment_prepare_upload` takes the +absolute workspace path of a file the agent already has and stores it as a pending upload in +process, so attachment bytes never pass through the bridge's request files. Attachments reach only +threads in the caller's own workspace: the attachment tools take no `environmentId`, as upstream's, +so a thread in a linked workspace answers `thread_not_found`, and an upload forwarded through the +gateway hub is refused because its path would name a file in the other workspace. Preview, device, +and `html_preview` toolkits are not carried, and neither is upstream's MCP HTTP server. Thread settlement is workspace-owned. The helper's settlement reactor checks persisted workspace settings at startup, after relevant settings changes, and once per minute, including while no @@ -615,6 +620,13 @@ checks that every name here still exists and that every modified upstream file i - No `lastErrorCode`: the server's `threadErrorSummary`, `ProjectionStore.ts`'s shell state, client-runtime's `ThreadRuntimeSummary` and `state/models.ts` drop it (the contract field stays). - `mcp/toolkits/orchestrator/handlers.ts` has no `t3_environment_link` or `t3_environment_unlink`. +- `mcp/toolkits/attachment/tools.ts`: `t3_attachment_prepare_upload` takes a `path` beside + `upload`, needs storage's services, returns only `attachmentId`, and its description names the + path instead of a URL to POST to. `handlers.ts` stores the file through upstream's + `validateAttachmentUploadToken` and `storeAttachmentUpload` (`storeWorkspaceFile`) after checking + it is an absolute path to a regular file of exactly `upload.sizeBytes`, and refuses a call the + gateway hub forwards (`client.linked`). Upstream's `core.test.ts` attachment cases run in + `attachment/handlers.test.ts`. - `persistence/Errors.ts` has no pairing-link correlation or auth repository errors. ### HTML renders diff --git a/docs/user/providers.md b/docs/user/providers.md index 4a4f2c0239cb..18ea493a3ab0 100644 --- a/docs/user/providers.md +++ b/docs/user/providers.md @@ -85,10 +85,11 @@ an approval request. The Claude browser integration is disabled. Codex, Claude, Pi, and Kilo Code can still use T3 Coder's own tools: delegating work to child agents, reading and messaging other threads, managing the queue and pending questions, scheduling recurring tasks, -launching threads in worktrees, managing projects, and linking merge requests. Instead of an MCP +launching threads in worktrees, managing projects, linking merge requests, and sending workspace +files and images to other threads in the same workspace. Instead of an MCP server, T3 gives each provider session a workspace command that runs these tools and removes it when the session stops. In plan mode, agents can use only the tools that read state. Browser -preview, device, and attachment-upload tools are not available. +preview and device tools are not available. ## Provider settings