Skip to content

Commit 97b70ee

Browse files
fix(filesystem): return valid MCP content type from read_media_file (#4029) (#4479)
* fix(filesystem): return valid MCP content type from read_media_file (#4029) read_media_file returned a content block with type: "blob" for non-image/ non-audio files. "blob" is not a valid MCP content type (the union is text | image | audio | resource_link | resource), so a strict client rejects the result on schema validation. Map the MIME type to a valid block: image/* -> image, audio/* -> audio, and any other file type -> an embedded resource (the spec-correct carrier for arbitrary bytes) with a pathToFileURL-encoded uri. Widen the tool's outputSchema to the matching union and drop the now-unnecessary `as unknown as CallToolResult` cast so tsc enforces the returned shape. Tests cover the image, audio, and resource content types, verify the base64 blob round-trips to the original bytes, and assert the resource uri is percent-encoded (space + non-ASCII) rather than a raw file:// concatenation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(filesystem): assert structuredContent mirrors content in read_media_file tests The SDK validates content and structuredContent independently against the outputSchema union, so a refactor that lets the two drift apart (e.g. a stale image block in structuredContent while content carries the resource) stays schema-valid and every test stays green. Mirror-equality assertions on all four callTool cases close that gap (mutation-verified: a schema-valid drifted structuredContent fails exactly these four assertions). Also drops a vacuous .not.toBe('blob') assertion that could never add signal, noting where the real "never blob" guard actually lives (the SDK client's CallToolResultSchema rejection, upstream of any local assertion). Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 0e30ad1 commit 97b70ee

3 files changed

Lines changed: 161 additions & 18 deletions

File tree

‎src/filesystem/README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,12 @@ The server's directory access control follows this flow:
7878
- Cannot specify both `head` and `tail` simultaneously
7979

8080
- **read_media_file**
81-
- Read an image or audio file
81+
- Read a file and return it as a base64-encoded content block with its MIME type
8282
- Inputs:
8383
- `path` (string)
84-
- Streams the file and returns base64 data with the corresponding MIME type
84+
- Streams the file and returns base64 data with the corresponding MIME type. Image and
85+
audio files are returned as `image`/`audio` content; any other file type is returned as
86+
an embedded `resource` (a valid MCP content block for arbitrary binary data)
8587

8688
- **read_multiple_files**
8789
- Read multiple files simultaneously

‎src/filesystem/__tests__/structured-content.test.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as os from 'os';
55
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
66
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
77
import { spawn } from 'child_process';
8+
import { fileURLToPath } from 'url';
89

910
/**
1011
* Integration tests to verify that tool handlers return structuredContent
@@ -155,4 +156,126 @@ describe('structuredContent schema compliance', () => {
155156
expect(Array.isArray(structuredContent.content)).toBe(false);
156157
});
157158
});
159+
160+
// read_media_file must return a VALID MCP content block. Previously it emitted
161+
// type: "blob" for non-image/audio files, which is not in the MCP content-block
162+
// union (text | image | audio | resource_link | resource) and a strict client
163+
// rejects on schema validation. See issue #4029.
164+
describe('read_media_file (issue #4029)', () => {
165+
// Image/audio inputs already returned valid content types before #4029 (only the
166+
// non-media fallback was the invalid "blob"), so these two cases are "still-works"
167+
// coverage — they round-trip the bytes to catch an encoding regression on the media
168+
// paths. The resource + café cases below are the actual #4029 regression guards
169+
// (they fail against the pre-fix "blob" build).
170+
it('returns type "image" for image files, round-tripping the bytes', async () => {
171+
const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
172+
const pngPath = path.join(testDir, 'pixel.png');
173+
// Contents aren't validated by the tool (MIME is by extension), so arbitrary bytes are fine.
174+
await fs.writeFile(pngPath, pngBytes);
175+
176+
const result = await client.callTool({
177+
name: 'read_media_file',
178+
arguments: { path: pngPath }
179+
});
180+
181+
const content = result.content as Array<{ type: string; data?: string; mimeType?: string }>;
182+
expect(Array.isArray(content)).toBe(true);
183+
expect(content).toHaveLength(1);
184+
expect(content[0].type).toBe('image');
185+
expect(content[0].mimeType).toBe('image/png');
186+
expect(Buffer.from(content[0].data!, 'base64').equals(pngBytes)).toBe(true);
187+
// structuredContent must MIRROR content. The SDK validates each field independently
188+
// against the outputSchema union (either arm is valid for either field), so schema
189+
// validation alone cannot catch the two drifting apart — only this equality can.
190+
expect(result.structuredContent).toEqual({ content });
191+
});
192+
193+
it('returns type "audio" for audio files, round-tripping the bytes', async () => {
194+
const mp3Bytes = Buffer.from([0x49, 0x44, 0x33, 0x04]);
195+
const mp3Path = path.join(testDir, 'clip.mp3');
196+
await fs.writeFile(mp3Path, mp3Bytes);
197+
198+
const result = await client.callTool({
199+
name: 'read_media_file',
200+
arguments: { path: mp3Path }
201+
});
202+
203+
const content = result.content as Array<{ type: string; data?: string; mimeType?: string }>;
204+
expect(content[0].type).toBe('audio');
205+
expect(content[0].mimeType).toBe('audio/mpeg');
206+
expect(Buffer.from(content[0].data!, 'base64').equals(mp3Bytes)).toBe(true);
207+
expect(result.structuredContent).toEqual({ content }); // must mirror content (see image case)
208+
});
209+
210+
it('returns an embedded resource (never "blob") for non-media binaries, round-tripping the bytes', async () => {
211+
const binBytes = Buffer.from([0x00, 0x01, 0x02, 0x03, 0xff, 0xfe]);
212+
const binPath = path.join(testDir, 'data.bin');
213+
await fs.writeFile(binPath, binBytes);
214+
215+
const result = await client.callTool({
216+
name: 'read_media_file',
217+
arguments: { path: binPath }
218+
});
219+
220+
const content = result.content as Array<{
221+
type: string;
222+
resource?: { uri: string; mimeType: string; blob: string };
223+
}>;
224+
expect(content).toHaveLength(1);
225+
// ("never blob" is enforced upstream of any assertion here: the SDK client's
226+
// CallToolResultSchema parse rejects a blob block before content is even inspected,
227+
// failing the callTool above — which is exactly how this test fails pre-fix.)
228+
expect(content[0].type).toBe('resource');
229+
expect(content[0].resource).toBeDefined();
230+
expect(content[0].resource!.uri.startsWith('file://')).toBe(true);
231+
// Decode the uri back to a path and confirm it is the file actually read — guards a
232+
// refactor that builds the uri from the wrong variable while still emitting a
233+
// well-formed file:// string. (realpath handles the /tmp -> /private/tmp macOS alias.)
234+
expect(fileURLToPath(content[0].resource!.uri)).toBe(await fs.realpath(binPath));
235+
expect(content[0].resource!.mimeType).toBe('application/octet-stream');
236+
// The base64 blob must round-trip to the original bytes (data integrity, not just a valid
237+
// shape) — this also subsumes a non-empty check.
238+
expect(Buffer.from(content[0].resource!.blob, 'base64').equals(binBytes)).toBe(true);
239+
expect(result.structuredContent).toEqual({ content }); // must mirror content (see image case)
240+
});
241+
242+
it('percent-encodes spaces and non-ASCII chars in the resource uri (pathToFileURL, not a raw file:// concatenation)', async () => {
243+
const fancyPath = path.join(testDir, 'my café.bin');
244+
await fs.writeFile(fancyPath, Buffer.from([0x10, 0x20, 0x30]));
245+
246+
const result = await client.callTool({
247+
name: 'read_media_file',
248+
arguments: { path: fancyPath }
249+
});
250+
251+
const content = result.content as Array<{ type: string; resource?: { uri: string } }>;
252+
expect(content[0].type).toBe('resource');
253+
const uri = content[0].resource!.uri;
254+
// pathToFileURL percent-encodes the space (%20) and the non-ASCII "é" (%C3%A9 for NFC,
255+
// or the base "e" + %CC%81 for the NFD form some filesystems store); a raw
256+
// `file://${validPath}` (as in PR #4044) would leave both literal.
257+
expect(uri).toContain('%20');
258+
expect(uri).not.toContain(' ');
259+
// The non-ASCII "é" must be percent-encoded: %C3%A9 (NFC) or base-"e" + %CC%81 (the NFD
260+
// form some filesystems decompose to). This regex — not a `.not.toContain('é')`, which is
261+
// vacuous on an NFD runner where the precomposed char never appears — is the load-bearing
262+
// assertion that distinguishes pathToFileURL from a raw `file://${path}` concatenation.
263+
expect(uri).toMatch(/%C3%A9|%CC%81/);
264+
expect(result.structuredContent).toEqual({ content }); // must mirror content (see image case)
265+
});
266+
267+
it('advertises the widened outputSchema union via tools/list (both branches serialize)', async () => {
268+
const { tools } = await client.listTools();
269+
const tool = tools.find((t) => t.name === 'read_media_file');
270+
expect(tool).toBeDefined();
271+
// The union outputSchema must serialize to JSON Schema — a DIFFERENT SDK path
272+
// (toJsonSchemaCompat / tools-list) than the callTool structuredContent validation the
273+
// other cases exercise — with BOTH branches present. Guards a nested-union-in-array
274+
// serialization quirk that could drop the resource arm from the advertised schema.
275+
const schemaStr = JSON.stringify(tool!.outputSchema);
276+
expect(schemaStr).toMatch(/resource/);
277+
expect(schemaStr).toMatch(/image/);
278+
expect(schemaStr).toMatch(/audio/);
279+
});
280+
});
158281
});

‎src/filesystem/index.ts‎

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
44
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
55
import {
6-
CallToolResult,
76
RootsListChangedNotificationSchema,
87
type Root,
98
} from "@modelcontextprotocol/sdk/types.js";
109
import fs from "fs/promises";
1110
import { createReadStream } from "fs";
1211
import path from "path";
12+
import { pathToFileURL } from "url";
1313
import { z } from "zod";
1414
import { minimatch } from "minimatch";
1515
import { normalizePath, expandHome } from './path-utils.js';
@@ -250,17 +250,29 @@ server.registerTool(
250250
{
251251
title: "Read Media File",
252252
description:
253-
"Read an image or audio file. Returns the base64 encoded data and MIME type. " +
254-
"Only works within allowed directories.",
253+
"Read a file and return it as a base64-encoded content block with its MIME type. " +
254+
"Image and audio files are returned as image/audio content; any other file type is " +
255+
"returned as an embedded resource. Only works within allowed directories.",
255256
inputSchema: {
256257
path: z.string()
257258
},
258259
outputSchema: {
259-
content: z.array(z.object({
260-
type: z.enum(["image", "audio", "blob"]),
261-
data: z.string(),
262-
mimeType: z.string()
263-
}))
260+
content: z.array(z.union([
261+
z.object({
262+
type: z.enum(["image", "audio"]),
263+
data: z.string(),
264+
mimeType: z.string()
265+
}),
266+
z.object({
267+
type: z.literal("resource"),
268+
resource: z.object({
269+
uri: z.string(),
270+
// Optional, matching the SDK's BlobResourceContents shape (the handler always sets it).
271+
mimeType: z.string().optional(),
272+
blob: z.string()
273+
})
274+
})
275+
]))
264276
},
265277
annotations: { readOnlyHint: true }
266278
},
@@ -283,17 +295,23 @@ server.registerTool(
283295
const mimeType = mimeTypes[extension] || "application/octet-stream";
284296
const data = await readFileAsBase64Stream(validPath);
285297

286-
const type = mimeType.startsWith("image/")
287-
? "image"
288-
: mimeType.startsWith("audio/")
289-
? "audio"
290-
// Fallback for other binary types, not officially supported by the spec but has been used for some time
291-
: "blob";
292-
const contentItem = { type: type as 'image' | 'audio' | 'blob', data, mimeType };
298+
// Map the MIME type to a valid MCP content block. The spec only allows
299+
// text, image, audio, resource_link, and resource — so non-image/audio
300+
// binaries are returned as an embedded resource (NOT type:"blob", which the
301+
// SDK content-block union rejects on schema validation).
302+
const contentItem =
303+
mimeType.startsWith("image/")
304+
? { type: "image" as const, data, mimeType }
305+
: mimeType.startsWith("audio/")
306+
? { type: "audio" as const, data, mimeType }
307+
: {
308+
type: "resource" as const,
309+
resource: { uri: pathToFileURL(validPath).href, mimeType, blob: data }
310+
};
293311
return {
294312
content: [contentItem],
295313
structuredContent: { content: [contentItem] }
296-
} as unknown as CallToolResult;
314+
};
297315
}
298316
);
299317

0 commit comments

Comments
 (0)