Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): reject duplicate attachments and report precise admission errors
Alfredo Lopezc578f0a35533
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 080e316d2..aa9b98825 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.447",+ "version": "0.1.448","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.447",+ "version": "0.1.448","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 2e0aab539..9a9a99b38 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.447",+ "version": "0.1.448","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/agent/__tests__/incomingAdmission.test.ts b/mcp-host/src/agent/__tests__/incomingAdmission.test.tsindex 27ee143df..325d9d9d3 100644--- a/mcp-host/src/agent/__tests__/incomingAdmission.test.ts+++ b/mcp-host/src/agent/__tests__/incomingAdmission.test.ts@@ -90,7 +90,7 @@ function makeAdmission(overrides: Partial<IncomingAdmissionDeps> = {}): {taskId: 't-1',status: 'pending',})),- fileReferenceClient: () => null,+ fileReferenceGfs: () => ({ status: 'unsupported' }),logger,...overrides,}@@ -590,6 +590,33 @@ describe('#666 file attachments at admission', () => {expect(logged).not.toContain(digestHex)})+ it('emits attachment_admitted only once the message is accepted', async () => {+ const notReady = makeAdmission({ queueReady: () => false })+ const refused = makeAdmission({+ dispatch: vi.fn(() => ({+ success: false,+ error: { code: 'X', message: 'x', retryable: false, provider: 'zai' },+ })),+ })+ const accepted = makeAdmission()++ const notReadyResponse = await notReady.admit(fileMessage())+ const refusedResponse = await refused.admit(fileMessage())+ await accepted.admit(fileMessage())++ // Witness: the accepted message emitted the event once.+ expect(admittedLogs(accepted.spies)).toHaveLength(1)+ // Witnesses: both refusals were produced by their own gates.+ expect(notReadyResponse).toMatchObject({+ success: false,+ error: { message: 'Message queue not initialized' },+ })+ expect(refused.spies.dispatch).toHaveBeenCalledTimes(1)+ expect(refusedResponse).toMatchObject({ success: false, error: { code: 'X' } })+ expect(admittedLogs(notReady.spies)).toHaveLength(0)+ expect(admittedLogs(refused.spies)).toHaveLength(0)+ })+it('emits no attachment_admitted event for an image-only message', async () => {const { admit, spies } = makeAdmission()diff --git a/mcp-host/src/agent/__tests__/incomingAttachments.test.ts b/mcp-host/src/agent/__tests__/incomingAttachments.test.tsindex c755416c6..88cd5a8bc 100644--- a/mcp-host/src/agent/__tests__/incomingAttachments.test.ts+++ b/mcp-host/src/agent/__tests__/incomingAttachments.test.ts@@ -283,15 +283,34 @@ describe('file attachment validation (issue #666)', () => {expect(attachment.kind).toBe('file')})- it('lets the host detection win over the declared one and records the disagreement', () => {- // The client claimed plain text; the host detects markdown from the extension.+ it('ignores the client detection: only the declared type can disagree with the host', () => {+ // The client detected plain text; the host detects markdown from the+ // extension. The client detection is not a declaration, so no mismatch.const { attachment, reference } = admitOne({ ...notes, detectedMediaType: 'text/plain' })expect(reference).toMatchObject({class: 'markdown',+ declaredMediaType: 'text/markdown',detectedMediaType: 'text/markdown',- mismatch: true,+ mismatch: false,})expect(attachment.detectedMediaType).toBe('text/markdown')++ // Witness: a declared type the host disagrees with is still recorded.+ const declaredPdf = admitOne({ ...notes, mimeType: 'application/pdf' })+ expect(declaredPdf.reference).toMatchObject({+ declaredMediaType: 'application/pdf',+ mismatch: true,+ })+ })++ it('admits an empty mimeType as no declared type', () => {+ const { attachment, reference } = admitOne({ ...notes, mimeType: '' })+ expect(reference).toMatchObject({+ declaredMediaType: null,+ detectedMediaType: 'text/markdown',+ mismatch: false,+ })+ expect(attachment.mimeType).toBe('')})it('admits a zero-byte file', () => {@@ -355,6 +374,12 @@ describe('file attachment validation (issue #666)', () => {'a name with a path separator',{ ...notes, filename: 'dir/notes.md' },],+ ['FILE_ATTACHMENT_INVALID', 'a negative declared size', { ...notes, sizeBytes: -1 }],+ [+ 'FILE_ATTACHMENT_INVALID',+ 'a fractional declared size',+ { ...notes, sizeBytes: notes.sizeBytes - 0.5 },+ ],['FILE_ATTACHMENT_TOO_LARGE', 'decoded bytes over maxFileBytes', tooBig],['FILE_ATTACHMENT_TOO_LARGE', 'a declared size over maxFileBytes', { ...notes, sizeBytes: 65 }],[@@ -382,4 +407,53 @@ describe('file attachment validation (issue #666)', () => {const result = validateIncomingAttachments([{ ...notes, kind: 'document' }], limits)expect(result).toMatchObject({ ok: false, error: { code: 'LLM_INVALID_ATTACHMENT' } })})++ it('rejects an attachment id sent twice, across kinds or within one', () => {+ // Witness: the same attachments with distinct ids are admitted.+ expect(validateIncomingAttachments([image, notes], limits).ok).toBe(true)+ const duplicate = {+ ok: false,+ error: {+ code: 'LLM_INVALID_ATTACHMENT',+ message: 'Each attachment id must appear once.',+ retryable: false,+ provider: 'unknown',+ },+ }+ expect(validateIncomingAttachments([image, { ...notes, id: image.id }], limits)).toEqual(+ duplicate+ )+ expect(validateIncomingAttachments([notes, notes], limits)).toEqual(duplicate)+ expect(validateIncomingAttachments([image, image], limits)).toEqual(duplicate)+ })++ it('does not ask for a rename when the reference fails for a reason other than the name', () => {+ const noMessage = validateIncomingAttachments([notes], { ...limits, messageId: '' })+ expect(noMessage).toMatchObject({+ ok: false,+ error: { code: 'FILE_ATTACHMENT_INVALID', retryable: false },+ })+ expect(noMessage.ok === false && noMessage.error.message).toMatch(+ /^A file attachment is invalid: /+ )+ expect(noMessage.ok === false && noMessage.error.message).not.toContain('Rename')++ // Witness: a name problem still asks for a rename.+ const badName = validateIncomingAttachments([{ ...notes, filename: 'dir/notes.md' }], limits)+ expect(badName.ok === false && badName.error.message).toBe(+ 'A file attachment has an invalid name. Rename the file and attach it again.'+ )+ })++ it('names the list requirement when attachments are not a list', () => {+ expect(validateIncomingAttachments('not-a-list', limits)).toEqual({+ ok: false,+ error: {+ code: 'LLM_INVALID_ATTACHMENT',+ message: 'Attachments must be a list.',+ retryable: false,+ provider: 'unknown',+ },+ })+ })})diff --git a/mcp-host/src/agent/incomingAttachments.ts b/mcp-host/src/agent/incomingAttachments.tsindex 488a56336..90981e112 100644--- a/mcp-host/src/agent/incomingAttachments.ts+++ b/mcp-host/src/agent/incomingAttachments.ts@@ -168,18 +168,14 @@ function validateFile(item: Record<string, unknown>, limits: IncomingAttachmentL}const declaredMediaType = item.mimeType === '' ? null : item.mimeType- const classified = classifyBytes({+ // The Host's classification is the only one used: `mismatch` compares the+ // declared type with the bytes, never with the client's own detection.+ const classification = classifyBytes({bytes,totalByteLength: bytes.length,declaredMediaType,filename: item.filename,})- // The host's detection wins over the one the client declared; a disagreement- // is recorded, never rejected.- const classification = {- ...classified,- mismatch: classified.mismatch || item.detectedMediaType !== classified.detectedMediaType,- }const reference = buildAttachmentFileReference({attachmentId: item.id,messageId: limits.messageId,@@ -190,7 +186,11 @@ function validateFile(item: Record<string, unknown>, limits: IncomingAttachmentLclassification,})if (!reference.ok) {- return rejectFile('A file attachment has an invalid name. Rename the file and attach it again.')+ // Every name problem the contract reports starts with "name "; any other+ // failure is not something the user can fix by renaming the file.+ return reference.message.startsWith('name ')+ ? rejectFile('A file attachment has an invalid name. Rename the file and attach it again.')+ : rejectFile(`A file attachment is invalid: ${reference.message}`)}return {ok: true,@@ -215,7 +215,7 @@ export function validateIncomingAttachments(limits: IncomingAttachmentLimits): IncomingAttachmentValidation {if (raw == null) return { ok: true, attachments: undefined, fileReferences: [] }- if (!Array.isArray(raw)) return rejectImage('Image attachments must be a list.')+ if (!Array.isArray(raw)) return rejectImage('Attachments must be a list.')if (!raw.length) return { ok: true, attachments: undefined, fileReferences: [] }// One ceiling over images and files together, checked before either branch.if (raw.length > limits.maxCount) {@@ -228,6 +228,7 @@ export function validateIncomingAttachments(}const attachments: Attachment[] = []const fileReferences: FileReferenceV1[] = []+ const ids = new Set<string>()for (const item of raw) {const result = !isPlainRecord(item)? rejectImage('Only PNG or JPEG images encoded as base64 are supported.')@@ -237,6 +238,9 @@ export function validateIncomingAttachments(? validateImage(item, limits.maxBytes): rejectImage('Only PNG or JPEG images encoded as base64 are supported.')if (!result.ok) return result+ // Ids name attachments in the ack and in tool calls, across both kinds.+ if (ids.has(result.attachment.id)) return rejectImage('Each attachment id must appear once.')+ ids.add(result.attachment.id)attachments.push(result.attachment)if (result.attachment.fileReference) fileReferences.push(result.attachment.fileReference)}diff --git a/mcp-host/src/messageHandler.ts b/mcp-host/src/messageHandler.tsindex f12a0dbb7..16802e971 100644--- a/mcp-host/src/messageHandler.ts+++ b/mcp-host/src/messageHandler.ts@@ -328,13 +328,28 @@ export class IncomingMessageHandler {// #666 — a success names the attachments and file references the first// delivery admitted, as the first response did; without them a client reads// a Host that dropped them.- const accepted = {- ...(record?.acceptedAttachmentIds.length- ? { acceptedAttachmentIds: [...record.acceptedAttachmentIds] }- : {}),- ...(record?.acceptedFileReferenceIds.length- ? { acceptedFileReferenceIds: [...record.acceptedFileReferenceIds] }- : {}),+ let accepted: Pick<MessageResponse, 'acceptedAttachmentIds' | 'acceptedFileReferenceIds'> = {}+ if (record) {+ accepted = {+ ...(record.acceptedAttachmentIds.length+ ? { acceptedAttachmentIds: [...record.acceptedAttachmentIds] }+ : {}),+ ...(record.acceptedFileReferenceIds.length+ ? { acceptedFileReferenceIds: [...record.acceptedFileReferenceIds] }+ : {}),+ }+ } else {+ // The queue knows the prior task but the lifecycle holds no record of it,+ // so this answer cannot name what the first delivery accepted.+ logger.warn(+ {+ event: 'duplicate_delivery_record_missing',+ taskId: this.task.id,+ priorTaskId,+ priorStatus,+ },+ 'Duplicate delivery record missing'+ )}if (priorStatus === 'completed') {return {