@withpica/mcp-server
Version:
MCP Server for withPICA — enables AI assistants to interact with your withPICA music catalog
326 lines • 12.9 kB
JavaScript
// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved.
/**
* Fetching a file a client hands a tool by URL (ChatGPT's
* `_meta["openai/fileParams"]`: `{ download_url, file_id, mime_type?,
* file_name? }`, developers.openai.com/apps-sdk/reference).
*
* ⚠️ The URL is caller input. Any MCP client, not only ChatGPT, can put any
* address in the field, and the hosted server fetches it from inside PICA's
* network. So a fetch here goes only to:
* - an https URL on the default port,
* - whose parsed hostname is on PICA_FILE_PARAM_HOSTS (exact, or a suffix
* entry written with a leading dot; never a substring match),
* - connecting only to public addresses. The check runs inside the
* connection's own DNS lookup (`lookup` on the request), so the address
* checked is the address connected to and a rebinding answer cannot slip
* in between a check and the connect,
* - following at most MAX_REDIRECTS redirects, each re-checked as above.
* PICA_FILE_PARAM_HOSTS empty or unset turns the whole path off.
*/
import { lookup as dnsLookup } from "node:dns";
import { request as httpsRequest } from "node:https";
import { isIP } from "node:net";
/** The JSON Schema ChatGPT requires for a file field (all four declared). */
export const FILE_PARAM_SCHEMA = {
type: "object",
properties: {
download_url: {
type: "string",
description: "Temporary download URL for the file, set by the client.",
},
file_id: { type: "string", description: "The client's id for the file." },
mime_type: { type: "string", description: "The file's MIME type." },
file_name: { type: "string", description: "The file's name." },
},
required: ["download_url", "file_id"],
};
export const MAX_REDIRECTS = 3;
/** A refusal whose message is safe to show the user and the agent. */
export class FileParamRefusal extends Error {
constructor(message) {
super(message);
this.name = "FileParamRefusal";
}
}
/**
* The allowed hosts, from a comma-separated list. "files.example.com" is
* that host only; ".example.com" is any host under example.com (not
* example.com itself).
*/
export function allowedFileHosts(raw = process.env.PICA_FILE_PARAM_HOSTS) {
return (raw ?? "")
.split(",")
.map((h) => h.trim().toLowerCase().replace(/\.$/, ""))
.filter((h) => h !== "" && h !== ".");
}
export function hostAllowed(hostname, allowed) {
const host = hostname.toLowerCase().replace(/\.$/, "");
if (host === "" || isIP(host))
return false;
return allowed.some((entry) => entry.startsWith(".") ? host.endsWith(entry) : host === entry);
}
function ipv4Parts(ip) {
const parts = ip.split(".").map(Number);
return parts.length === 4 &&
parts.every((p) => Number.isInteger(p) && p >= 0 && p <= 255)
? parts
: null;
}
function publicIpv4(ip) {
const p = ipv4Parts(ip);
if (!p)
return false;
const [a, b] = p;
if (a === 0 || a === 10 || a === 127)
return false;
if (a === 100 && b >= 64 && b <= 127)
return false; // carrier-grade NAT
if (a === 169 && b === 254)
return false; // link-local, cloud metadata
if (a === 172 && b >= 16 && b <= 31)
return false;
if (a === 192 && b === 168)
return false;
if (a === 192 && b === 0 && (p[2] === 0 || p[2] === 2))
return false;
if (a === 198 && (b === 18 || b === 19))
return false; // benchmarking
if (a === 198 && b === 51 && p[2] === 100)
return false;
if (a === 203 && b === 0 && p[2] === 113)
return false;
if (a >= 224)
return false; // multicast, reserved, broadcast
return true;
}
/** True only for a globally routable unicast address. */
export function isPublicAddress(ip) {
const family = isIP(ip);
if (family === 4)
return publicIpv4(ip);
if (family !== 6)
return false;
const v6 = ip.toLowerCase();
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v6);
if (mapped)
return publicIpv4(mapped[1]);
if (v6 === "::" || v6 === "::1")
return false;
// fc00::/7 unique-local, fe80::/10 link-local, ff00::/8 multicast,
// 64:ff9b::/96 NAT64 and 2001:db8::/32 documentation: all refused.
if (/^f[cd]/.test(v6) || /^fe[89ab]/.test(v6) || v6.startsWith("ff"))
return false;
if (v6.startsWith("64:ff9b:") || v6.startsWith("2001:db8:"))
return false;
return /^[23]/.test(v6); // 2000::/3, global unicast
}
/**
* The connection's DNS lookup: resolves, refuses if ANY answer is not
* public, and hands the socket only checked addresses.
*/
export function publicOnlyLookup(hostname, options, callback) {
const opts = typeof options === "number" ? { family: options } : options;
dnsLookup(hostname, { all: true, family: opts.family ?? 0 }, (err, addresses) => {
if (err)
return callback(err, "");
const list = addresses;
if (list.length === 0 || !list.every((a) => isPublicAddress(a.address)))
return callback(Object.assign(new Error("refused: not a public address"), {
code: "EPICAPRIVATE",
}), "");
if (opts.all)
return callback(null, list);
callback(null, list[0].address, list[0].family);
});
}
/** Checks one URL against the rules above, before any connection. */
export function checkFileUrl(raw, allowed) {
let url;
try {
url = new URL(raw);
}
catch {
throw new FileParamRefusal("the file link is not a valid address.");
}
if (url.protocol !== "https:" || (url.port !== "" && url.port !== "443"))
throw new FileParamRefusal("the file link must be an https address.");
if (url.username || url.password)
throw new FileParamRefusal("the file link must not carry credentials.");
if (!hostAllowed(url.hostname, allowed))
throw new FileParamRefusal("pica only fetches attached files from the chat app's own file storage.");
return url;
}
/**
* Opens a download, following redirects only to allowed hosts. Resolves
* once the status is 200 and the size is known and within `maxBytes`; the
* caller reads `body`. Sends no credentials of PICA's.
*/
export function openFileDownload(raw, opts) {
let url;
try {
url = checkFileUrl(raw, opts.allowed);
}
catch (err) {
return Promise.reject(err);
}
const redirectsLeft = opts.redirectsLeft ?? MAX_REDIRECTS;
return new Promise((resolve, reject) => {
const req = httpsRequest(url, {
method: "GET",
lookup: publicOnlyLookup,
headers: { accept: "*/*" },
timeout: opts.timeoutMs ?? 30_000,
}, (res) => {
const status = res.statusCode ?? 0;
if (status >= 300 && status < 400 && res.headers.location) {
res.resume();
if (redirectsLeft <= 0)
return reject(new FileParamRefusal("the file link redirected too many times."));
let next;
try {
next = new URL(res.headers.location, url).toString();
}
catch {
return reject(new FileParamRefusal("the file link redirected somewhere invalid."));
}
return openFileDownload(next, {
...opts,
redirectsLeft: redirectsLeft - 1,
}).then(resolve, reject);
}
if (status !== 200) {
res.destroy();
return reject(new FileParamRefusal(status === 403 || status === 404 || status === 410
? "the file link has expired. attach the file again."
: `the file could not be fetched (status ${status}).`));
}
const length = Number(res.headers["content-length"]);
if (!Number.isSafeInteger(length) || length <= 0) {
res.destroy();
return reject(new FileParamRefusal("the file's size could not be read."));
}
if (length > opts.maxBytes) {
res.destroy();
return reject(new FileParamRefusal(`the file is too large: ${Math.round(length / 1024 / 1024)}MB. maximum: ${Math.round(opts.maxBytes / 1024 / 1024)}MB.`));
}
const type = res.headers["content-type"];
resolve({
body: res,
contentLength: length,
contentType: typeof type === "string" ? type : null,
});
});
req.on("timeout", () => req.destroy(new FileParamRefusal("the file took too long to answer.")));
req.on("error", (err) => reject(err instanceof FileParamRefusal
? err
: err.code === "EPICAPRIVATE"
? new FileParamRefusal("pica only fetches attached files from the chat app's own file storage.")
: new FileParamRefusal("the file could not be fetched.")));
req.end();
});
}
/** Audio MIME types the upload path accepts, by their leading bytes. */
export function sniffAudioType(head) {
const ascii = (from, to) => String.fromCharCode(...head.subarray(from, to));
if (head.length >= 12 && ascii(0, 4) === "RIFF" && ascii(8, 12) === "WAVE")
return "audio/wav";
if (head.length >= 4 && ascii(0, 4) === "fLaC")
return "audio/flac";
if (head.length >= 4 && ascii(0, 4) === "OggS")
return "audio/ogg";
if (head.length >= 12 &&
ascii(0, 4) === "FORM" &&
(ascii(8, 12) === "AIFF" || ascii(8, 12) === "AIFC"))
return "audio/aiff";
if (head.length >= 4 &&
head[0] === 0x1a &&
head[1] === 0x45 &&
head[2] === 0xdf &&
head[3] === 0xa3)
return "audio/webm";
if (head.length >= 3 && ascii(0, 3) === "ID3")
return "audio/mpeg";
if (head.length >= 2 && head[0] === 0xff && (head[1] & 0xe0) === 0xe0)
return "audio/mpeg";
return null;
}
/**
* Reads the first bytes of a download (at least `min`, unless the file is
* shorter) and returns them with an iterator for the rest, so a type check
* can run before anything is sent on.
*/
export async function readHead(body, min = 16) {
const rest = body[Symbol.asyncIterator]();
const chunks = [];
let size = 0;
while (size < min) {
const next = await rest.next();
if (next.done)
break;
chunks.push(next.value);
size += next.value.length;
}
return { head: Buffer.concat(chunks), rest };
}
/**
* Streams a download to a signed PUT URL (the storage URL
* pica_audio_presigned_upload returns), sending exactly `contentLength`
* bytes: a body longer or shorter than the size it declared is refused,
* not stored.
*/
export async function putToSignedUrl(input) {
const { contentLength } = input;
async function* bytes() {
let seen = input.head.length;
if (seen > contentLength)
throw new FileParamRefusal("the file is larger than its stated size.");
if (seen > 0)
yield input.head;
for (;;) {
const next = await input.rest.next();
if (next.done)
break;
seen += next.value.length;
if (seen > contentLength)
throw new FileParamRefusal("the file is larger than its stated size.");
yield next.value;
}
if (seen !== contentLength)
throw new FileParamRefusal("the file ended before its stated size.");
}
const target = new URL(input.uploadUrl);
const { request } = target.protocol === "http:"
? await import("node:http")
: await import("node:https");
await new Promise((resolve, reject) => {
const req = request(target, {
method: "PUT",
headers: {
"content-type": input.contentType,
"content-length": String(contentLength),
},
}, (res) => {
res.resume();
const status = res.statusCode ?? 0;
if (status >= 200 && status < 300)
resolve();
else
reject(new Error(`storage refused the upload (status ${status})`));
});
req.on("error", reject);
(async () => {
try {
for await (const chunk of bytes()) {
if (!req.write(chunk))
await new Promise((r) => req.once("drain", () => r()));
}
req.end();
}
catch (err) {
req.destroy(err);
reject(err);
}
})();
});
}
//# sourceMappingURL=file-param-fetch.js.map