-
Notifications
You must be signed in to change notification settings - Fork 6.3k
feat(mcp): support thread attachments #8700
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
juliusmarminge
wants to merge
13
commits into
t3code/codex-turn-mapping
from
agents/mcp-queue-inputs/attachments
Closed
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
cb54c3b
feat(mcp): support thread attachments
juliusmarminge 2342d30
fix(mcp): harden attachment retries
juliusmarminge 181502a
fix(mcp): reload accepted send results
juliusmarminge 0d93b71
fix(mcp): preserve OpenCode file attachments
juliusmarminge 90c3110
refactor(mcp): export attachment service constructor
juliusmarminge 4fdfbd9
fix(server): report replayed launch messages
juliusmarminge 172d4f7
fix(mcp): preserve launched run identity
juliusmarminge 72c4752
fix(mcp): preserve OpenCode attachment path cues
juliusmarminge 7de6d64
test(mcp): preserve service module namespace
juliusmarminge b72f861
fix(mcp): accept case-insensitive image MIME types
juliusmarminge c032339
fix(server): align receipt service typing
juliusmarminge aa49a21
test(server): use inferred event sink service type
juliusmarminge 6991ca7
fix(mcp): support Antigravity image attachments
juliusmarminge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| import { | ||
| AttachmentMcpFailure, | ||
| IsoDateTime, | ||
| PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES, | ||
| type AttachmentMcpDiscardUploadInput, | ||
| type AttachmentMcpDiscardUploadResult, | ||
| type AttachmentMcpPrepareUploadInput, | ||
| type AttachmentMcpPrepareUploadResult, | ||
| } from "@t3tools/contracts"; | ||
| import * as Context from "effect/Context"; | ||
| import * as DateTime from "effect/DateTime"; | ||
| import * as Effect from "effect/Effect"; | ||
| import * as FileSystem from "effect/FileSystem"; | ||
| import * as Layer from "effect/Layer"; | ||
|
|
||
| import { | ||
| deletePendingAttachment, | ||
| issueAttachmentUploadUrl, | ||
| validateAttachmentUploadToken, | ||
| } from "../assets/AttachmentUpload.ts"; | ||
| import { | ||
| parseThreadSegmentFromAttachmentId, | ||
| PENDING_ATTACHMENT_THREAD_SEGMENT, | ||
| } from "../attachmentStore.ts"; | ||
| import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; | ||
| import * as ServerConfig from "../config.ts"; | ||
| import type { McpInvocationScope } from "./McpInvocationContext.ts"; | ||
|
|
||
| export class AttachmentMcpService extends Context.Service< | ||
| AttachmentMcpService, | ||
| { | ||
| readonly prepareUpload: ( | ||
| scope: McpInvocationScope, | ||
| input: AttachmentMcpPrepareUploadInput, | ||
| ) => Effect.Effect<AttachmentMcpPrepareUploadResult, AttachmentMcpFailure>; | ||
| readonly discardUpload: ( | ||
| scope: McpInvocationScope, | ||
| input: AttachmentMcpDiscardUploadInput, | ||
| ) => Effect.Effect<AttachmentMcpDiscardUploadResult, AttachmentMcpFailure>; | ||
| } | ||
| >()("t3/mcp/AttachmentMcpService") {} | ||
|
|
||
| function failure(code: AttachmentMcpFailure["code"], message: string): AttachmentMcpFailure { | ||
| return new AttachmentMcpFailure({ code, message }); | ||
| } | ||
|
|
||
| const requireCapability = (scope: McpInvocationScope) => | ||
| scope.capabilities.has("orchestration") | ||
| ? Effect.void | ||
| : Effect.fail( | ||
| failure( | ||
| "capability_denied", | ||
| "This MCP credential does not grant orchestration capabilities.", | ||
| ), | ||
| ); | ||
|
|
||
| export const make = Effect.gen(function* () { | ||
| const config = yield* ServerConfig.ServerConfig; | ||
| const secretStore = yield* ServerSecretStore.ServerSecretStore; | ||
| const fileSystem = yield* FileSystem.FileSystem; | ||
| const issueUpload = (input: Parameters<typeof issueAttachmentUploadUrl>[0]) => | ||
| issueAttachmentUploadUrl(input).pipe( | ||
| Effect.provideService(ServerConfig.ServerConfig, config), | ||
| Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), | ||
| ); | ||
| const discardPending = (attachmentId: string) => | ||
| deletePendingAttachment(attachmentId).pipe( | ||
| Effect.provideService(ServerConfig.ServerConfig, config), | ||
| Effect.provideService(FileSystem.FileSystem, fileSystem), | ||
| ); | ||
| const validateUploadToken = (token: string) => | ||
| validateAttachmentUploadToken(token).pipe( | ||
| Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), | ||
| ); | ||
|
|
||
| return AttachmentMcpService.of({ | ||
| prepareUpload: (scope, input) => | ||
| Effect.gen(function* () { | ||
| yield* requireCapability(scope); | ||
| const uploadInput = | ||
| input.type === "file" | ||
| ? { | ||
| type: "file" as const, | ||
| name: input.name, | ||
| mimeType: input.mimeType, | ||
| sizeBytes: input.sizeBytes, | ||
| } | ||
| : { | ||
| type: "image" as const, | ||
| name: input.name, | ||
| mimeType: | ||
| input.mimeType as (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number], | ||
| sizeBytes: input.sizeBytes, | ||
| }; | ||
| const issued = yield* issueUpload(uploadInput).pipe( | ||
| Effect.mapError(() => | ||
| failure("upload_error", "Unable to prepare a signed attachment upload."), | ||
| ), | ||
| ); | ||
| const attachment = { | ||
| id: issued.attachmentId, | ||
| type: input.type ?? "image", | ||
| name: input.name, | ||
| mimeType: input.mimeType, | ||
| sizeBytes: input.sizeBytes, | ||
| } as const; | ||
| return { | ||
| attachmentId: issued.attachmentId, | ||
| attachment, | ||
| type: input.type ?? "image", | ||
| name: input.name, | ||
| mimeType: input.mimeType, | ||
| sizeBytes: input.sizeBytes, | ||
| upload: { | ||
| method: "POST", | ||
| relativeUrl: issued.relativeUrl, | ||
| expiresAt: IsoDateTime.make(DateTime.formatIso(DateTime.makeUnsafe(issued.expiresAt))), | ||
| }, | ||
| }; | ||
| }), | ||
| discardUpload: (scope, input) => | ||
| Effect.gen(function* () { | ||
| yield* requireCapability(scope); | ||
| if ( | ||
| parseThreadSegmentFromAttachmentId(input.attachmentId) !== | ||
| PENDING_ATTACHMENT_THREAD_SEGMENT | ||
| ) { | ||
| return yield* failure( | ||
| "invalid_attachment", | ||
| "Only a pending upload can be discarded; thread-owned attachments are immutable here.", | ||
| ); | ||
| } | ||
| const token = input.uploadRelativeUrl.split("/").at(-1) ?? ""; | ||
| const claims = yield* validateUploadToken(token); | ||
| if (claims?.attachmentId !== input.attachmentId) { | ||
| return yield* failure( | ||
| "invalid_attachment", | ||
| "The signed upload URL does not authorize this pending attachment id.", | ||
| ); | ||
| } | ||
| yield* discardPending(input.attachmentId); | ||
| return { attachmentId: input.attachmentId, discarded: true }; | ||
| }), | ||
| }); | ||
| }); | ||
|
|
||
| export const layer = Layer.effect(AttachmentMcpService, make); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| // @effect-diagnostics nodeBuiltinImport:off | ||
| import * as NodeFS from "node:fs"; | ||
| import * as NodePath from "node:path"; | ||
|
|
||
| import * as NodeServices from "@effect/platform-node/NodeServices"; | ||
| import { expect, it } from "@effect/vitest"; | ||
| import { | ||
| ChatAttachmentId, | ||
| EnvironmentId, | ||
| ProjectId, | ||
| ProviderInstanceId, | ||
| type ServerProvider, | ||
| ThreadId, | ||
| type OrchestrationV2ThreadProjection, | ||
| } from "@t3tools/contracts"; | ||
| import * as Effect from "effect/Effect"; | ||
| import * as Layer from "effect/Layer"; | ||
| import * as Option from "effect/Option"; | ||
| import * as Ref from "effect/Ref"; | ||
|
|
||
| import { createPendingAttachmentId } from "../attachmentStore.ts"; | ||
| import * as ServerConfig from "../config.ts"; | ||
| import { | ||
| ThreadManagementPostDispatchProjectionError, | ||
| ThreadManagementService, | ||
| } from "../orchestration-v2/ThreadManagementService.ts"; | ||
| import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts"; | ||
| import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; | ||
| import type { McpInvocationScope } from "./McpInvocationContext.ts"; | ||
| import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; | ||
|
|
||
| it.effect( | ||
| "retains fresh accepted claims and releases unused replay claims after projection errors", | ||
| () => | ||
| Effect.gen(function* () { | ||
| const projectId = ProjectId.make("project:mcp-attachment-cleanup"); | ||
| const threadId = ThreadId.make("thread:mcp-attachment-cleanup"); | ||
| const projection = { | ||
| thread: { | ||
| id: threadId, | ||
| projectId, | ||
| runtimeMode: "full-access", | ||
| interactionMode: "default", | ||
| modelSelection: { | ||
| instanceId: ProviderInstanceId.make("codex"), | ||
| model: "gpt-5.6-sol", | ||
| }, | ||
| deletedAt: null, | ||
| }, | ||
| messages: [], | ||
| } as unknown as OrchestrationV2ThreadProjection; | ||
| const dispatchReplayed = yield* Ref.make(false); | ||
| const configLayer = ServerConfig.layerTest(process.cwd(), { | ||
| prefix: "t3-mcp-attachment-cleanup-", | ||
| }).pipe(Layer.provide(NodeServices.layer)); | ||
| const dependencies = Layer.mergeAll( | ||
| NodeServices.layer, | ||
| configLayer, | ||
| Layer.mock(ThreadManagementService)({ | ||
| getCommandReceipt: () => Effect.succeed(Option.none()), | ||
| getThreadProjection: () => Effect.succeed(projection), | ||
| sendToThread: (input) => | ||
| Ref.get(dispatchReplayed).pipe( | ||
| Effect.flatMap((replayed) => | ||
| Effect.fail( | ||
| new ThreadManagementPostDispatchProjectionError({ | ||
| projectId, | ||
| threadId, | ||
| messageId: input.messageId, | ||
| dispatchReplayed: replayed, | ||
| cause: new Error("projection unavailable after accepted dispatch"), | ||
| }), | ||
| ), | ||
| ), | ||
| ), | ||
| }), | ||
| Layer.mock(ProviderRegistry)({ | ||
| getProviders: Effect.succeed([ | ||
| { | ||
| instanceId: ProviderInstanceId.make("codex"), | ||
| driver: "codex", | ||
| } as unknown as ServerProvider, | ||
| ]), | ||
| }), | ||
| Layer.mock(ScheduledTaskService)({}), | ||
| ); | ||
| const testLayer = OrchestratorMcpService.layer.pipe(Layer.provideMerge(dependencies)); | ||
|
|
||
| yield* Effect.gen(function* () { | ||
| const service = yield* OrchestratorMcpService.OrchestratorMcpService; | ||
| const config = yield* ServerConfig.ServerConfig; | ||
| const scope: McpInvocationScope = { | ||
| environmentId: EnvironmentId.make("environment:mcp-attachment-cleanup"), | ||
| threadId, | ||
| providerSessionId: "provider-session:mcp-attachment-cleanup", | ||
| providerInstanceId: ProviderInstanceId.make("codex"), | ||
| capabilities: new Set(["orchestration"]), | ||
| issuedAt: 1, | ||
| }; | ||
| const stage = (name: string) => { | ||
| const id = createPendingAttachmentId(); | ||
| if (id === null) throw new Error("Expected a pending attachment id."); | ||
| NodeFS.writeFileSync( | ||
| NodePath.join(config.attachmentsDir, `${id}.png`), | ||
| Buffer.from([1, 2, 3, 4]), | ||
| ); | ||
| return { | ||
| type: "image" as const, | ||
| id: ChatAttachmentId.make(id), | ||
| name, | ||
| mimeType: "image/png", | ||
| sizeBytes: 4, | ||
| }; | ||
| }; | ||
| const claimedFiles = () => | ||
| NodeFS.readdirSync(config.attachmentsDir).filter( | ||
| (entry) => !entry.startsWith("pending-"), | ||
| ); | ||
|
|
||
| const freshError = yield* service | ||
| .sendToThread(scope, { | ||
| threadId, | ||
| attachments: [stage("fresh.png")], | ||
| clientRequestId: "fresh-accepted-claim", | ||
| }) | ||
| .pipe(Effect.flip); | ||
| expect(freshError.code).toBe("orchestration_error"); | ||
| expect(claimedFiles()).toHaveLength(1); | ||
|
|
||
| yield* Ref.set(dispatchReplayed, true); | ||
| const replayError = yield* service | ||
| .sendToThread(scope, { | ||
| threadId, | ||
| attachments: [stage("replay.png")], | ||
| clientRequestId: "replayed-accepted-claim", | ||
| }) | ||
| .pipe(Effect.flip); | ||
| expect(replayError.code).toBe("orchestration_error"); | ||
| expect(claimedFiles()).toHaveLength(1); | ||
| }).pipe(Effect.provide(testLayer)); | ||
| }), | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.