Testing File Handling in MCP Apps: Uploads, Downloads, and Cross-Host Compatibility (November 2026)

Testing file uploads and downloads in MCP Apps across ChatGPT and Claude.
File handling is one of the easiest parts of an MCP App to under-test because it crosses four boundaries at once: the model calls a tool, the server returns file metadata or resource content, the host renders a sandboxed app resource, and the user may pick or download a file through a host-owned UI.
That is why file tests need more than a component test with a fake File object. You need to test the tool contract, the resource UI, the host capability branch, and the server-side file checks separately.
TL;DR: Keep the portable path on MCP tools and resources. Use ChatGPT file APIs only behind feature detection. Put file metadata in structuredContent, not raw bytes. Test uploads with mocked host APIs, server contract tests, sunpeak simulation files, and one small live-host check for native picker behavior. Test downloads with useDownloadFile, binary resource assertions, and temporary URL failure cases.
Know Which File Reference You Have
The MCP Apps overview separates server tools and resources from the sandboxed View. A file can reach that View as an MCP resource or resource link, an application-owned storage ID, or a ChatGPT-specific file ID. These are different contracts, so record the source and intended reader before writing the test.
OpenAI’s plugin reference documents three optional ChatGPT helpers:
uploadFile(file, { library?: boolean })uploads a user-selected file and returns afileId. The library option saves it to the user’s ChatGPT file library when available.selectFiles()returns metadata for files the user selected from that library, when the helper is available.getFileDownloadUrl({ fileId })returns a temporary URL for a file authorized for the plugin.
A tool can also receive a ChatGPT file parameter. In that case, OpenAI requires _meta["openai/fileParams"] and a file object schema that declares download_url, file_id, mime_type, and file_name. The first two are required; the last two are optional. Test the tool schema and the runtime input separately. The server must validate the file against the current user and workflow, and it must not treat a client-supplied file ID or URL as proof of authorization.
These helpers belong to ChatGPT. Build a portable path with MCP tools, resources, host-mediated downloads, or an authenticated upload endpoint, then test the ChatGPT extension as an optional branch. Use capability checks for each control instead of deciding by host name.
Five File Flows to Test
Do not start by asking “does file upload work?” Name the direction first.
| Flow | Example | Test focus |
|---|---|---|
| Server returns binary content | Tool generates a PDF or image | MCP resource shape, MIME type, base64 validity, render/download UI |
| User picks a local file | User uploads a PDF from the app | Host capability check, file metadata, server validation, upload failure |
| User picks an existing host file | ChatGPT file library selection | selectFiles() feature detection, returned fileId, fallback path |
| Host passes a file to a tool | ChatGPT file parameter | Tool schema, optional metadata, temporary URL, user authorization |
| App downloads or exports a file | User downloads a CSV from the resource | Host-mediated download result, filename, MIME type, cancelled or denied result |
Most production bugs come from mixing these flows. A fileId is not a URL. A native picker is not available everywhere. A model-visible tool result is not a file store. A filename is not a trusted path.
Keep the Tool Contract Small
For file workflows, structuredContent should describe the file. It should not carry large bytes.
Good structuredContent for a file result looks like this:
{
"file": {
"id": "file_abc123",
"name": "quarterly-report.pdf",
"mimeType": "application/pdf",
"size": 482193,
"status": "ready",
"summary": "Quarterly revenue report with 8 pages"
}
}
That gives the model and resource enough context to reason about the file. The bytes belong somewhere else:
- In an MCP resource with
blobandmimeType. - Behind a
resource_linkor short-lived signed URL. - In host storage referenced by a
fileId. - In your own storage after server-side validation.
Write a protocol-level test that locks this contract down:
import { test, expect } from 'sunpeak/test';
test('analyze-report returns file metadata without raw bytes', async ({ mcp }) => {
const result = await mcp.callTool('analyze-report', {
reportId: 'q2-2026',
});
expect(result.isError).toBeFalsy();
const file = (result.structuredContent as { file?: Record<string, unknown> } | undefined)?.file;
expect(file).toMatchObject({
name: 'quarterly-report.pdf',
mimeType: 'application/pdf',
status: 'ready',
});
const serialized = JSON.stringify(result.structuredContent ?? {});
expect(serialized).not.toContain('JVBER'); // PDF base64 prefix
expect(serialized.length).toBeLessThan(4000);
});
This catches the easiest mistake: stuffing base64 into a model-visible field because it works in one manual test.
Test Binary MCP Resources Directly
When your server returns binary content through MCP resources, test the bytes before you render a browser.
import { test, expect } from 'sunpeak/test';
test('export-chart returns a valid PNG resource', async ({ mcp }) => {
const result = await mcp.callTool('export-chart', {
series: [12, 18, 23, 31],
});
expect(result.isError).toBeFalsy();
const content = result.content?.find((item) => item.type === 'resource') as
| { resource?: { mimeType?: string; blob?: string } }
| undefined;
expect(content).toBeDefined();
expect(content?.resource?.mimeType).toBe('image/png');
const bytes = Buffer.from(content?.resource?.blob ?? '', 'base64');
expect(bytes.length).toBeGreaterThan(100);
expect(bytes[0]).toBe(0x89);
expect(bytes[1]).toBe(0x50);
});
Add a PDF version if your app exports documents:
expect(bytes[0]).toBe(0x25); // %
expect(bytes[1]).toBe(0x50); // P
expect(bytes[2]).toBe(0x44); // D
expect(bytes[3]).toBe(0x46); // F
The browser test can then focus on user-visible behavior instead of discovering that your base64 encoder broke.
Test ChatGPT File APIs as Optional Capabilities
ChatGPT’s window.openai file methods are host extensions. The sunpeak useUploadFile hook in the version used here accepts one File argument, so it cannot pass ChatGPT’s optional library flag. The OpenAI changelog says the host upload method gained non-image support in March 2026. For a PDF or CSV flow that needs the current host options, call the documented window.openai.uploadFile method directly and feature-detect it. Import the sunpeak hook from sunpeak/host/chatgpt when you need its one-argument wrapper; sunpeak/chatgpt is the Inspector entry point.
This small component tests the native upload branch without claiming that the MCP server has received the bytes:
import { useState } from 'react';
type ChatGPTFiles = {
uploadFile?: (file: File, options?: { library?: boolean }) => Promise<{ fileId: string }>;
};
function fileBridge(): ChatGPTFiles | undefined {
if (typeof window === 'undefined') return undefined;
return (window as Window & { openai?: ChatGPTFiles }).openai;
}
export function ReportUpload() {
const [file, setFile] = useState<File | null>(null);
const [status, setStatus] = useState<'idle' | 'uploading' | 'ready' | 'error'>('idle');
async function handleUpload() {
const bridge = fileBridge();
if (!file || !bridge?.uploadFile) return;
setStatus('uploading');
try {
const { fileId } = await bridge.uploadFile(file);
if (!fileId) throw new Error('Missing file ID');
setStatus('ready');
} catch {
setStatus('error');
}
}
if (!fileBridge()?.uploadFile) {
return <p>Upload the report in your connected document system, then import it here.</p>;
}
return (
<div>
<input
aria-label="Report file"
type="file"
accept="application/pdf,text/csv"
onChange={(event) => setFile(event.currentTarget.files?.[0] ?? null)}
/>
<button type="button" disabled={!file || status === 'uploading'} onClick={handleUpload}>
{status === 'uploading' ? 'Uploading...' : 'Upload report'}
</button>
{status === 'ready' ? <p>Upload complete</p> : null}
{status === 'error' ? <p role="alert">Upload failed. Try again.</p> : null}
</div>
);
}
Run the success, error, and unavailable branches. This test checks the actual method shape and waits for the async UI result:
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ReportUpload } from './ReportUpload';
const uploadFile = vi.fn();
function setBridge(value: unknown) {
Object.defineProperty(window, 'openai', { configurable: true, value });
}
describe('ReportUpload', () => {
beforeEach(() => {
uploadFile.mockReset().mockResolvedValue({ fileId: 'file_abc123' });
setBridge({ uploadFile });
});
test('uploads a selected file through ChatGPT', async () => {
render(<ReportUpload />);
const file = new File(['id,total\n1,42'], 'report.csv', { type: 'text/csv' });
await userEvent.upload(screen.getByLabelText('Report file'), file);
await userEvent.click(screen.getByRole('button', { name: 'Upload report' }));
expect(uploadFile).toHaveBeenCalledWith(file);
expect(await screen.findByText('Upload complete')).toBeDefined();
});
test('shows a fallback when the helper is unavailable', () => {
setBridge(undefined);
render(<ReportUpload />);
expect(screen.getByText(/connected document system/)).toBeDefined();
expect(screen.queryByRole('button', { name: 'Upload report' })).toBeNull();
});
test('reports an upload failure', async () => {
uploadFile.mockRejectedValue(new Error('denied'));
render(<ReportUpload />);
await userEvent.upload(screen.getByLabelText('Report file'),
new File(['x'], 'report.csv', { type: 'text/csv' }));
await userEvent.click(screen.getByRole('button', { name: 'Upload report' }));
expect((await screen.findByRole('alert')).textContent).toContain('Upload failed');
});
});
For the file library, test both selectFiles() being absent and returning an authorized fileId. Keep that fileId distinct from a download URL. If an MCP tool must import the file, use the host’s supported file-parameter path or another authorized transfer flow, then validate ownership, type, and size on the server. Uploading to ChatGPT alone does not copy bytes into your MCP server.
Test Downloads with the Host, Not Just href
Sandboxed MCP App iframes often cannot rely on normal browser downloads. The portable pattern is a host-mediated download request.
sunpeak exposes that through useDownloadFile, which supports embedded text content, embedded base64 content, and resource links.
import { useState } from 'react';
import { useDownloadFile } from 'sunpeak';
export function ExportButton({ rows }: { rows: unknown[] }) {
const downloadFile = useDownloadFile();
const [error, setError] = useState<string | null>(null);
async function handleExport() {
setError(null);
try {
const result = await downloadFile({
contents: [{
type: 'resource',
resource: {
uri: 'file:///exports/report.json',
mimeType: 'application/json',
text: JSON.stringify(rows, null, 2),
},
}],
});
if (!result || result.isError) setError('Download was cancelled or unavailable.');
} catch {
setError('Download failed. Try again.');
}
}
return (
<div>
<button type="button" onClick={handleExport}>Export JSON</button>
{error ? <p role="alert">{error}</p> : null}
</div>
);
}
Unit test the download request shape:
import { expect, test, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ExportButton } from './ExportButton';
const mockDownloadFile = vi.hoisted(() => vi.fn());
vi.mock('sunpeak', () => ({
useDownloadFile: () => mockDownloadFile,
}));
test('exports rows through host-mediated download', async () => {
mockDownloadFile.mockResolvedValue({ isError: false });
render(<ExportButton rows={[{ id: 1, total: 42 }]} />);
await userEvent.click(screen.getByText('Export JSON'));
expect(mockDownloadFile).toHaveBeenCalledWith({
contents: [
{
type: 'resource',
resource: expect.objectContaining({
uri: 'file:///exports/report.json',
mimeType: 'application/json',
}),
},
],
});
});
test('shows the denied download path', async () => {
mockDownloadFile.mockResolvedValue({ isError: true });
render(<ExportButton rows={[]} />);
await userEvent.click(screen.getByText('Export JSON'));
expect((await screen.findByRole('alert')).textContent).toContain('cancelled or unavailable');
});
If you use ChatGPT fileId references, getFileDownloadUrl({ fileId }) is a different path. It returns a temporary URL, so resolve it when the user asks to download. Test the missing-helper case, a successful { downloadUrl } response, a rejected request, and a retry that asks for a fresh URL. Do not cache that URL as a durable file location. OpenAI’s file API reference lists the file sources the plugin may access.
Use Simulations for File States
sunpeak simulations are JSON fixtures in tests/simulations/ that pin a tool name, input, result, and optional server tool mocks. For file handling, they replace hard-to-reproduce live states with deterministic fixtures.
Start with a success fixture:
{
"tool": "show-report",
"userMessage": "Open the quarterly report",
"toolInput": {
"reportId": "q2-2026"
},
"toolResult": {
"structuredContent": {
"file": {
"id": "file_abc123",
"name": "quarterly-report.pdf",
"mimeType": "application/pdf",
"size": 482193,
"status": "ready"
},
"summary": "Quarterly revenue report with 8 pages"
}
}
}
Then add the states that break:
- No file returned.
- Unsupported host.
- Upload rejected by size or MIME type.
- Temporary download URL expired.
- File metadata exists but the server-side import is still processing.
- Binary resource has an unsupported MIME type.
- User cancelled a host-mediated download.
The E2E test should assert what the user sees in each state:
import { test, expect } from 'sunpeak/test';
test('report viewer renders file metadata from a simulation', async ({ inspector }) => {
const result = await inspector.renderTool('show-report');
const app = result.app();
await expect(app.getByText('quarterly-report.pdf')).toBeVisible();
await expect(app.getByText('application/pdf')).toBeVisible();
});
For host-specific branches, keep the test explicit:
test('ChatGPT file action is visible only when the host supports it', async ({ inspector }) => {
const result = await inspector.renderTool('show-report');
const app = result.app();
if (inspector.host === 'chatgpt') {
await expect(app.getByRole('button', { name: 'Open in ChatGPT files' })).toBeVisible();
} else {
await expect(app.getByRole('button', { name: 'Open in ChatGPT files' })).not.toBeVisible();
await expect(app.getByText('Use the connected document system to open this file.')).toBeVisible();
}
});
Avoid broad skips for portable behavior. Skip or branch only around the feature that truly belongs to one host.
Test Server-Side File Security
File handling security belongs on the server. The iframe can help the user choose a file, but the server has to validate what it receives.
Add tests for:
- Maximum file size.
- Allowed MIME types and extensions.
- MIME sniffing or magic-byte checks for risky formats.
- User authorization for the file or upload ID.
- Path traversal in filenames such as
../../secret.txt. - Duplicate upload IDs and idempotency behavior.
- Virus scanning or malware checks when your product needs them.
- Cleanup after failed uploads.
Example server test:
import { test, expect } from 'sunpeak/test';
test('rejects unsupported upload MIME types', async ({ mcp }) => {
const result = await mcp.callTool('create-upload', {
fileName: 'payload.exe',
mimeType: 'application/x-msdownload',
size: 12000,
});
expect(result.isError).toBe(true);
expect(result.content?.[0]?.text).toContain('Unsupported file type');
});
And test filenames like data, not paths:
test('does not trust filenames as storage paths', async ({ mcp }) => {
const result = await mcp.callTool('create-upload', {
fileName: '../../private/report.pdf',
mimeType: 'application/pdf',
size: 12000,
});
expect(result.isError).toBe(true);
});
This is the part a live ChatGPT or Claude smoke test will not catch. Keep it in fast CI.
Cross-Host Test Matrix
For a file-heavy ChatGPT App, Claude Connector, or portable MCP App, use this matrix:
| Layer | What to verify | Runs where |
|---|---|---|
| Protocol test | Tool input schema, outputSchema, structuredContent, _meta, resource content | Local CI |
| ChatGPT file parameter test | _meta["openai/fileParams"], required file fields, optional metadata, and server authorization | Local CI plus one live input check |
| Server file test | Size, MIME, extension, auth, storage, cleanup | Local CI |
| Component unit test | Host API mocks, loading states, error states, fallback text | Local CI |
| Inspector E2E test | Rendered iframe UI across host replicas and simulations | Local CI |
| Visual test | File cards, previews, progress, empty states, narrow layouts | Local CI |
| Live-host smoke test | Native picker opens and returns expected metadata | Slow path before release |
The live-host test should stay small. It should prove that the native host path still works after deployment. Most coverage belongs in deterministic local tests because that is where you can run every file state on every change.
With sunpeak’s testing framework, the usual workflow is:
pnpm test:unit
pnpm test:e2e
pnpm test:visual
For an existing MCP server that is not built with sunpeak, scaffold tests around it:
npx sunpeak test init --server http://localhost:8000/mcp
Then add simulations for file states and use the inspector fixture to render those states in local ChatGPT and Claude-style runtimes.
File Handling Test Checklist
Use this before you ship a file workflow:
- The tool contract keeps raw bytes out of
structuredContent. - Binary MCP resources decode to valid bytes and match their MIME type.
- ChatGPT-only APIs are feature-detected before use.
- ChatGPT file parameters have the required schema and server authorization checks.
- Claude and non-ChatGPT hosts render a tested fallback.
- Native file picker logic has unit coverage after the picker returns.
- Server upload tools reject unsupported type, size, path, and auth cases.
- Download flows handle cancelled, denied, expired, and retry states.
- Simulation files cover ready, missing, rejected, processing, and error states.
- E2E tests assert the rendered file UI in each supported host profile.
- One live smoke test covers the native host picker if the release depends on it.
Get Started
File handling in MCP Apps is not one API. It is a contract between your tool, resource, host, storage layer, and user-facing fallback.
Build the portable contract first. Add ChatGPT file APIs where they improve the flow. Test Claude and other non-ChatGPT paths with the same care. sunpeak helps by giving you local host replicas, simulation fixtures, protocol tests, and Playwright E2E tests, so file bugs do not have to wait for a live chat session.
Start with npx sunpeak new, add one file simulation, and turn the most fragile manual file check into an automated test before your next deploy.
Get Started
npx sunpeak newFurther Reading
- File Uploads in MCP Apps - ChatGPT Apps, blob resources, and Claude Connectors
- Cross-host compatibility testing for MCP Apps
- MCP App capability detection and fallbacks
- Mocking and stubbing in MCP App tests
- E2E testing MCP Apps with the inspector fixture
- Security testing MCP Apps - file path validation and upload risk
- MCP App tool results - content, structuredContent, and _meta
- sunpeak useDownloadFile hook reference
- sunpeak simulations - deterministic file states for tests
- OpenAI plugin reference - ChatGPT file APIs
- OpenAI ChatGPT UI guide - feature-detect window.openai extensions
- Official MCP Apps overview - resources, iframes, and host bridge
- MCP Apps App API - downloadFile request and result
Frequently Asked Questions
How do I test file uploads in an MCP App?
Test file uploads in layers. Unit test the resource component with mocked file APIs. Integration test the server-side validation and storage contract. Render deterministic upload states with sunpeak simulation files. Then run one narrow live-host smoke test for the native picker path if the app depends on ChatGPT file APIs.
What file APIs do ChatGPT Apps expose?
OpenAI documents optional ChatGPT helpers: window.openai.uploadFile(file, { library?: boolean }), window.openai.selectFiles(), and window.openai.getFileDownloadUrl({ fileId }). uploadFile returns a fileId, selectFiles returns metadata for files authorized for the plugin when the library is available, and getFileDownloadUrl returns a temporary URL. Feature-detect each helper. The sunpeak useUploadFile wrapper accepts one File argument, so call window.openai directly if you need the library option.
Do Claude Connectors support the same file APIs as ChatGPT Apps?
Do not assume they do. Build the portable path around MCP tools, resources, authenticated data sources, and server-side upload or import flows. If the same MCP App runs in ChatGPT, keep ChatGPT-only file controls behind capability detection and verify the Claude fallback in E2E tests.
How do I test file downloads in MCP Apps?
For portable downloads, test the host-mediated ui/download-file path with embedded text, embedded base64 resource content, or resource links. In sunpeak, use useDownloadFile and assert the request shape plus the denied or cancelled result. For ChatGPT file IDs, test that getFileDownloadUrl receives the right fileId and that the UI handles temporary URL failures.
Should file bytes go in structuredContent?
Usually no. structuredContent is typed data for the model and app resource, so it should contain concise metadata, IDs, status, and summaries. Use MCP blob resources, resource links, signed URLs, or host file IDs for file bytes. This keeps model-visible context small and avoids leaking raw file data into places that only need metadata.
Can MCP Apps handle binary files like images and PDFs?
Yes. MCP resources can carry binary content as base64 blob data with a MIME type, and MCP Apps can render or download that content through the host. Test binary output by decoding the base64 in a protocol-level test, checking magic bytes, validating the MIME type, and rendering the file state in an inspector E2E test.
How do simulation files help with file handling tests?
Simulation files pin tool input, tool results, structuredContent, and server tool mocks. They let you render file-present, file-missing, upload-error, unsupported-host, large-file, and expired-link states in the local inspector without opening a native file picker or touching real storage. A live-host check is still needed for native picker behavior.
What are the most common file handling bugs in MCP Apps?
Common bugs include calling window.openai without feature detection, treating a fileId as a URL, putting base64 content in structuredContent, missing MIME or size validation on the server, trusting filenames as paths, not handling temporary download URL expiry, and only testing ChatGPT while the app also claims to support Claude.