Upload images through the API, and from the MCP server
Some checks failed
Tests / lint (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / test-postgres (push) Has been cancelled
Tests / mcp (push) Has been cancelled

POST /api/v1/media stores an image where the panel keeps a page's and
answers with the path to send as `featured_image`. Without it the MCP
server could create a page but never give it a picture. The file goes
through Media::for(), so it is processed, served and pruned like one
uploaded in the panel.

Two ways in, one per request: a multipart `file`, or JSON with a `url`
the API downloads itself. JPEG, PNG, WebP, GIF or AVIF only, decided
from the bytes; no SVG, which is a document that can carry script.

The URL is fetched from inside the stack's network, so RemoteImage
guards it: HTTPS only, every resolved address must be public, the
connection is pinned to the checked address with CURLOPT_RESOLVE so a
changing DNS answer cannot swap in a private one, redirects are not
followed, and the body is read to a ceiling whatever its headers say.

Uploading needs permission to write pages. MediaPolicy::create stays
false, so the panel gains no free-standing "new file" button.

In the MCP server a multipart binary field becomes `<field>_path` over
stdio: the server reads the file from the caller's disk and sends it
as multipart, instead of the model pushing base64 through its context.
Over HTTP the server's disk is not the caller's, so only `body.url` is
offered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-28 11:16:33 +02:00
parent daf6098203
commit a49816eb46
21 changed files with 1008 additions and 11 deletions

View File

@@ -16,11 +16,13 @@ export class Catalogue {
* @param {string} options.source Path or URL of openapi.yaml.
* @param {string} options.baseUrl Application root the document's server URL is relative to.
* @param {number} [options.ttlMs] How long a loaded document is trusted. Infinity: load once.
* @param {boolean} [options.localFiles] Offer uploads from a local path; see `buildTools`.
*/
constructor({ source, baseUrl, ttlMs = Infinity }) {
constructor({ source, baseUrl, ttlMs = Infinity, localFiles = false }) {
this.source = source;
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.ttlMs = ttlMs;
this.localFiles = localFiles;
this.current = null;
this.loadedAt = 0;
this.pending = null;
@@ -58,7 +60,7 @@ export class Catalogue {
this.current = {
spec,
tools: buildTools(spec),
tools: buildTools(spec, { localFiles: this.localFiles }),
apiBase: /^https?:\/\//.test(serverUrl) ? serverUrl : `${this.baseUrl}${serverUrl}`,
};
this.loadedAt = Date.now();

View File

@@ -8,12 +8,19 @@
* expired upstream costs one extra round trip, not a broken session.
*/
import { readFile, stat } from 'node:fs/promises';
import { basename } from 'node:path';
// Refresh this long before the stated expiry, so a token never expires between
// the check and the request.
const EXPIRY_MARGIN_MS = 60_000;
const TIMEOUT_MS = 30_000;
// Above the API's own 20 MB so its answer, not this one, is what a caller
// usually sees; this only stops something absurd being read into memory.
const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
export class LandingClient {
/**
* @param {object} options
@@ -55,7 +62,7 @@ export class LandingClient {
* @returns {Promise<{status: number, body: unknown}>}
*/
async call(operation, args = {}) {
const request = this.buildRequest(operation, args);
const request = await this.buildRequest(operation, args);
if (!operation.requiresAuth) {
if (this.previewToken) request.headers['X-Preview-Token'] = this.previewToken;
@@ -77,7 +84,7 @@ export class LandingClient {
return response;
}
buildRequest(operation, args) {
async buildRequest(operation, args) {
let path = operation.path;
const query = new URLSearchParams();
@@ -100,7 +107,20 @@ export class LandingClient {
const headers = { Accept: 'application/json' };
let body;
if (operation.hasBody && args.body !== undefined) {
const uploads = (operation.files ?? []).filter((field) => args[`${field}_path`]);
if (uploads.length > 0) {
// No Content-Type: fetch writes it, boundary included, from the form.
body = new FormData();
for (const [key, value] of Object.entries(args.body ?? {})) {
body.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
}
for (const field of uploads) {
body.append(field, ...(await this.readUpload(args[`${field}_path`])));
}
} else if (operation.hasBody && args.body !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(args.body);
}
@@ -115,6 +135,22 @@ export class LandingClient {
};
}
/** @returns {Promise<[Blob, string]>} */
async readUpload(path) {
let info;
try {
info = await stat(path);
} catch {
throw new Error(`Cannot read ${path}: no such file`);
}
if (!info.isFile()) throw new Error(`${path} is not a file`);
if (info.size > MAX_UPLOAD_BYTES) throw new Error(`${path} is ${Math.round(info.size / 1048576)} MB; the limit is 20 MB`);
return [new Blob([await readFile(path)]), basename(path)];
}
async send({ url, method, headers, body }) {
const response = await this.fetch(url, {
method,

View File

@@ -30,6 +30,7 @@ const DROPPED_KEYWORDS = new Set([
* @property {string} path Path as documented, e.g. /v1/pages/{page}.
* @property {{name: string, in: string}[]} params
* @property {boolean} hasBody
* @property {string[]} files Multipart fields filled from a local file, read from `<name>_path`.
* @property {boolean} requiresAuth
*
* @typedef {object} Tool
@@ -42,9 +43,13 @@ const DROPPED_KEYWORDS = new Set([
/**
* @param {object} spec The parsed OpenAPI document.
* @param {object} [options]
* @param {boolean} [options.localFiles] Offer uploads from a path on this
* machine. Only true over stdio, where this machine is the caller's own; a
* deployed server would be reading its own disk on a stranger's say-so.
* @returns {Tool[]}
*/
export function buildTools(spec) {
export function buildTools(spec, { localFiles = false } = {}) {
const paths = Object.keys(spec.paths ?? {});
const tools = [];
@@ -58,7 +63,9 @@ export function buildTools(spec) {
if (EXCLUDED_OPERATIONS.has(`${method.toUpperCase()} ${path}`)) continue;
if ((op.tags ?? []).some((tag) => EXCLUDED_TAGS.has(tag))) continue;
tools.push(buildTool(spec, paths, path, method, item, op));
const tool = buildTool(spec, paths, path, method, item, op, localFiles);
if (tool) tools.push(tool);
}
}
@@ -79,7 +86,7 @@ export function buildTools(spec) {
return tools;
}
function buildTool(spec, paths, path, method, item, op) {
function buildTool(spec, paths, path, method, item, op, localFiles) {
const params = mergeParameters(spec, item.parameters, op.parameters)
// Headers are credentials here (preview and ingest secrets), which come
// from the server's configuration, never from the model.
@@ -99,6 +106,32 @@ function buildTool(spec, paths, path, method, item, op) {
}
const bodySchema = op.requestBody?.content?.['application/json']?.schema;
const multipartSchema = op.requestBody?.content?.['multipart/form-data']?.schema;
// A file in a multipart body cannot travel as JSON — as base64 an ordinary
// photo costs hundreds of thousands of tokens — so the model names a path
// and the server reads it. Only where that path is on the caller's machine.
const files = localFiles && multipartSchema
? Object.entries(toJsonSchema(spec, multipartSchema).properties ?? {})
.filter(([, property]) => property.format === 'binary')
.map(([name]) => name)
: [];
// Multipart only, and no way to send a file from here: nothing to offer.
if (!bodySchema && multipartSchema && files.length === 0) return null;
for (const field of files) {
const name = `${field}_path`;
if (name in properties) {
throw new Error(`${method.toUpperCase()} ${path} has a parameter named "${name}", which the file upload needs`);
}
properties[name] = {
type: 'string',
description: `Absolute path to a file on this machine, uploaded as \`${field}\`. Read by the MCP server; use instead of \`body\`.`,
};
}
if (bodySchema) {
if ('body' in properties) {
@@ -114,7 +147,9 @@ function buildTool(spec, paths, path, method, item, op) {
properties.body = { ...body, description: 'JSON request body.' };
if (op.requestBody.required) required.push('body');
// With a file to send instead, the JSON body is the other way in rather
// than a requirement; the API says which one it missed if neither comes.
if (op.requestBody.required && files.length === 0) required.push('body');
}
const security = op.security ?? spec.security ?? [];
@@ -139,6 +174,7 @@ function buildTool(spec, paths, path, method, item, op) {
path,
params: params.map(({ name, in: location }) => ({ name, in: location })),
hasBody: Boolean(bodySchema),
files,
requiresAuth: security.length > 0,
},
};