feat(mcp): support thread attachments #8700
Closedjuliusmarmingewants to merge 13 commits into
t3code/codex-turn-mapping fromagents/mcp-queue-inputs/attachmentsopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/Orchestrator.ts line 7196Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6983,3 +6986,4 @@69836986 return {69846987 sequence: committed.receipt.resultSequence,69856988 storedEvents: committed.storedEvents,6989+ replayed: !committed.committed,apps/server/src/mcp/OrchestratorMcpService.ts line 1503OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1409,20 +1503 @@1409- requestKey: key,1410- operation: "dispatch-thread",1411- index,1412- }),1413- threadId,1414- messageId: stableMessageId({1415- scope,1416- requestKey: key,1417- index,1418- }),1419- text: request.prompt,1420- attachments: [],1421- modelSelection: target.modelSelection,1422- dispatchMode: { type: "start_immediately" },1423- })1424- .pipe(1425- Effect.mapError((error) =>1426- failure(1427- "orchestration_error",1428- `Unable to start thread ${index + 1}: ${errorMessage(error)}`,1503+ yield* validateAttachmentOwnership(null, requestedAttachments);apps/server/src/mcp/AttachmentMcpService.ts lines 107 to 107OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +87,21 @@87+ }88+ : {89+ type: "image" as const,90+ name: input.name,91+ mimeType:92+ input.mimeType as (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number],93+ sizeBytes: input.sizeBytes,94+ };95+ const issued = yield* issueUpload(uploadInput).pipe(96+ Effect.mapError(() =>97+ failure("upload_error", "Unable to prepare a signed attachment upload."),98+ ),99+ );100+ return {101+ attachmentId: issued.attachmentId,102+ type: input.type ?? "image",103+ name: input.name,104+ mimeType: input.mimeType,105+ sizeBytes: input.sizeBytes,106+ upload: {107+ method: "PUT",apps/server/src/mcp/OrchestratorMcpService.ts lines 195 to 195OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -160,0 +175,21 @@175+ case "cursor":176+ case "grok":177+ return ["image"];178+ case "opencode":179+ return ["image", "file"];180+ default:181+ return [];182+ }183+}184+185+function validateProviderAttachments(186+ provider: ServerProvider,187+ attachments: ReadonlyArray<ChatAttachment>,188+): Effect.Effect<void, OrchestratorMcpFailure> {189+ if (attachments.length === 0) return Effect.void;190+ const kinds = providerAttachmentKinds(provider);191+ const unsupported = attachments.find(192+ (attachment) =>193+ (attachment.type !== "image" && attachment.type !== "file") ||194+ !kinds.includes(attachment.type) ||195+ (provider.driver === "opencode" && !isOpenCodeNativeFilePart(attachment)),
- apps/server/src/mcp/OrchestratorMcpService.ts line 1703Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1419,10 +1503,11 @@1419- text: request.prompt,1420- attachments: [],1421- modelSelection: target.modelSelection,1422- dispatchMode: { type: "start_immediately" },1423- })1424- .pipe(1425- Effect.mapError((error) =>1426- failure(1427- "orchestration_error",1428- `Unable to start thread ${index + 1}: ${errorMessage(error)}`,1503+ yield* validateAttachmentOwnership(null, requestedAttachments);1504+ const initialMessageId = stableMessageId({1505+ scope,1506+ requestKey: key,1507+ index,1508+ });1509+ yield* Effect.gen(function* () {1510+ const claimed = yield* claimAttachments({1511+ threadId,1512+ attachments: requestedAttachments,1513+ }).pipe(Effect.mapError((error) => failure("invalid_request", error.message)));
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/Orchestrator.ts lines 3081 to 3082OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +3017,21 @@3017+ nodeId: sourcePlan.nodeId,3018+ occurredAt,3019+ payload: { ...sourcePlan, status: "completed" },3020+ });3021+3022+ if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {3023+ yield* dispatchSteerIntoRun({3024+ command,3025+ events,3026+ effects,3027+ projection,3028+ modelSelection,3029+ targetRunId: dispatchMode.targetRunId,3030+ messageId: command.messageId,3031+ text: dispatchText,3032+ attachments: command.attachments,3033+ createdBy: command.createdBy,3034+ creationSource: command.creationSource,3035+ forceRestart: dispatchMode.type === "restart_active",3036+ });3037+ return;@@ -0,0 +178,21 @@178+ return ["image"];179+ case "opencode":180+ return ["image", "file"];181+ default:182+ return [];183+ }184+}185+186+function validateProviderAttachments(187+ provider: ServerProvider,188+ attachments: ReadonlyArray<ChatAttachment>,189+): Effect.Effect<void, OrchestratorMcpFailure> {190+ if (attachments.length === 0) return Effect.void;191+ const kinds = providerAttachmentKinds(provider);192+ const unsupported = attachments.find(193+ (attachment) =>194+ (attachment.type !== "image" && attachment.type !== "file") ||195+ !kinds.includes(attachment.type) ||196+ (attachment.type === "image" &&197+ !isProviderSendTurnSupportedImageMimeType(attachment.mimeType)) ||198+ (provider.driver === "opencode" && !isOpenCodeNativeFilePart(attachment)),
- apps/server/src/mcp/OrchestratorMcpService.ts line 1858OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1838,21 @@1838+1839+ const mode = input.mode ?? "auto";1840+ const key = yield* requestKey(input.clientRequestId);1841+ const messageId = stableOperationMessageId({1842+ scope,1843+ requestKey: key,1844+ operation: "thread-send",1845+ });1846+ const commandId = stableCommandId({1847+ scope,1848+ requestKey: key,1849+ operation: "thread-send",1850+ });1851+ if (1852+ yield* acceptedReceipt({1853+ commandId,1854+ threadId: input.threadId,1855+ commandType: "message.dispatch",1856+ })1857+ ) {1858+ const accepted = yield* acceptedMessageResult(target, messageId, mode);
- @@ -1647,14 +1630,5 @@16471630 const openPreview = useAtomCommand(previewEnvironment.open, {16481631 reportFailure: false,16491632 });1650- const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {1651- reportFailure: false,1652- });1653- const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;1654- const remoteOpen = useRemoteOpenResolution(environmentId);1655- const canUseShellActions = canUseMarkdownFileShellActions(1656- environmentId,1657- remoteOpen.state.mode,1658- remoteOpen.isResolved,1659- );1660- const preparedConnection = usePreparedConnection(environmentId);1633+ const preparedConnection = usePreparedConnection(threadRef?.environmentId ?? null);1634+ const environmentId = useActiveEnvironmentId();apps/web/src/components/pullRequest/PullRequestMarkdown.tsx lines 36 to 36OutdatedResolvedby juliusmarminge@@ -33,11 +33,4 @@3333 <div className={cn("space-y-3", className)}>3434 {segments.map((segment) => {3535 if (segment.kind === "markdown") {36- return (37- <ChatMarkdown38- key={segment.id}39- text={segment.text}40- cwd={cwd}41- environmentId={environmentId}42- />43- );36+ return <ChatMarkdown key={segment.id} text={segment.text} cwd={cwd} />;
- apps/server/src/mcp/AttachmentMcpService.ts lines 57 to 57OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +37,21 @@37+ scope: McpInvocationScope,38+ input: AttachmentMcpDiscardUploadInput,39+ ) => Effect.Effect<AttachmentMcpDiscardUploadResult, AttachmentMcpFailure>;40+ }41+>()("t3/mcp/AttachmentMcpService") {}42+43+function failure(code: AttachmentMcpFailure["code"], message: string): AttachmentMcpFailure {44+ return new AttachmentMcpFailure({ code, message });45+}46+47+const requireCapability = (scope: McpInvocationScope) =>48+ scope.capabilities.has("orchestration")49+ ? Effect.void50+ : Effect.fail(51+ failure(52+ "capability_denied",53+ "This MCP credential does not grant orchestration capabilities.",54+ ),55+ );56+57+const make = Effect.gen(function* () {
- apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts lines 1849 to 1851OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1739,21 @@1739+ runtimeRequestId: pending.requestId,1740+ checkpointScopeId: null,1741+ startedAt: pending.createdAt,1742+ completedAt: now,1743+ },1744+ });1745+ yield* emitProviderEvent({1746+ type: "turn_item.updated",1747+ driver: OPENCODE_PROVIDER,1748+ turnItem: runtimeRequestTurnItem(1749+ pending,1750+ status === "resolved" ? "completed" : "cancelled",1751+ now,1752+ now,1753+ ),1754+ });1755+ pendingRequests.delete(String(pending.requestId));1756+ pendingRequestsByNativeId.delete(nativeRequestId);1757+ const hasOtherPending = Array.from(pendingRequests.values()).some(1758+ (candidate) => candidate.turn.isRoot,1759+ );apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts line 1952OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1840,21 @@1840+ readonly failure?: OrchestrationV2ProviderFailure;1841+ readonly threadDisposition?: "reusable" | "broken";1842+ },1843+ ) {1844+ if (turn.finalized) return;1845+ turn.finalized = true;1846+ const completedAt = yield* DateTime.now;1847+ for (const part of turn.parts.values()) {1848+ if (part.type === "text" || part.type === "reasoning") {1849+ yield* emitTextPart(state, turn, part, true);1850+ }1851+ }1852+ for (const pending of Array.from(pendingRequests.values())) {1853+ if (pending.turn.providerTurnId === turn.providerTurnId) {1854+ yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled");1855+ }1856+ }1857+ yield* emitProviderTurn(state, turn, status, completedAt);1858+ const threadDisposition = terminal?.threadDisposition ?? "reusable";1859+ yield* updateProviderThread(state, {1860+ status: turn.isRoot ? "active" : threadDisposition === "broken" ? "error" : "idle",apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts line 1917OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1805,21 @@1805+ request:1806+ | { readonly type: "permission"; readonly value: PermissionRequest }1807+ | { readonly type: "question"; readonly value: QuestionRequest },1808+ ) {1809+ if (pendingChildRequestRoutes.has(nativeRequestId)) return;1810+ const attempt = Effect.gen(function* () {1811+ if (1812+ settledNativeRequestIds.has(nativeRequestId) ||1813+ pendingRequestsByNativeId.has(nativeRequestId)1814+ ) {1815+ return true;1816+ }1817+ const owner = yield* resolveSessionOwner(sessionId);1818+ if (owner?.activeTurn == null) return false;1819+ yield* emitRuntimeRequest(owner, owner.activeTurn, nativeRequestId, request);1820+ return true;1821+ });1822+ if (yield* attempt) return;1823+ pendingChildRequestRoutes.add(nativeRequestId);1824+ yield* Effect.gen(function* () {1825+ for (let retry = 0; retry < 5; retry += 1) {
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/contracts/src/attachmentMcp.ts lines 25 to 25OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+ ChatAttachmentId,6+ PROVIDER_SEND_TURN_MAX_FILE_BYTES,7+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,8+ PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,9+} from "./chatAttachment.ts";10+import { IsoDateTime, NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";11+12+export const AttachmentMcpPrepareUploadInput = Schema.Struct({13+ type: Schema.optional(Schema.Literals(["image", "file"])),14+ name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),15+ mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),16+ sizeBytes: NonNegativeInt.check(17+ Schema.isGreaterThanOrEqualTo(1),18+ Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_FILE_BYTES),19+ ),20+}).check(21+ Schema.makeFilter((input) => {22+ if (input.type === "file") return true;23+ if (24+ !PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.includes(25+ input.mimeType as (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number],
- apps/server/src/mcp/OrchestratorMcpAttachments.test.ts line 30OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+ ProjectId,11+ ProviderInstanceId,12+ type ServerProvider,13+ ThreadId,14+ type OrchestrationV2ThreadProjection,15+} from "@t3tools/contracts";16+import * as Effect from "effect/Effect";17+import * as Layer from "effect/Layer";18+import * as Option from "effect/Option";19+import * as Ref from "effect/Ref";20+21+import { createPendingAttachmentId } from "../attachmentStore.ts";22+import * as ServerConfig from "../config.ts";23+import {24+ ThreadManagementPostDispatchProjectionError,25+ ThreadManagementService,26+} from "../orchestration-v2/ThreadManagementService.ts";27+import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";28+import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";29+import type { McpInvocationScope } from "./McpInvocationContext.ts";30+import { layer, OrchestratorMcpService } from "./OrchestratorMcpService.ts";
- apps/server/src/orchestration-v2/Orchestrator.ts lines 181 to 181OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -169,10 +169,13 @@169169 export interface OrchestratorV2DispatchResult {170170 readonly sequence: number;171171 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;172+ /** True when this call returned an already-accepted command receipt. */173+ readonly replayed?: boolean;172174 }173175174176 export interface OrchestratorV2Shape {175177 readonly resumeQueuedRuns: Effect.Effect<number, OrchestratorV2Error>;176178 readonly dispatch: (177179 command: OrchestrationV2Command,178180 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;181+ readonly getCommandReceipt: CommandReceiptStoreV2Shape["getByCommandId"];
- @@ -0,0 +121,21 @@121+ discardUpload: (scope, input) =>122+ Effect.gen(function* () {123+ yield* requireCapability(scope);124+ if (125+ parseThreadSegmentFromAttachmentId(input.attachmentId) !==126+ PENDING_ATTACHMENT_THREAD_SEGMENT127+ ) {128+ return yield* failure(129+ "invalid_attachment",130+ "Only a pending upload can be discarded; thread-owned attachments are immutable here.",131+ );132+ }133+ const token = input.uploadRelativeUrl.split("/").at(-1) ?? "";134+ const claims = yield* validateUploadToken(token);135+ if (claims?.attachmentId !== input.attachmentId) {136+ return yield* failure(137+ "invalid_attachment",138+ "The signed upload URL does not authorize this pending attachment id.",139+ );140+ }141+ yield* discardPending(input.attachmentId);
- apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts line 33OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -28,4 +28,6 @@2828 layer as effectWorkerLayer,2929 runDaemon as runEffectWorkerDaemon,3030 } from "../EffectWorker.ts";31-import { layerFromStores as eventSinkLayer } from "../EventSink.ts";31+import {32+ EventSinkV2,33+ type EventSinkV2Shape,
- @@ -159,3 +169,17 @@159169 return new OrchestratorMcpFailure({ code, message });160170 }161171172+function providerAttachmentKinds(provider: ServerProvider): ReadonlyArray<"image" | "file"> {173+ switch (provider.driver) {174+ case "codex":175+ case "claudeAgent":176+ case "cursor":177+ case "grok":178+ case "antigravity":179+ return ["image"];180+ case "opencode":181+ return ["image", "file"];182+ default:183+ return [];184+ }185+}
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
7c62e49a-4968-46bc-a1ba-91b5d2c332f8You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Warning
Your free Security trial is over. An organization admin can activate Security or dismiss this notice.
Comment `@coderabbitai help` to get the list of available commands.