mirror of
https://github.com/Dasemu/gemini-media-mcp.git
synced 2026-11-26 23:36:09 +00:00
Initial commit
This commit is contained in:
commit
85fbc8b05a
27 files changed
+4465
No files matched your search
@@ -0,0 +1,118 @@
|
||||
import type { GenerationReferenceImage, InlineReferenceImage, ModelSpec, ReferenceImage, ToolArgument } from "./types.js";
|
||||
|
||||
export function normalizeArguments(model: ModelSpec, input: ToolArgument[]): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
const specs = new Map(model.arguments.map((argument) => [argument.name, argument]));
|
||||
|
||||
for (const argument of input) {
|
||||
if (!specs.has(argument.name)) throw new Error(`Unknown argument '${argument.name}' for model ${model.name}`);
|
||||
if (Object.hasOwn(result, argument.name)) throw new Error(`Duplicate argument '${argument.name}'`);
|
||||
result[argument.name] = argument.value;
|
||||
}
|
||||
|
||||
for (const spec of model.arguments) {
|
||||
if (!Object.hasOwn(result, spec.name) && spec.default !== undefined) result[spec.name] = spec.default;
|
||||
if (spec.required && !Object.hasOwn(result, spec.name)) throw new Error(`Missing required argument '${spec.name}'`);
|
||||
|
||||
const value = result[spec.name];
|
||||
if (value === undefined) continue;
|
||||
if (spec.allowedValues && !spec.allowedValues.some((allowed) => allowed === value)) {
|
||||
throw new Error(`Invalid '${spec.name}': ${JSON.stringify(value)}. Allowed: ${spec.allowedValues.map(String).join(", ")}`);
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
if (spec.minimum !== undefined && value < spec.minimum) throw new Error(`'${spec.name}' must be >= ${spec.minimum}`);
|
||||
if (spec.maximum !== undefined && value > spec.maximum) throw new Error(`'${spec.name}' must be <= ${spec.maximum}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof result.prompt !== "string" || result.prompt.trim().length === 0) throw new Error("'prompt' must be a non-empty string");
|
||||
if (String(result.prompt).length > 8000) throw new Error("'prompt' must be at most 8000 characters");
|
||||
|
||||
if (model.type === "image" && result.reference_images !== undefined) {
|
||||
result.reference_images = normalizeReferenceImages(model, result.reference_images);
|
||||
}
|
||||
|
||||
if (model.type === "video") {
|
||||
const resolution = String(result.resolution);
|
||||
const duration = Number(result.duration_seconds);
|
||||
if ((resolution === "1080p" || resolution === "4k") && duration !== 8) {
|
||||
throw new Error(`${resolution} video generation requires duration_seconds=8`);
|
||||
}
|
||||
if (result.with_audio !== true) throw new Error("Veo 3.1 always generates native audio; with_audio=false is not supported");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizeReferenceImages(model: ModelSpec, input: unknown): ReferenceImage[] {
|
||||
if (!Array.isArray(input)) throw new Error("'reference_images' must be an array of {base64, mime_type} or {generation_id, index?} objects");
|
||||
const spec = model.arguments.find((argument) => argument.name === "reference_images");
|
||||
const maximumItems = spec?.maximumItems ?? 1;
|
||||
if (input.length < 1 || input.length > maximumItems) {
|
||||
throw new Error(`'reference_images' must contain between 1 and ${maximumItems} images for ${model.name}`);
|
||||
}
|
||||
|
||||
const maxPerImageBytes = 20 * 1024 * 1024;
|
||||
const maxAggregateBytes = Math.floor((Number(process.env.MAX_REFERENCE_INPUT_MB) || 25) * 1024 * 1024);
|
||||
let aggregateBytes = 0;
|
||||
const normalized: ReferenceImage[] = [];
|
||||
|
||||
for (const [index, value] of input.entries()) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`reference_images[${index}] must be an object`);
|
||||
const record = value as Record<string, unknown>;
|
||||
const hasInline = Object.hasOwn(record, "base64") || Object.hasOwn(record, "mime_type");
|
||||
const hasGeneration = Object.hasOwn(record, "generation_id") || Object.hasOwn(record, "index");
|
||||
if (hasInline && hasGeneration) throw new Error(`reference_images[${index}] must use either {base64, mime_type} or {generation_id, index?}, not both`);
|
||||
|
||||
if (hasGeneration) {
|
||||
if (typeof record.generation_id !== "string" || !isUuid(record.generation_id)) {
|
||||
throw new Error(`reference_images[${index}].generation_id must be a valid UUID`);
|
||||
}
|
||||
const outputIndex = record.index ?? 0;
|
||||
if (!Number.isInteger(outputIndex) || Number(outputIndex) < 0) {
|
||||
throw new Error(`reference_images[${index}].index must be a non-negative integer`);
|
||||
}
|
||||
normalized.push({ generation_id: record.generation_id, index: Number(outputIndex) } satisfies GenerationReferenceImage);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rawBase64 = record.base64;
|
||||
let mimeType = record.mime_type;
|
||||
if (typeof rawBase64 !== "string" || rawBase64.length === 0) throw new Error(`reference_images[${index}].base64 must be a non-empty string`);
|
||||
let base64: string = rawBase64;
|
||||
|
||||
const dataUri = base64.match(/^data:(image\/(?:png|jpeg|webp));base64,(.+)$/s);
|
||||
if (dataUri) {
|
||||
mimeType ??= dataUri[1];
|
||||
base64 = dataUri[2];
|
||||
}
|
||||
base64 = base64.replace(/\s/g, "");
|
||||
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64) || base64.length % 4 !== 0) {
|
||||
throw new Error(`reference_images[${index}].base64 is not valid standard base64`);
|
||||
}
|
||||
if (mimeType !== "image/png" && mimeType !== "image/jpeg" && mimeType !== "image/webp") {
|
||||
throw new Error(`reference_images[${index}].mime_type must be image/png, image/jpeg, or image/webp`);
|
||||
}
|
||||
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
const decodedBytes = Math.floor(base64.length * 3 / 4) - padding;
|
||||
if (decodedBytes <= 0 || decodedBytes > maxPerImageBytes) throw new Error(`reference_images[${index}] exceeds the 20 MiB per-image limit`);
|
||||
aggregateBytes += decodedBytes;
|
||||
if (aggregateBytes > maxAggregateBytes) throw new Error(`reference_images exceed the aggregate MAX_REFERENCE_INPUT_MB limit (${maxAggregateBytes} bytes)`);
|
||||
|
||||
const header = Buffer.from(base64.slice(0, 24), "base64");
|
||||
if (!mimeMatchesHeader(mimeType, header)) throw new Error(`reference_images[${index}] content does not match ${mimeType}`);
|
||||
normalized.push({ base64, mime_type: mimeType } satisfies InlineReferenceImage);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function mimeMatchesHeader(mimeType: InlineReferenceImage["mime_type"], header: Buffer): boolean {
|
||||
if (mimeType === "image/png") return header.length >= 8 && header.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
|
||||
if (mimeType === "image/jpeg") return header.length >= 3 && header[0] === 0xff && header[1] === 0xd8 && header[2] === 0xff;
|
||||
return header.length >= 12 && header.subarray(0, 4).toString("ascii") === "RIFF" && header.subarray(8, 12).toString("ascii") === "WEBP";
|
||||
}
|
||||
|
||||
function isUuid(value: string): boolean {
|
||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import type { ModelSpec } from "./types.js";
|
||||
|
||||
export const PRICING_REFERENCE_DATE = "2026-08-14";
|
||||
export const PRICING_SOURCE = "https://ai.google.dev/gemini-api/docs/pricing";
|
||||
|
||||
const commonImageRatios = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
|
||||
const extendedFlashRatios = ["1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9"];
|
||||
|
||||
function imageArguments(resolutions: string[], ratios = commonImageRatios, maximumReferenceImages = 14): ModelSpec["arguments"] {
|
||||
return [
|
||||
{ name: "prompt", required: true, description: "Detailed text prompt for the image." },
|
||||
{
|
||||
name: "reference_images",
|
||||
required: false,
|
||||
description: "Reference images. Prefer {generation_id,index?} to reuse a completed server-side image without moving base64 through the client; inline {base64,mime_type} remains supported.",
|
||||
format: 'array<({generation_id:uuid,index?:integer=0}|{base64:string,mime_type:"image/png"|"image/jpeg"|"image/webp"})>',
|
||||
maximumItems: maximumReferenceImages,
|
||||
},
|
||||
{ name: "resolution", required: false, description: "Requested output image size.", allowedValues: resolutions, default: resolutions.includes("1K") ? "1K" : resolutions[0] },
|
||||
{ name: "aspect_ratio", required: false, description: "Output image aspect ratio.", allowedValues: ratios, default: "1:1" },
|
||||
{ name: "image_count", required: false, description: "Number of independent images. The server makes one provider request per image.", allowedValues: [1, 2, 3, 4], default: 1 },
|
||||
];
|
||||
}
|
||||
|
||||
function videoArguments(resolutions: string[]): ModelSpec["arguments"] {
|
||||
return [
|
||||
{ name: "prompt", required: true, description: "Video prompt; may include dialogue, sound and ambience cues." },
|
||||
{ name: "resolution", required: false, description: "Output resolution. 1080p and 4k require an 8 second duration.", allowedValues: resolutions, default: "720p" },
|
||||
{ name: "aspect_ratio", required: false, description: "Output orientation.", allowedValues: ["16:9", "9:16"], default: "16:9" },
|
||||
{ name: "duration_seconds", required: false, description: "Generated clip duration.", allowedValues: [4, 6, 8], default: 8 },
|
||||
{ name: "with_audio", required: false, description: "Veo 3.1 native audio is always enabled; false is unsupported.", allowedValues: [true], default: true },
|
||||
{ name: "seed", required: false, description: "Optional seed (improves repeatability but does not guarantee determinism).", minimum: 0, maximum: 2147483647 },
|
||||
];
|
||||
}
|
||||
|
||||
export const MODEL_CATALOG: ModelSpec[] = [
|
||||
{
|
||||
name: "gemini-3-pro-image",
|
||||
aliases: ["nano-banana-pro"],
|
||||
description: "Nano Banana Pro; professional assets, complex instructions and high-quality text rendering up to 4K.",
|
||||
type: "image",
|
||||
canonicalApiModel: "gemini-3-pro-image",
|
||||
arguments: imageArguments(["1K", "2K", "4K"], commonImageRatios, 14),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "1K": 0.134, "2K": 0.134, "4K": 0.24 }, source: PRICING_SOURCE },
|
||||
},
|
||||
{
|
||||
name: "gemini-3.1-flash-image",
|
||||
aliases: ["nano-banana-2"],
|
||||
description: "Nano Banana 2; recommended balance of quality, latency and cost, with 0.5K through 4K output.",
|
||||
type: "image",
|
||||
canonicalApiModel: "gemini-3.1-flash-image",
|
||||
arguments: imageArguments(["0.5K", "1K", "2K", "4K"], extendedFlashRatios, 14),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "0.5K": 0.045, "1K": 0.067, "2K": 0.101, "4K": 0.151 }, source: PRICING_SOURCE },
|
||||
},
|
||||
{
|
||||
name: "gemini-3.1-flash-lite-image",
|
||||
aliases: ["nano-banana-2-lite"],
|
||||
description: "Nano Banana 2 Lite; lowest-latency and lowest-cost 1K image generation.",
|
||||
type: "image",
|
||||
canonicalApiModel: "gemini-3.1-flash-lite-image",
|
||||
arguments: imageArguments(["1K"], commonImageRatios, 14),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "1K": 0.0336 }, source: PRICING_SOURCE },
|
||||
},
|
||||
{
|
||||
name: "gemini-2.5-flash-image",
|
||||
aliases: ["nano-banana"],
|
||||
description: "Original Nano Banana; efficient fixed-resolution 1K image generation.",
|
||||
type: "image",
|
||||
canonicalApiModel: "gemini-2.5-flash-image",
|
||||
arguments: imageArguments(["1K"], commonImageRatios, 3),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per output image (text input/tokens excluded)", rates: { "1K": 0.039 }, source: PRICING_SOURCE },
|
||||
},
|
||||
{
|
||||
name: "veo-3.1",
|
||||
aliases: ["veo-3.1-standard"],
|
||||
description: "Veo 3.1 Preview standard; highest-quality video with native audio, up to 4K.",
|
||||
type: "video",
|
||||
canonicalApiModel: "veo-3.1-generate-preview",
|
||||
arguments: videoArguments(["720p", "1080p", "4k"]),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per generated second, with audio", rates: { "720p": 0.4, "1080p": 0.4, "4k": 0.6 }, source: PRICING_SOURCE },
|
||||
},
|
||||
{
|
||||
name: "veo-3.1-fast",
|
||||
aliases: [],
|
||||
description: "Veo 3.1 Fast Preview; optimized for fast, high-throughput social and advertising workflows.",
|
||||
type: "video",
|
||||
canonicalApiModel: "veo-3.1-fast-generate-preview",
|
||||
arguments: videoArguments(["720p", "1080p", "4k"]),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per generated second, with audio", rates: { "720p": 0.1, "1080p": 0.12, "4k": 0.3 }, source: PRICING_SOURCE },
|
||||
},
|
||||
{
|
||||
name: "veo-3.1-lite",
|
||||
aliases: [],
|
||||
description: "Veo 3.1 Lite Preview; lowest-cost native-audio video generation at 720p or 1080p.",
|
||||
type: "video",
|
||||
canonicalApiModel: "veo-3.1-lite-generate-preview",
|
||||
arguments: videoArguments(["720p", "1080p"]),
|
||||
pricing: { currency: "USD", referenceDate: PRICING_REFERENCE_DATE, basis: "per generated second, with audio", rates: { "720p": 0.05, "1080p": 0.08 }, source: PRICING_SOURCE },
|
||||
},
|
||||
];
|
||||
|
||||
export function resolveModel(requested: string, type?: "image" | "video"): ModelSpec {
|
||||
const normalized = requested.trim().toLowerCase();
|
||||
const model = MODEL_CATALOG.find((item) =>
|
||||
(item.name.toLowerCase() === normalized || item.aliases.some((alias) => alias.toLowerCase() === normalized)) &&
|
||||
(!type || item.type === type),
|
||||
);
|
||||
if (!model) throw new Error(`Unsupported ${type ?? "generation"} model: ${requested}`);
|
||||
return model;
|
||||
}
|
||||
|
||||
export function estimateCost(model: ModelSpec, args: Record<string, unknown>): number {
|
||||
if (model.type === "image") {
|
||||
const resolution = String(args.resolution ?? "1K");
|
||||
const count = Number(args.image_count ?? 1);
|
||||
return roundUsd((model.pricing.rates[resolution] ?? 0) * count);
|
||||
}
|
||||
const resolution = String(args.resolution ?? "720p");
|
||||
const seconds = Number(args.duration_seconds ?? 8);
|
||||
return roundUsd((model.pricing.rates[resolution] ?? 0) * seconds);
|
||||
}
|
||||
|
||||
function roundUsd(value: number): number {
|
||||
return Math.round(value * 10000) / 10000;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtemp, rm, unlink } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { mediaDir, registerDownloaded } from "./media.js";
|
||||
import type { StoredOutput, VideoOverlay } from "./types.js";
|
||||
|
||||
const commandTimeoutMs = 5 * 60 * 1000;
|
||||
const maxDiagnosticBytes = 256 * 1024;
|
||||
|
||||
interface VideoMetadata {
|
||||
durationSeconds: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export async function composeVideoOverlay(
|
||||
generationId: string,
|
||||
baseOutput: StoredOutput,
|
||||
overlays: VideoOverlay[],
|
||||
): Promise<StoredOutput[]> {
|
||||
const workDir = await mkdtemp(path.join(os.tmpdir(), "zenvairo-compose-"));
|
||||
const temporaryOutput = path.join(mediaDir, `${generationId}-0.download`);
|
||||
try {
|
||||
const metadata = await probeVideo(baseOutput.path);
|
||||
validateComposition(metadata, overlays);
|
||||
const cards: string[] = [];
|
||||
for (const [index, overlay] of overlays.entries()) {
|
||||
const outputPath = path.join(workDir, `card-${index}.png`);
|
||||
await run(process.env.PYTHON_BIN || "python3", [
|
||||
process.env.OVERLAY_CARD_SCRIPT || "/opt/gemini-veo-mcp/scripts/make_overlay_card.py",
|
||||
JSON.stringify({ text: overlay.text, kicker: overlay.kicker, style: overlay.style, out: outputPath }),
|
||||
]);
|
||||
cards.push(outputPath);
|
||||
}
|
||||
|
||||
const ffmpegArgs = buildFfmpegArguments(baseOutput.path, cards, temporaryOutput, metadata, overlays);
|
||||
await run(process.env.FFMPEG_BIN || "ffmpeg", ffmpegArgs);
|
||||
return [await registerDownloaded(generationId, 0, temporaryOutput, "video/mp4")];
|
||||
} catch (error) {
|
||||
await unlink(temporaryOutput).catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
await rm(workDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function buildFfmpegFilter(metadata: Pick<VideoMetadata, "width" | "height">, overlays: VideoOverlay[]): string {
|
||||
const chains: string[] = ["[0:v]setpts=PTS-STARTPTS[base]"];
|
||||
overlays.forEach((overlay, index) => {
|
||||
const fade = Math.min(0.25, overlay.duration / 3);
|
||||
const fadeOutStart = overlay.duration - fade;
|
||||
chains.push(
|
||||
`[${index + 1}:v]format=rgba,scale=${metadata.width}:${metadata.height},` +
|
||||
`trim=duration=${decimal(overlay.duration)},setpts=PTS-STARTPTS,` +
|
||||
`fade=t=in:st=0:d=${decimal(fade)}:alpha=1,` +
|
||||
`fade=t=out:st=${decimal(fadeOutStart)}:d=${decimal(fade)}:alpha=1,` +
|
||||
`setpts=PTS+${decimal(overlay.start_time)}/TB[overlay${index}]`,
|
||||
);
|
||||
const input = index === 0 ? "base" : `v${index}`;
|
||||
chains.push(
|
||||
`[${input}][overlay${index}]overlay=0:0:eof_action=pass:shortest=0:format=auto[v${index + 1}]`,
|
||||
);
|
||||
});
|
||||
return chains.join(";");
|
||||
}
|
||||
|
||||
function buildFfmpegArguments(
|
||||
basePath: string,
|
||||
cards: string[],
|
||||
outputPath: string,
|
||||
metadata: VideoMetadata,
|
||||
overlays: VideoOverlay[],
|
||||
): string[] {
|
||||
const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", basePath];
|
||||
for (const card of cards) args.push("-loop", "1", "-framerate", "30", "-i", card);
|
||||
args.push(
|
||||
"-filter_complex", buildFfmpegFilter(metadata, overlays),
|
||||
"-map", `[v${overlays.length}]`,
|
||||
"-map", "0:a?",
|
||||
"-map_metadata", "0",
|
||||
"-c:v", "libx264",
|
||||
"-preset", "medium",
|
||||
"-crf", "23",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-c:a", "copy",
|
||||
"-movflags", "+faststart",
|
||||
"-shortest",
|
||||
"-f", "mp4",
|
||||
outputPath,
|
||||
);
|
||||
return args;
|
||||
}
|
||||
|
||||
async function probeVideo(inputPath: string): Promise<VideoMetadata> {
|
||||
const result = await run(process.env.FFPROBE_BIN || "ffprobe", [
|
||||
"-v", "error",
|
||||
"-select_streams", "v:0",
|
||||
"-show_entries", "stream=width,height:format=duration",
|
||||
"-of", "json",
|
||||
inputPath,
|
||||
]);
|
||||
let parsed: { streams?: Array<{ width?: number; height?: number }>; format?: { duration?: string } };
|
||||
try {
|
||||
parsed = JSON.parse(result.stdout);
|
||||
} catch {
|
||||
throw new Error("COMPOSE_INVALID_BASE_VIDEO: ffprobe returned invalid metadata");
|
||||
}
|
||||
const width = Number(parsed.streams?.[0]?.width);
|
||||
const height = Number(parsed.streams?.[0]?.height);
|
||||
const durationSeconds = Number(parsed.format?.duration);
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
|
||||
throw new Error("COMPOSE_INVALID_BASE_VIDEO: missing duration or dimensions");
|
||||
}
|
||||
return { width, height, durationSeconds };
|
||||
}
|
||||
|
||||
function validateComposition(metadata: VideoMetadata, overlays: VideoOverlay[]): void {
|
||||
const ratio = metadata.width / metadata.height;
|
||||
if (Math.abs(ratio - 9 / 16) > 0.02) {
|
||||
throw new Error(
|
||||
`COMPOSE_BASE_ASPECT_RATIO_UNSUPPORTED: expected a vertical 9:16 video, received ${metadata.width}x${metadata.height}`,
|
||||
);
|
||||
}
|
||||
for (const [index, overlay] of overlays.entries()) {
|
||||
if (overlay.start_time >= metadata.durationSeconds) {
|
||||
throw new Error(
|
||||
`COMPOSE_TIMING_OUT_OF_RANGE: overlays[${index}].start_time ${overlay.start_time} is outside the ${decimal(metadata.durationSeconds)}s base video`,
|
||||
);
|
||||
}
|
||||
if (overlay.start_time + overlay.duration > metadata.durationSeconds + 0.05) {
|
||||
throw new Error(
|
||||
`COMPOSE_TIMING_OUT_OF_RANGE: overlays[${index}] ends at ${decimal(overlay.start_time + overlay.duration)}s, after the ${decimal(metadata.durationSeconds)}s base video`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function run(command: string, args: string[]): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, { shell: false, stdio: ["ignore", "pipe", "pipe"] });
|
||||
const stdout: Buffer[] = [];
|
||||
const stderr: Buffer[] = [];
|
||||
let capturedBytes = 0;
|
||||
const capture = (target: Buffer[], chunk: Buffer) => {
|
||||
if (capturedBytes >= maxDiagnosticBytes) return;
|
||||
const remaining = maxDiagnosticBytes - capturedBytes;
|
||||
target.push(chunk.subarray(0, remaining));
|
||||
capturedBytes += Math.min(chunk.length, remaining);
|
||||
};
|
||||
child.stdout.on("data", (chunk: Buffer) => capture(stdout, chunk));
|
||||
child.stderr.on("data", (chunk: Buffer) => capture(stderr, chunk));
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), commandTimeoutMs);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(new Error(`COMPOSE_DEPENDENCY_ERROR: failed to start ${path.basename(command)}: ${error.message}`));
|
||||
});
|
||||
child.once("close", (code, signal) => {
|
||||
clearTimeout(timeout);
|
||||
const output = { stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") };
|
||||
if (code === 0) resolve(output);
|
||||
else reject(new Error(`COMPOSE_COMMAND_FAILED: ${path.basename(command)} exited with ${code ?? signal}: ${output.stderr.slice(-2000)}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function decimal(value: number): string {
|
||||
return Number(value.toFixed(3)).toString();
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import "dotenv/config";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import express from "express";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { JobManager } from "./jobs.js";
|
||||
import { audit, auditError } from "./log.js";
|
||||
import { cleanupOrphanMedia, ensureMediaDir, mediaDir, migrateLegacyOutputs, resolvePublicOutput } from "./media.js";
|
||||
import { publicMediaSigningConfigured, validatePublicMediaSignature } from "./public-media.js";
|
||||
import { registerTools } from "./tools.js";
|
||||
|
||||
const jobs = new JobManager();
|
||||
const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168;
|
||||
await ensureMediaDir();
|
||||
const orphanCleanup = async () => {
|
||||
const removed = await cleanupOrphanMedia(retentionHours);
|
||||
if (removed > 0) audit("orphan_media_expired", { removed, retentionHours });
|
||||
};
|
||||
await orphanCleanup();
|
||||
const migratedLegacyJobs = await migrateLegacyOutputs();
|
||||
if (migratedLegacyJobs > 0) audit("legacy_outputs_migrated", { count: migratedLegacyJobs });
|
||||
await jobs.restoreCompletedJobs();
|
||||
jobs.startCleanup(retentionHours);
|
||||
const orphanCleanupInterval = setInterval(() => void orphanCleanup().catch((error) => auditError("orphan_media_cleanup_failed", error)), 15 * 60 * 1000);
|
||||
orphanCleanupInterval.unref();
|
||||
|
||||
function buildServer(): McpServer {
|
||||
const server = new McpServer({ name: "zenvairo-google-media", version: "1.0.0" });
|
||||
registerTools(server, jobs);
|
||||
return server;
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.disable("x-powered-by");
|
||||
app.use(express.json({ limit: `${Number(process.env.MAX_MCP_REQUEST_MB) || 40}mb` }));
|
||||
|
||||
app.get("/public-media/:filename", async (req, res) => {
|
||||
const started = Date.now();
|
||||
const validation = validatePublicMediaSignature(req.params.filename, req.query.expires, req.query.signature);
|
||||
if (!validation.valid) {
|
||||
const status = validation.reason === "expired" ? 410 : 403;
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
res.status(status).json({ error: validation.reason === "expired" ? "url_expired" : "invalid_signature" });
|
||||
return;
|
||||
}
|
||||
const output = await resolvePublicOutput(req.params.filename);
|
||||
if (!output) {
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
res.setHeader("Content-Type", output.mimeType);
|
||||
res.setHeader("Content-Length", String(output.sizeBytes));
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
return res.sendFile(output.filename, { root: mediaDir, dotfiles: "deny", maxAge: 0 }, (error) => {
|
||||
if (error && !res.headersSent) res.status((error as Error & { statusCode?: number }).statusCode || 404).json({ error: "not_found" });
|
||||
audit("public_media_download", { filename: output.filename, sizeBytes: output.sizeBytes, durationMs: Date.now() - started, success: !error });
|
||||
});
|
||||
});
|
||||
|
||||
app.use(authenticate);
|
||||
|
||||
app.get("/health", (_req, res) => res.json({ ok: true, service: "zenvairo-google-media", googleCredentialsConfigured: Boolean(process.env.GEMINI_API_KEY), publicMediaSigningConfigured: publicMediaSigningConfigured() }));
|
||||
app.get("/media/:filename", (req, res) => {
|
||||
if (!/^[0-9a-f-]{36}-\d+\.(png|jpg|mp4)$/.test(req.params.filename)) return res.status(404).json({ error: "not_found" });
|
||||
return res.sendFile(req.params.filename, { root: mediaDir, dotfiles: "deny", maxAge: 0 }, (error) => {
|
||||
if (error && !res.headersSent) res.status((error as Error & { statusCode?: number }).statusCode || 404).json({ error: "not_found" });
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/mcp", async (req, res) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const server = buildServer();
|
||||
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
||||
res.on("close", () => { void transport.close(); void server.close(); });
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
audit("mcp_request", { method: req.body?.method, durationMs: Date.now() - started, statusCode: res.statusCode });
|
||||
} catch (error) {
|
||||
auditError("mcp_request_failed", error, { method: req.body?.method, durationMs: Date.now() - started });
|
||||
if (!res.headersSent) res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: req.body?.id ?? null });
|
||||
}
|
||||
});
|
||||
app.get("/mcp", (_req, res) => res.status(405).json({ error: "Method not allowed; this stateless Streamable HTTP server accepts POST /mcp." }));
|
||||
app.delete("/mcp", (_req, res) => res.status(405).json({ error: "Method not allowed; this stateless Streamable HTTP server accepts POST /mcp." }));
|
||||
|
||||
const port = Number(process.env.PORT) || 8087;
|
||||
const host = process.env.HOST || "127.0.0.1";
|
||||
app.listen(port, host, () => audit("server_started", { host, port, endpoint: "/mcp", mediaRetentionHours: retentionHours }));
|
||||
|
||||
function authenticate(req: express.Request, res: express.Response, next: express.NextFunction): void {
|
||||
const required = process.env.MCP_SERVER_TOKEN;
|
||||
if (!required) {
|
||||
res.status(503).json({ error: "server_not_configured", message: "MCP_SERVER_TOKEN is required" });
|
||||
return;
|
||||
}
|
||||
const authorization = req.get("authorization") || "";
|
||||
const bearer = authorization.startsWith("Bearer ") ? authorization.slice(7) : "";
|
||||
const injected = req.get("x-mcp-server-token") || "";
|
||||
if (!safeEqual(required, bearer) && !safeEqual(required, injected)) {
|
||||
res.setHeader("WWW-Authenticate", "Bearer");
|
||||
res.status(401).json({ error: "unauthorized" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function safeEqual(expected: string, actual: string): boolean {
|
||||
const a = Buffer.from(expected); const b = Buffer.from(actual);
|
||||
return a.length === b.length && timingSafeEqual(a, b);
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { estimateCost, resolveModel } from "./catalog.js";
|
||||
import { audit, auditError, providerStatus } from "./log.js";
|
||||
import { generationWasPurged, loadPersistedJob, loadPersistedJobs, outputExists, persistCompletedJob, purgeGeneration } from "./media.js";
|
||||
import { composeVideoOverlay } from "./compositor.js";
|
||||
import { GoogleMediaProvider } from "./provider.js";
|
||||
import type { GenerationJob, InlineReferenceImage, JobKind, ReferenceImage, VideoOverlay } from "./types.js";
|
||||
|
||||
export class JobManager {
|
||||
private readonly jobs = new Map<string, GenerationJob>();
|
||||
private estimatedSubmittedUsd = 0;
|
||||
private estimatedCompletedUsd = 0;
|
||||
|
||||
constructor(private readonly provider = new GoogleMediaProvider()) {}
|
||||
|
||||
submit(kind: JobKind, requestedModel: string, args: Record<string, unknown>, taskTraceId?: string): GenerationJob {
|
||||
const model = resolveModel(requestedModel, kind);
|
||||
const now = new Date().toISOString();
|
||||
const job: GenerationJob = {
|
||||
generationId: randomUUID(), taskTraceId, kind, model: model.name, canonicalModel: model.canonicalApiModel,
|
||||
arguments: args, estimatedCostUsd: estimateCost(model, args), status: "QUEUING", createdAt: now, updatedAt: now,
|
||||
};
|
||||
this.jobs.set(job.generationId, job);
|
||||
this.estimatedSubmittedUsd += job.estimatedCostUsd;
|
||||
audit("generation_queued", {
|
||||
generationId: job.generationId, taskTraceId, kind, model: job.model,
|
||||
referenceImageCount: Array.isArray(args.reference_images) ? args.reference_images.length : 0,
|
||||
estimatedCostUsd: job.estimatedCostUsd,
|
||||
});
|
||||
setImmediate(() => void (kind === "image" ? this.runImage(job) : this.runVideoSubmit(job)));
|
||||
return job;
|
||||
}
|
||||
|
||||
get(generationId: string): GenerationJob | undefined { return this.jobs.get(generationId); }
|
||||
|
||||
async submitComposition(baseGenerationId: string, overlays: VideoOverlay[], taskTraceId?: string): Promise<GenerationJob> {
|
||||
let base = this.jobs.get(baseGenerationId);
|
||||
if (!base) {
|
||||
base = await loadPersistedJob(baseGenerationId);
|
||||
if (base) this.jobs.set(base.generationId, base);
|
||||
}
|
||||
if (!base) {
|
||||
const code = await generationWasPurged(baseGenerationId) ? "COMPOSE_BASE_EXPIRED" : "COMPOSE_BASE_NOT_FOUND";
|
||||
throw new Error(`${code}: base_generation_id ${baseGenerationId} is unavailable`);
|
||||
}
|
||||
if (base.kind !== "video") throw new Error(`COMPOSE_BASE_IS_NOT_VIDEO: base_generation_id ${baseGenerationId} is an image generation`);
|
||||
if (base.status !== "COMPLETED" || !base.outputs) {
|
||||
throw new Error(`COMPOSE_BASE_NOT_COMPLETED: base_generation_id ${baseGenerationId} has status ${base.status}; wait for COMPLETED`);
|
||||
}
|
||||
const baseOutput = base.outputs.find((output) => output.index === 0 && output.mimeType === "video/mp4");
|
||||
if (!baseOutput) throw new Error(`COMPOSE_BASE_OUTPUT_MISSING: base_generation_id ${baseGenerationId} has no video/mp4 output at index 0`);
|
||||
if (!(await outputExists(baseOutput))) throw new Error(`COMPOSE_BASE_EXPIRED: base_generation_id ${baseGenerationId} media has expired or was purged`);
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const job: GenerationJob = {
|
||||
generationId: randomUUID(), taskTraceId, kind: "video", model: "ffmpeg-overlay", canonicalModel: "local-ffmpeg-overlay-v1",
|
||||
arguments: { base_generation_id: baseGenerationId, overlays }, estimatedCostUsd: 0, status: "QUEUING", createdAt: now, updatedAt: now,
|
||||
};
|
||||
this.jobs.set(job.generationId, job);
|
||||
audit("composition_queued", { generationId: job.generationId, taskTraceId, baseGenerationId, overlayCount: overlays.length });
|
||||
setImmediate(() => void this.runComposition(job, baseOutput, overlays));
|
||||
return job;
|
||||
}
|
||||
|
||||
async restoreCompletedJobs(): Promise<number> {
|
||||
const restored = await loadPersistedJobs();
|
||||
for (const job of restored) {
|
||||
this.jobs.set(job.generationId, job);
|
||||
this.estimatedCompletedUsd += job.estimatedCostUsd;
|
||||
}
|
||||
if (restored.length > 0) audit("completed_jobs_restored", { count: restored.length });
|
||||
return restored.length;
|
||||
}
|
||||
|
||||
async resolveImageReferences(args: Record<string, unknown>): Promise<Record<string, unknown>> {
|
||||
const references = args.reference_images as ReferenceImage[] | undefined;
|
||||
if (!references) return args;
|
||||
const resolved: InlineReferenceImage[] = [];
|
||||
const maxAggregateBytes = Math.floor((Number(process.env.MAX_REFERENCE_INPUT_MB) || 25) * 1024 * 1024);
|
||||
let aggregateBytes = 0;
|
||||
|
||||
for (const [position, reference] of references.entries()) {
|
||||
if ("base64" in reference) {
|
||||
aggregateBytes += decodedBase64Size(reference.base64);
|
||||
resolved.push(reference);
|
||||
} else {
|
||||
let source = this.jobs.get(reference.generation_id);
|
||||
if (!source) {
|
||||
source = await loadPersistedJob(reference.generation_id);
|
||||
if (source) this.jobs.set(source.generationId, source);
|
||||
}
|
||||
if (!source) {
|
||||
if (await generationWasPurged(reference.generation_id)) {
|
||||
throw new Error(`REFERENCE_GENERATION_EXPIRED: reference_images[${position}] generation_id ${reference.generation_id} has expired or was purged by retention`);
|
||||
}
|
||||
throw new Error(`REFERENCE_GENERATION_NOT_FOUND: reference_images[${position}] generation_id ${reference.generation_id} does not exist`);
|
||||
}
|
||||
if (source.kind === "video") {
|
||||
throw new Error(`REFERENCE_IS_VIDEO: reference_images[${position}] generation_id ${reference.generation_id} is a video generation and cannot be used as an image reference`);
|
||||
}
|
||||
if (source.status !== "COMPLETED" || !source.outputs) {
|
||||
throw new Error(`REFERENCE_GENERATION_NOT_COMPLETED: reference_images[${position}] generation_id ${reference.generation_id} has status ${source.status}; wait for COMPLETED`);
|
||||
}
|
||||
const output = source.outputs.find((candidate) => candidate.index === reference.index);
|
||||
if (!output) {
|
||||
const available = source.outputs.map((candidate) => candidate.index).sort((a, b) => a - b);
|
||||
throw new Error(`REFERENCE_INDEX_OUT_OF_RANGE: reference_images[${position}] index ${reference.index} is unavailable for generation ${reference.generation_id}; available indexes: ${available.join(", ") || "none"}`);
|
||||
}
|
||||
if (!(await outputExists(output))) {
|
||||
throw new Error(`REFERENCE_GENERATION_EXPIRED: reference_images[${position}] generation_id ${reference.generation_id} output ${reference.index} has expired or was purged by retention`);
|
||||
}
|
||||
if (output.mimeType !== "image/png" && output.mimeType !== "image/jpeg" && output.mimeType !== "image/webp") {
|
||||
throw new Error(`REFERENCE_IS_VIDEO: reference_images[${position}] generation_id ${reference.generation_id} output ${reference.index} is ${output.mimeType}, not an image`);
|
||||
}
|
||||
aggregateBytes += output.sizeBytes;
|
||||
resolved.push({ base64: (await readFile(output.path)).toString("base64"), mime_type: output.mimeType });
|
||||
}
|
||||
if (aggregateBytes > maxAggregateBytes) {
|
||||
throw new Error(`REFERENCE_INPUT_TOO_LARGE: reference_images exceed the aggregate MAX_REFERENCE_INPUT_MB limit (${maxAggregateBytes} bytes)`);
|
||||
}
|
||||
}
|
||||
return { ...args, reference_images: resolved };
|
||||
}
|
||||
|
||||
async refresh(job: GenerationJob): Promise<GenerationJob> {
|
||||
if (job.kind !== "video" || job.status !== "RUNNING" || !job.operation) return job;
|
||||
try {
|
||||
const result = await this.provider.pollVideo(job);
|
||||
job.operation = result.operation;
|
||||
job.updatedAt = new Date().toISOString();
|
||||
if (result.done && result.outputs) await this.complete(job, result.outputs);
|
||||
} catch (error) {
|
||||
this.fail(job, error);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
usage(): Record<string, unknown> {
|
||||
const jobs = [...this.jobs.values()];
|
||||
return {
|
||||
providerQuotaAvailable: false,
|
||||
providerQuotaMessage: "The Gemini Developer API does not expose remaining account spend/quota through this generation API.",
|
||||
scope: "current process plus completed generations restored from retained disk manifests",
|
||||
jobsSubmitted: jobs.length,
|
||||
jobsCompleted: jobs.filter((job) => job.status === "COMPLETED").length,
|
||||
jobsFailed: jobs.filter((job) => job.status === "FAILED").length,
|
||||
jobsInProgress: jobs.filter((job) => job.status === "QUEUING" || job.status === "RUNNING").length,
|
||||
estimatedSubmittedCostUsd: Math.round(this.estimatedSubmittedUsd * 10000) / 10000,
|
||||
estimatedCompletedCostUsd: Math.round(this.estimatedCompletedUsd * 10000) / 10000,
|
||||
};
|
||||
}
|
||||
|
||||
startCleanup(retentionHours: number): NodeJS.Timeout {
|
||||
const interval = setInterval(() => void this.cleanup(retentionHours), 15 * 60 * 1000);
|
||||
interval.unref();
|
||||
return interval;
|
||||
}
|
||||
|
||||
async cleanup(retentionHours: number): Promise<void> {
|
||||
const cutoff = Date.now() - retentionHours * 60 * 60 * 1000;
|
||||
for (const [id, job] of this.jobs) {
|
||||
if ((job.status === "COMPLETED" || job.status === "FAILED") && new Date(job.updatedAt).getTime() < cutoff) {
|
||||
await purgeGeneration(job);
|
||||
this.jobs.delete(id);
|
||||
audit("generation_expired", { generationId: id, retentionHours });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async runImage(job: GenerationJob): Promise<void> {
|
||||
this.start(job);
|
||||
try { await this.complete(job, await this.provider.generateImages(job)); }
|
||||
catch (error) { this.fail(job, error); }
|
||||
}
|
||||
|
||||
private async runVideoSubmit(job: GenerationJob): Promise<void> {
|
||||
this.start(job);
|
||||
try {
|
||||
job.operation = await this.provider.submitVideo(job);
|
||||
job.updatedAt = new Date().toISOString();
|
||||
audit("video_operation_submitted", { generationId: job.generationId, model: job.model });
|
||||
} catch (error) { this.fail(job, error); }
|
||||
}
|
||||
|
||||
private async runComposition(job: GenerationJob, baseOutput: NonNullable<GenerationJob["outputs"]>[number], overlays: VideoOverlay[]): Promise<void> {
|
||||
this.start(job);
|
||||
try { await this.complete(job, await composeVideoOverlay(job.generationId, baseOutput, overlays)); }
|
||||
catch (error) { this.fail(job, error); }
|
||||
}
|
||||
|
||||
private start(job: GenerationJob): void {
|
||||
job.status = "RUNNING"; job.startedAt = new Date().toISOString(); job.updatedAt = job.startedAt;
|
||||
audit("generation_started", { generationId: job.generationId, kind: job.kind, model: job.model });
|
||||
}
|
||||
|
||||
private async complete(job: GenerationJob, outputs: NonNullable<GenerationJob["outputs"]>): Promise<void> {
|
||||
job.status = "COMPLETED"; job.outputs = outputs; job.operation = undefined; job.completedAt = new Date().toISOString(); job.updatedAt = job.completedAt;
|
||||
await persistCompletedJob(job);
|
||||
job.arguments = {};
|
||||
this.estimatedCompletedUsd += job.estimatedCostUsd;
|
||||
const durationMs = job.startedAt ? Date.now() - new Date(job.startedAt).getTime() : undefined;
|
||||
audit("generation_completed", { generationId: job.generationId, kind: job.kind, model: job.model, outputCount: outputs.length, outputBytes: outputs.reduce((sum, output) => sum + output.sizeBytes, 0), durationMs, estimatedCostUsd: job.estimatedCostUsd });
|
||||
}
|
||||
|
||||
private fail(job: GenerationJob, error: unknown): void {
|
||||
const status = providerStatus(error);
|
||||
const rawMessage = error instanceof Error ? error.message : String(error);
|
||||
job.status = "FAILED"; job.updatedAt = new Date().toISOString(); job.completedAt = job.updatedAt;
|
||||
job.arguments = {};
|
||||
job.error = { code: classifyError(rawMessage, status), message: rawMessage.slice(0, 2000), ...(status ? { providerStatus: status } : {}), retryable: false };
|
||||
auditError("generation_failed", error, { generationId: job.generationId, kind: job.kind, model: job.model, durationMs: job.startedAt ? Date.now() - new Date(job.startedAt).getTime() : undefined });
|
||||
}
|
||||
}
|
||||
|
||||
function decodedBase64Size(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor(base64.length * 3 / 4) - padding;
|
||||
}
|
||||
|
||||
function classifyError(message: string, status?: number): string {
|
||||
const composeCode = message.match(/^(COMPOSE_[A-Z_]+):/)?.[1];
|
||||
if (composeCode) return composeCode;
|
||||
if (message.includes("GEMINI_API_KEY")) return "SERVER_NOT_CONFIGURED";
|
||||
if (status === 429) return "PROVIDER_RATE_LIMITED";
|
||||
if (status && status >= 500) return "PROVIDER_UNAVAILABLE";
|
||||
if (/safety|blocked|moderation|policy/i.test(message)) return "CONTENT_POLICY_BLOCKED";
|
||||
if (status === 400 || /invalid|unsupported|required|prompt/i.test(message)) return "INVALID_REQUEST";
|
||||
if (status === 401 || status === 403) return "PROVIDER_AUTH_ERROR";
|
||||
return "GENERATION_FAILED";
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
export function audit(event: string, fields: Record<string, unknown> = {}): void {
|
||||
process.stdout.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level: "info", event, ...fields })}\n`);
|
||||
}
|
||||
|
||||
export function auditError(event: string, error: unknown, fields: Record<string, unknown> = {}): void {
|
||||
const details = errorDetails(error);
|
||||
process.stderr.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level: "error", event, ...fields, ...details })}\n`);
|
||||
}
|
||||
|
||||
export function errorDetails(error: unknown): { errorName: string; errorMessage: string; providerStatus?: number } {
|
||||
if (error instanceof Error) {
|
||||
const status = providerStatus(error);
|
||||
return { errorName: error.name, errorMessage: error.message, ...(status ? { providerStatus: status } : {}) };
|
||||
}
|
||||
return { errorName: "UnknownError", errorMessage: String(error) };
|
||||
}
|
||||
|
||||
export function providerStatus(error: unknown): number | undefined {
|
||||
if (!error || typeof error !== "object") return undefined;
|
||||
const record = error as Record<string, unknown>;
|
||||
const candidates = [record.status, record.statusCode, record.code];
|
||||
for (const value of candidates) {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
if (Number.isInteger(parsed) && parsed >= 100 && parsed <= 599) return parsed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { chmod, mkdir, open, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { GenerationJob, StoredOutput } from "./types.js";
|
||||
import { createPublicMediaUrl } from "./public-media.js";
|
||||
|
||||
export const mediaDir = path.resolve(process.env.MEDIA_DIR || "/opt/gemini-veo-mcp/media");
|
||||
export const maxInlineBytes = Math.floor((Number(process.env.MAX_INLINE_MEDIA_MB) || 25) * 1024 * 1024);
|
||||
export const maxMediaBytes = Math.floor((Number(process.env.MAX_MEDIA_MB) || 300) * 1024 * 1024);
|
||||
const tombstoneRetentionDays = Number(process.env.TOMBSTONE_RETENTION_DAYS) || 30;
|
||||
|
||||
export async function ensureMediaDir(): Promise<void> {
|
||||
await mkdir(mediaDir, { recursive: true });
|
||||
}
|
||||
|
||||
export async function storeBase64(generationId: string, index: number, data: string, mimeType: string): Promise<StoredOutput> {
|
||||
const buffer = Buffer.from(data, "base64");
|
||||
if (buffer.length === 0) throw new Error("Google returned an empty media payload");
|
||||
if (buffer.length > maxMediaBytes) throw new Error(`Generated media exceeds MAX_MEDIA_MB (${maxMediaBytes} bytes)`);
|
||||
const normalizedMime = normalizeMime(mimeType, buffer);
|
||||
const extension = normalizedMime === "video/mp4" ? "mp4" : normalizedMime === "image/jpeg" ? "jpg" : "png";
|
||||
const filename = `${generationId}-${index}.${extension}`;
|
||||
const outputPath = path.join(mediaDir, filename);
|
||||
await writeFile(outputPath, buffer, { mode: 0o640 });
|
||||
return metadata(outputPath, filename, normalizedMime, buffer);
|
||||
}
|
||||
|
||||
export async function registerDownloaded(generationId: string, index: number, tempPath: string, mimeType = "video/mp4"): Promise<StoredOutput> {
|
||||
const file = await stat(tempPath);
|
||||
if (file.size === 0) throw new Error("Google returned an empty video file");
|
||||
if (file.size > maxMediaBytes) {
|
||||
await unlink(tempPath).catch(() => undefined);
|
||||
throw new Error(`Generated media exceeds MAX_MEDIA_MB (${maxMediaBytes} bytes)`);
|
||||
}
|
||||
const handle = await open(tempPath, "r");
|
||||
const header = Buffer.alloc(12);
|
||||
await handle.read(header, 0, header.length, 0);
|
||||
await handle.close();
|
||||
const normalizedMime = normalizeMime(mimeType, header);
|
||||
if (normalizedMime !== "video/mp4") throw new Error(`Expected video/mp4, received ${normalizedMime}`);
|
||||
const filename = `${generationId}-${index}.mp4`;
|
||||
const outputPath = path.join(mediaDir, filename);
|
||||
if (tempPath !== outputPath) {
|
||||
await rename(tempPath, outputPath);
|
||||
}
|
||||
await chmod(outputPath, 0o640);
|
||||
return { index, path: outputPath, filename, mimeType: normalizedMime, sizeBytes: file.size, sha256: await hashFile(outputPath) };
|
||||
}
|
||||
|
||||
export async function outputPayload(outputs: StoredOutput[], publicBaseUrl: string, includeBase64 = true): Promise<Array<Record<string, unknown>>> {
|
||||
const totalBytes = outputs.reduce((sum, output) => sum + output.sizeBytes, 0);
|
||||
const inline = includeBase64 && totalBytes <= maxInlineBytes;
|
||||
return Promise.all(outputs.map(async (output) => {
|
||||
const signed = createPublicMediaUrl(output.filename, publicBaseUrl);
|
||||
return {
|
||||
index: output.index,
|
||||
mimeType: output.mimeType,
|
||||
sizeBytes: output.sizeBytes,
|
||||
sha256: output.sha256,
|
||||
...signed,
|
||||
...(inline
|
||||
? { base64: (await readFile(output.path)).toString("base64") }
|
||||
: { downloadUrl: `${publicBaseUrl.replace(/\/$/, "")}/media/${encodeURIComponent(output.filename)}` }),
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
export async function resolvePublicOutput(filename: string): Promise<StoredOutput | undefined> {
|
||||
const match = filename.match(/^([0-9a-f-]{36})-(\d+)\.(png|jpg|mp4)$/);
|
||||
if (!match) return undefined;
|
||||
const job = await loadPersistedJob(match[1]);
|
||||
const output = job?.outputs?.find((candidate) => candidate.filename === filename && candidate.index === Number(match[2]));
|
||||
if (!output || !(await outputExists(output))) return undefined;
|
||||
return output;
|
||||
}
|
||||
|
||||
export async function removeOutputs(outputs: StoredOutput[] | undefined): Promise<void> {
|
||||
if (!outputs) return;
|
||||
await Promise.all(outputs.map((output) => unlink(output.path).catch(() => undefined)));
|
||||
}
|
||||
|
||||
export async function persistCompletedJob(job: GenerationJob): Promise<void> {
|
||||
if (job.status !== "COMPLETED" || !job.outputs) throw new Error("Only completed jobs with outputs can be persisted");
|
||||
const manifest = {
|
||||
version: 1,
|
||||
generationId: job.generationId,
|
||||
taskTraceId: job.taskTraceId,
|
||||
kind: job.kind,
|
||||
model: job.model,
|
||||
canonicalModel: job.canonicalModel,
|
||||
estimatedCostUsd: job.estimatedCostUsd,
|
||||
status: "COMPLETED",
|
||||
createdAt: job.createdAt,
|
||||
startedAt: job.startedAt,
|
||||
completedAt: job.completedAt,
|
||||
updatedAt: job.updatedAt,
|
||||
outputs: job.outputs.map((output) => ({
|
||||
index: output.index,
|
||||
filename: output.filename,
|
||||
mimeType: output.mimeType,
|
||||
sizeBytes: output.sizeBytes,
|
||||
sha256: output.sha256,
|
||||
})),
|
||||
};
|
||||
const target = manifestPath(job.generationId);
|
||||
const temporary = `${target}.${process.pid}.tmp`;
|
||||
await writeFile(temporary, JSON.stringify(manifest), { mode: 0o640 });
|
||||
await rename(temporary, target);
|
||||
}
|
||||
|
||||
export async function loadPersistedJobs(): Promise<GenerationJob[]> {
|
||||
const jobs: GenerationJob[] = [];
|
||||
for (const filename of await readdir(mediaDir)) {
|
||||
const match = filename.match(/^([0-9a-f-]{36})\.manifest\.json$/);
|
||||
if (!match) continue;
|
||||
const job = await loadPersistedJob(match[1]);
|
||||
if (job) jobs.push(job);
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
export async function migrateLegacyOutputs(): Promise<number> {
|
||||
const groups = new Map<string, Array<{ index: number; filename: string; extension: "png" | "jpg" | "mp4" }>>();
|
||||
for (const filename of await readdir(mediaDir)) {
|
||||
const match = filename.match(/^([0-9a-f-]{36})-(\d+)\.(png|jpg|mp4)$/);
|
||||
if (!match) continue;
|
||||
const list = groups.get(match[1]) ?? [];
|
||||
list.push({ index: Number(match[2]), filename, extension: match[3] as "png" | "jpg" | "mp4" });
|
||||
groups.set(match[1], list);
|
||||
}
|
||||
|
||||
let migrated = 0;
|
||||
for (const [generationId, files] of groups) {
|
||||
try {
|
||||
await stat(manifestPath(generationId));
|
||||
continue;
|
||||
} catch {
|
||||
// No manifest: this is an output created by the pre-persistence server.
|
||||
}
|
||||
if (await generationWasPurged(generationId)) continue;
|
||||
const outputs: StoredOutput[] = [];
|
||||
let latestMtime = 0;
|
||||
for (const file of files.sort((a, b) => a.index - b.index)) {
|
||||
const outputPath = path.join(mediaDir, file.filename);
|
||||
const details = await stat(outputPath);
|
||||
latestMtime = Math.max(latestMtime, details.mtimeMs);
|
||||
outputs.push({
|
||||
index: file.index,
|
||||
path: outputPath,
|
||||
filename: file.filename,
|
||||
mimeType: file.extension === "png" ? "image/png" : file.extension === "jpg" ? "image/jpeg" : "video/mp4",
|
||||
sizeBytes: details.size,
|
||||
sha256: await hashFile(outputPath),
|
||||
});
|
||||
}
|
||||
const timestamp = new Date(latestMtime || Date.now()).toISOString();
|
||||
await persistCompletedJob({
|
||||
generationId,
|
||||
kind: outputs.every((output) => output.mimeType.startsWith("image/")) ? "image" : "video",
|
||||
model: "legacy-restored",
|
||||
canonicalModel: "legacy-restored",
|
||||
arguments: {},
|
||||
estimatedCostUsd: 0,
|
||||
status: "COMPLETED",
|
||||
createdAt: timestamp,
|
||||
startedAt: timestamp,
|
||||
completedAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
outputs,
|
||||
});
|
||||
migrated += 1;
|
||||
}
|
||||
return migrated;
|
||||
}
|
||||
|
||||
export async function loadPersistedJob(generationId: string): Promise<GenerationJob | undefined> {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(manifestPath(generationId), "utf8")) as Record<string, unknown>;
|
||||
if (parsed.version !== 1 || parsed.generationId !== generationId || parsed.status !== "COMPLETED") return undefined;
|
||||
if (parsed.kind !== "image" && parsed.kind !== "video") return undefined;
|
||||
if (!Array.isArray(parsed.outputs)) return undefined;
|
||||
const outputs: StoredOutput[] = parsed.outputs.map((value, position) => {
|
||||
if (!value || typeof value !== "object") throw new Error("Invalid persisted output");
|
||||
const output = value as Record<string, unknown>;
|
||||
const index = Number(output.index ?? position);
|
||||
const filename = String(output.filename ?? "");
|
||||
if (!Number.isInteger(index) || index < 0 || !safeOutputFilename(generationId, index, filename)) throw new Error("Invalid persisted output path");
|
||||
return {
|
||||
index,
|
||||
path: path.join(mediaDir, filename),
|
||||
filename,
|
||||
mimeType: String(output.mimeType),
|
||||
sizeBytes: Number(output.sizeBytes),
|
||||
sha256: String(output.sha256),
|
||||
};
|
||||
});
|
||||
return {
|
||||
generationId,
|
||||
taskTraceId: typeof parsed.taskTraceId === "string" ? parsed.taskTraceId : undefined,
|
||||
kind: parsed.kind,
|
||||
model: String(parsed.model),
|
||||
canonicalModel: String(parsed.canonicalModel),
|
||||
arguments: {},
|
||||
estimatedCostUsd: Number(parsed.estimatedCostUsd) || 0,
|
||||
status: "COMPLETED",
|
||||
createdAt: String(parsed.createdAt),
|
||||
startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : undefined,
|
||||
completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : undefined,
|
||||
updatedAt: String(parsed.updatedAt),
|
||||
outputs,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function purgeGeneration(job: GenerationJob): Promise<void> {
|
||||
await removeOutputs(job.outputs);
|
||||
await unlink(manifestPath(job.generationId)).catch(() => undefined);
|
||||
await writeTombstone(job.generationId);
|
||||
}
|
||||
|
||||
export async function generationWasPurged(generationId: string): Promise<boolean> {
|
||||
try {
|
||||
return (await stat(tombstonePath(generationId))).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function outputExists(output: StoredOutput): Promise<boolean> {
|
||||
try {
|
||||
const file = await stat(output.path);
|
||||
return file.isFile() && file.size === output.sizeBytes;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupOrphanMedia(retentionHours: number): Promise<number> {
|
||||
const cutoff = Date.now() - retentionHours * 60 * 60 * 1000;
|
||||
const tombstoneCutoff = Date.now() - tombstoneRetentionDays * 24 * 60 * 60 * 1000;
|
||||
let removed = 0;
|
||||
for (const filename of await readdir(mediaDir)) {
|
||||
const artifact = filename.match(/^([0-9a-f-]{36})(?:-\d+\.(?:png|jpg|mp4|download)|\.manifest\.json)$/);
|
||||
const tombstone = filename.match(/^([0-9a-f-]{36})\.expired\.json$/);
|
||||
if (!artifact && !tombstone) continue;
|
||||
const outputPath = path.join(mediaDir, filename);
|
||||
try {
|
||||
const file = await stat(outputPath);
|
||||
if (artifact && file.mtimeMs < cutoff) {
|
||||
await unlink(outputPath);
|
||||
await writeTombstone(artifact[1]);
|
||||
removed += 1;
|
||||
} else if (tombstone && file.mtimeMs < tombstoneCutoff) {
|
||||
await unlink(outputPath);
|
||||
}
|
||||
} catch {
|
||||
// A concurrent cleanup/download may have removed the file.
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
function metadata(outputPath: string, filename: string, mimeType: string, buffer: Buffer): StoredOutput {
|
||||
const index = Number(filename.match(/-(\d+)\.[^.]+$/)?.[1] ?? 0);
|
||||
return { index, path: outputPath, filename, mimeType, sizeBytes: buffer.length, sha256: createHash("sha256").update(buffer).digest("hex") };
|
||||
}
|
||||
|
||||
async function hashFile(outputPath: string): Promise<string> {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(outputPath)) hash.update(chunk as Buffer);
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
||||
function normalizeMime(reported: string | undefined, data: Buffer): string {
|
||||
if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "image/png";
|
||||
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return "image/jpeg";
|
||||
if (data.length >= 12 && data.subarray(4, 8).toString("ascii") === "ftyp") return "video/mp4";
|
||||
return reported || "application/octet-stream";
|
||||
}
|
||||
|
||||
function manifestPath(generationId: string): string {
|
||||
return path.join(mediaDir, `${generationId}.manifest.json`);
|
||||
}
|
||||
|
||||
function tombstonePath(generationId: string): string {
|
||||
return path.join(mediaDir, `${generationId}.expired.json`);
|
||||
}
|
||||
|
||||
async function writeTombstone(generationId: string): Promise<void> {
|
||||
await writeFile(tombstonePath(generationId), JSON.stringify({ generationId, purgedAt: new Date().toISOString() }), { mode: 0o640 });
|
||||
}
|
||||
|
||||
function safeOutputFilename(generationId: string, index: number, filename: string): boolean {
|
||||
return filename.startsWith(`${generationId}-${index}.`) && /^[0-9a-f-]{36}-\d+\.(png|jpg|mp4)$/.test(filename);
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import { GoogleGenAI } from "@google/genai";
|
||||
import path from "node:path";
|
||||
import { mediaDir, registerDownloaded, removeOutputs, storeBase64 } from "./media.js";
|
||||
import { withRetry } from "./retry.js";
|
||||
import type { GenerationJob, StoredOutput } from "./types.js";
|
||||
|
||||
export class GoogleMediaProvider {
|
||||
private readonly client: GoogleGenAI;
|
||||
|
||||
constructor(apiKey = process.env.GEMINI_API_KEY) {
|
||||
this.client = new GoogleGenAI({ apiKey: apiKey || "missing-gemini-api-key" });
|
||||
}
|
||||
|
||||
async generateImages(job: GenerationJob): Promise<StoredOutput[]> {
|
||||
this.assertConfigured();
|
||||
const count = Number(job.arguments.image_count ?? 1);
|
||||
const outputs: StoredOutput[] = [];
|
||||
|
||||
try {
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const references = (job.arguments.reference_images as Array<{ base64: string; mime_type: string }> | undefined) ?? [];
|
||||
const response: any = await withRetry("generate_image", () => this.client.models.generateContent({
|
||||
model: job.canonicalModel,
|
||||
contents: [{
|
||||
role: "user",
|
||||
parts: [
|
||||
...references.map((reference) => ({ inlineData: { data: reference.base64, mimeType: reference.mime_type } })),
|
||||
{ text: String(job.arguments.prompt) },
|
||||
],
|
||||
}],
|
||||
config: {
|
||||
responseModalities: ["IMAGE"],
|
||||
imageConfig: {
|
||||
aspectRatio: String(job.arguments.aspect_ratio),
|
||||
...(job.canonicalModel !== "gemini-2.5-flash-image" ? { imageSize: String(job.arguments.resolution) } : {}),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const parts = response?.candidates?.flatMap((candidate: any) => candidate?.content?.parts ?? []) ?? [];
|
||||
const imagePart = parts.find((part: any) => part?.inlineData?.data);
|
||||
if (!imagePart?.inlineData?.data) {
|
||||
const reason = response?.promptFeedback?.blockReason || response?.candidates?.[0]?.finishReason;
|
||||
throw new Error(reason ? `Image generation produced no image (${reason})` : "Image generation produced no image");
|
||||
}
|
||||
outputs.push(await storeBase64(job.generationId, index, imagePart.inlineData.data, imagePart.inlineData.mimeType || "image/png"));
|
||||
}
|
||||
return outputs;
|
||||
} catch (error) {
|
||||
await removeOutputs(outputs);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async submitVideo(job: GenerationJob): Promise<unknown> {
|
||||
this.assertConfigured();
|
||||
return withRetry("submit_video", () => this.client.models.generateVideos({
|
||||
model: job.canonicalModel,
|
||||
prompt: String(job.arguments.prompt),
|
||||
config: {
|
||||
aspectRatio: String(job.arguments.aspect_ratio),
|
||||
durationSeconds: Number(job.arguments.duration_seconds),
|
||||
resolution: String(job.arguments.resolution),
|
||||
numberOfVideos: 1,
|
||||
...(job.arguments.seed !== undefined ? { seed: Number(job.arguments.seed) } : {}),
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
async pollVideo(job: GenerationJob): Promise<{ done: boolean; operation: unknown; outputs?: StoredOutput[] }> {
|
||||
this.assertConfigured();
|
||||
if (!job.operation) return { done: false, operation: job.operation };
|
||||
const operation: any = await withRetry("poll_video", () => this.client.operations.getVideosOperation({ operation: job.operation as any }));
|
||||
if (!operation?.done) return { done: false, operation };
|
||||
if (operation.error) {
|
||||
const error = new Error(operation.error.message || "Veo generation failed") as Error & { code?: number };
|
||||
error.code = operation.error.code;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const videos = operation?.response?.generatedVideos ?? [];
|
||||
if (videos.length === 0) throw new Error("Veo operation completed without a video");
|
||||
const outputs: StoredOutput[] = [];
|
||||
for (let index = 0; index < videos.length; index += 1) {
|
||||
const video = videos[index]?.video;
|
||||
if (video?.videoBytes) {
|
||||
outputs.push(await storeBase64(job.generationId, index, video.videoBytes, video.mimeType || "video/mp4"));
|
||||
continue;
|
||||
}
|
||||
if (!video) throw new Error("Veo returned an invalid video reference");
|
||||
const tempPath = path.join(mediaDir, `${job.generationId}-${index}.download`);
|
||||
await withRetry("download_video", () => this.client.files.download({ file: video, downloadPath: tempPath }));
|
||||
outputs.push(await registerDownloaded(job.generationId, index, tempPath, video.mimeType || "video/mp4"));
|
||||
}
|
||||
return { done: true, operation, outputs };
|
||||
}
|
||||
|
||||
private assertConfigured(): void {
|
||||
if (!process.env.GEMINI_API_KEY) throw new Error("GEMINI_API_KEY is not configured on the MCP server");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const DEFAULT_TTL_SECONDS = 24 * 60 * 60;
|
||||
const MAX_TTL_SECONDS = 7 * 24 * 60 * 60;
|
||||
const CLOCK_SKEW_SECONDS = 60;
|
||||
|
||||
export interface SignedPublicMediaUrl {
|
||||
publicUrl: string;
|
||||
publicUrlExpiresAt: string;
|
||||
}
|
||||
|
||||
export function publicMediaTtlSeconds(): number {
|
||||
const configured = Number(process.env.PUBLIC_MEDIA_URL_TTL_SECONDS);
|
||||
if (!Number.isInteger(configured) || configured < 60) return DEFAULT_TTL_SECONDS;
|
||||
return Math.min(configured, MAX_TTL_SECONDS);
|
||||
}
|
||||
|
||||
export function publicMediaSigningConfigured(): boolean {
|
||||
return signingSecret().length >= 32;
|
||||
}
|
||||
|
||||
export function createPublicMediaUrl(
|
||||
filename: string,
|
||||
publicBaseUrl: string,
|
||||
nowMs = Date.now(),
|
||||
): SignedPublicMediaUrl {
|
||||
assertSafeFilename(filename);
|
||||
const secret = requireSigningSecret();
|
||||
const expires = Math.floor(nowMs / 1000) + publicMediaTtlSeconds();
|
||||
const signature = sign(filename, expires, secret);
|
||||
const base = publicBaseUrl.replace(/\/+$/, "");
|
||||
return {
|
||||
publicUrl: `${base}/public-media/${encodeURIComponent(filename)}?expires=${expires}&signature=${signature}`,
|
||||
publicUrlExpiresAt: new Date(expires * 1000).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export function validatePublicMediaSignature(
|
||||
filename: string,
|
||||
rawExpires: unknown,
|
||||
rawSignature: unknown,
|
||||
nowMs = Date.now(),
|
||||
): { valid: true; expires: number } | { valid: false; reason: "invalid" | "expired" } {
|
||||
if (!publicMediaSigningConfigured()) return { valid: false, reason: "invalid" };
|
||||
try {
|
||||
assertSafeFilename(filename);
|
||||
} catch {
|
||||
return { valid: false, reason: "invalid" };
|
||||
}
|
||||
if (typeof rawExpires !== "string" || !/^\d{10}$/.test(rawExpires)) return { valid: false, reason: "invalid" };
|
||||
if (typeof rawSignature !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(rawSignature)) return { valid: false, reason: "invalid" };
|
||||
|
||||
const expires = Number(rawExpires);
|
||||
const nowSeconds = Math.floor(nowMs / 1000);
|
||||
if (!Number.isSafeInteger(expires)) return { valid: false, reason: "invalid" };
|
||||
if (expires < nowSeconds) return { valid: false, reason: "expired" };
|
||||
if (expires > nowSeconds + publicMediaTtlSeconds() + CLOCK_SKEW_SECONDS) return { valid: false, reason: "invalid" };
|
||||
|
||||
const expected = Buffer.from(sign(filename, expires, requireSigningSecret()));
|
||||
const actual = Buffer.from(rawSignature);
|
||||
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return { valid: false, reason: "invalid" };
|
||||
return { valid: true, expires };
|
||||
}
|
||||
|
||||
function sign(filename: string, expires: number, secret: string): string {
|
||||
return createHmac("sha256", secret)
|
||||
.update(`zenvairo-public-media-v1\n${filename}\n${expires}`, "utf8")
|
||||
.digest("base64url");
|
||||
}
|
||||
|
||||
function signingSecret(): string {
|
||||
return process.env.PUBLIC_MEDIA_SIGNING_SECRET || "";
|
||||
}
|
||||
|
||||
function requireSigningSecret(): string {
|
||||
const secret = signingSecret();
|
||||
if (secret.length < 32) throw new Error("PUBLIC_MEDIA_SIGNING_SECRET must contain at least 32 characters");
|
||||
return secret;
|
||||
}
|
||||
|
||||
function assertSafeFilename(filename: string): void {
|
||||
if (!/^[0-9a-f-]{36}-\d+\.(png|jpg|mp4)$/.test(filename)) throw new Error("Invalid public media filename");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { audit } from "./log.js";
|
||||
import { providerStatus } from "./log.js";
|
||||
|
||||
export function isTransient(error: unknown): boolean {
|
||||
const status = providerStatus(error);
|
||||
if (status === 429 || (status !== undefined && status >= 500)) return true;
|
||||
if (error instanceof Error) {
|
||||
return /ECONNRESET|ETIMEDOUT|EAI_AGAIN|fetch failed|network/i.test(error.message);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function withRetry<T>(operation: string, fn: () => Promise<T>, maxRetries = 2): Promise<T> {
|
||||
let attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
if (!isTransient(error) || attempt >= maxRetries) throw error;
|
||||
attempt += 1;
|
||||
const delayMs = Math.min(4000, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 250);
|
||||
audit("provider_retry", { operation, attempt, maxRetries, delayMs, providerStatus: providerStatus(error) });
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import { normalizeArguments } from "./arguments.js";
|
||||
import { MODEL_CATALOG, PRICING_REFERENCE_DATE, resolveModel } from "./catalog.js";
|
||||
import { JobManager } from "./jobs.js";
|
||||
import { maxInlineBytes, outputExists, outputPayload } from "./media.js";
|
||||
import { publicMediaSigningConfigured, publicMediaTtlSeconds } from "./public-media.js";
|
||||
|
||||
const taskTraceIdSchema = z.string().uuid().optional().describe("Optional UUID used to group related calls.");
|
||||
const inlineReferenceImageSchema = z.object({
|
||||
base64: z.string().min(1).describe("Raw standard base64 from query_tasks outputs[].base64; a data URI is also accepted."),
|
||||
mime_type: z.enum(["image/png", "image/jpeg", "image/webp"]),
|
||||
}).strict();
|
||||
const generationReferenceImageSchema = z.object({
|
||||
generation_id: z.string().uuid().describe("generationId of a completed image generation retained by this server."),
|
||||
index: z.number().int().nonnegative().default(0).describe("Zero-based output index; defaults to 0."),
|
||||
}).strict();
|
||||
const referenceImageSchema = z.union([inlineReferenceImageSchema, generationReferenceImageSchema]);
|
||||
const argumentsSchema = z.array(z.object({
|
||||
name: z.string().min(1),
|
||||
value: z.union([z.string(), z.number(), z.boolean(), z.array(referenceImageSchema)]),
|
||||
})).describe("Kling-compatible name/value argument list.");
|
||||
const videoOverlaySchema = z.object({
|
||||
text: z.string().trim().min(1).max(240).describe("Card text; never logged."),
|
||||
kicker: z.string().trim().min(1).max(40).optional().describe("Optional uppercase label displayed above the text."),
|
||||
style: z.enum(["normal", "cta"]).default("normal"),
|
||||
start_time: z.number().finite().min(0).max(600).describe("Seconds from the start of the base video."),
|
||||
duration: z.number().finite().min(0.5).max(60).describe("Seconds the card remains visible, including 250ms fades."),
|
||||
}).strict();
|
||||
|
||||
export function registerTools(server: McpServer, jobs: JobManager): void {
|
||||
const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168;
|
||||
server.tool("who_am_i", "List available Google image/video models, accepted arguments and current cost estimates.", {
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ taskTraceId }) => jsonResult({
|
||||
service: "Zenvairo Google Media MCP",
|
||||
taskTraceId,
|
||||
backend: "Gemini Developer API",
|
||||
authentication: { googleCredentialsConfigured: Boolean(process.env.GEMINI_API_KEY), credentialsExposed: false },
|
||||
pricingReferenceDate: PRICING_REFERENCE_DATE,
|
||||
costCaveat: "Estimates cover output image/video pricing only; prompt input tokens and optional grounding charges are excluded.",
|
||||
resultDelivery: {
|
||||
inlineBase64AggregateLimitBytes: maxInlineBytes,
|
||||
inlineBase64AggregateLimitMiB: maxInlineBytes / 1024 / 1024,
|
||||
oversizedAlternative: "Protected same-domain downloadUrl; use the same connector HTTP Basic credentials.",
|
||||
recommendedDelivery: "publicUrl is an HMAC-signed same-domain URL that Meta can fetch directly without credentials.",
|
||||
publicUrl: { configured: publicMediaSigningConfigured(), ttlSeconds: publicMediaTtlSeconds(), authentication: "expiring HMAC signature in query string" },
|
||||
queryTasksArguments: [
|
||||
{ name: "generationId", required: true, format: "uuid" },
|
||||
{ name: "taskTraceId", required: false, format: "uuid" },
|
||||
{ name: "include_base64", required: false, allowedValues: [true, false], default: false, description: "Default false: compact outputs include publicUrl and protected downloadUrl. Set true only when inline bytes are explicitly required." },
|
||||
],
|
||||
},
|
||||
generationRetention: {
|
||||
ttlHours: retentionHours,
|
||||
ttlDays: retentionHours / 24,
|
||||
storage: "disk manifests and media indexed by generationId",
|
||||
behaviorAfterExpiry: "References fail with REFERENCE_GENERATION_EXPIRED while the purge tombstone is retained.",
|
||||
},
|
||||
referenceImages: {
|
||||
argumentName: "reference_images",
|
||||
variants: [
|
||||
{ format: '{generation_id:uuid,index?:integer=0}', recommended: true, description: "Reuses a retained completed image entirely server-side; no base64 enters the client context." },
|
||||
{ format: '{base64:string,mime_type:"image/png"|"image/jpeg"|"image/webp"}', recommended: false, description: "Backward-compatible inline image input." },
|
||||
],
|
||||
mixingAllowed: true,
|
||||
modelLimits: { "gemini-2.5-flash-image": 3, "gemini-3-pro-image": 14, "gemini-3.1-flash-image": 14, "gemini-3.1-flash-lite-image": 14 },
|
||||
},
|
||||
videoComposition: {
|
||||
tool: "compose_video_overlay",
|
||||
backend: "local Pillow + ffmpeg; no Google generation call and no media crosses the client context",
|
||||
asynchronous: true,
|
||||
baseRequirements: { kind: "video", status: "COMPLETED", mimeType: "video/mp4", aspectRatio: "9:16", retainedByThisServer: true },
|
||||
overlayArguments: [
|
||||
{ name: "text", required: true, maximumCharacters: 240 },
|
||||
{ name: "kicker", required: false, maximumCharacters: 40 },
|
||||
{ name: "style", required: false, allowedValues: ["normal", "cta"], default: "normal" },
|
||||
{ name: "start_time", required: true, unit: "seconds", minimum: 0 },
|
||||
{ name: "duration", required: true, unit: "seconds", minimum: 0.5, maximum: 60 },
|
||||
],
|
||||
overlayCount: { minimum: 1, maximum: 10 },
|
||||
output: "A new retained generationId polled through query_tasks; use outputs[].publicUrl directly in SocialMCP publish_post.",
|
||||
},
|
||||
models: {
|
||||
image: MODEL_CATALOG.filter((model) => model.type === "image"),
|
||||
video: MODEL_CATALOG.filter((model) => model.type === "video"),
|
||||
},
|
||||
}));
|
||||
|
||||
server.tool("generate_image", "Queue a Gemini image generation job and return immediately.", {
|
||||
model: z.string().min(1), arguments: argumentsSchema, taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ model, arguments: inputArguments, taskTraceId }) => {
|
||||
const spec = resolveModel(model, "image");
|
||||
const args = await jobs.resolveImageReferences(normalizeArguments(spec, inputArguments));
|
||||
const job = jobs.submit("image", model, args, taskTraceId);
|
||||
return jsonResult(submitPayload(job));
|
||||
});
|
||||
|
||||
server.tool("generate_video", "Queue a Veo video generation job and return immediately.", {
|
||||
model: z.string().min(1), arguments: argumentsSchema, taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ model, arguments: inputArguments, taskTraceId }) => {
|
||||
const spec = resolveModel(model, "video");
|
||||
const args = normalizeArguments(spec, inputArguments);
|
||||
const job = jobs.submit("video", model, args, taskTraceId);
|
||||
return jsonResult(submitPayload(job));
|
||||
});
|
||||
|
||||
server.tool("compose_video_overlay", "Queue a local Pillow/ffmpeg composition over a retained completed 9:16 video. Returns a new generationId immediately; poll it with query_tasks and publish outputs[].publicUrl directly.", {
|
||||
base_generation_id: z.string().uuid().describe("generationId of a retained COMPLETED video/mp4 from this server."),
|
||||
overlays: z.array(videoOverlaySchema).min(1).max(10),
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ base_generation_id, overlays, taskTraceId }) => {
|
||||
const job = await jobs.submitComposition(base_generation_id, overlays, taskTraceId);
|
||||
return jsonResult(submitPayload(job));
|
||||
});
|
||||
|
||||
server.tool("query_tasks", "Poll either an image or video generation job. Compact output is the default and includes an expiring publicUrl that can be passed directly to SocialMCP publish_post.", {
|
||||
generationId: z.string().uuid(),
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
include_base64: z.boolean().default(false).describe("Default false. Outputs include publicUrl and omit base64. Set true only for explicit inline delivery."),
|
||||
}, async ({ generationId, taskTraceId, include_base64 }) => {
|
||||
let job = jobs.get(generationId);
|
||||
if (!job) return jsonResult({ generationId, status: "FAILED", error: { code: "JOB_NOT_FOUND", message: "Unknown or expired generationId", retryable: false } }, true);
|
||||
if (taskTraceId && job.taskTraceId && taskTraceId !== job.taskTraceId) {
|
||||
return jsonResult({ generationId, status: "FAILED", error: { code: "TRACE_ID_MISMATCH", message: "taskTraceId does not match this generation", retryable: false } }, true);
|
||||
}
|
||||
job = await jobs.refresh(job);
|
||||
const payload: Record<string, unknown> = {
|
||||
generationId: job.generationId, taskTraceId: job.taskTraceId, status: job.status, type: job.kind, model: job.model,
|
||||
estimatedCostUsd: job.estimatedCostUsd, createdAt: job.createdAt, startedAt: job.startedAt, completedAt: job.completedAt,
|
||||
};
|
||||
if (job.status === "FAILED") payload.error = job.error;
|
||||
if (job.status === "COMPLETED" && job.outputs) {
|
||||
const allPresent = (await Promise.all(job.outputs.map(outputExists))).every(Boolean);
|
||||
if (!allPresent) return jsonResult({ ...payload, status: "FAILED", error: { code: "MEDIA_EXPIRED", message: "Generated media is no longer available", retryable: false } }, true);
|
||||
payload.outputs = await outputPayload(job.outputs, process.env.PUBLIC_BASE_URL || "https://mcp.zenvairo.es/zenvairogoogle", include_base64);
|
||||
}
|
||||
return jsonResult(payload, job.status === "FAILED");
|
||||
});
|
||||
|
||||
server.tool("get_usage", "Return process-local estimated generation usage; Google does not expose remaining billing quota here.", {
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ taskTraceId }) => jsonResult({ taskTraceId, ...jobs.usage(), pricingReferenceDate: PRICING_REFERENCE_DATE }));
|
||||
}
|
||||
|
||||
function submitPayload(job: ReturnType<JobManager["submit"]>): Record<string, unknown> {
|
||||
return { generationId: job.generationId, status: "QUEUING", model: job.model, estimatedCostUsd: job.estimatedCostUsd, creditsConsumed_o_costEstimado: { amount: job.estimatedCostUsd, currency: "USD", kind: "estimate" } };
|
||||
}
|
||||
|
||||
function jsonResult(payload: Record<string, unknown>, isError = false): { content: Array<{ type: "text"; text: string }>; isError?: boolean } {
|
||||
return { content: [{ type: "text", text: JSON.stringify(payload) }], ...(isError ? { isError: true } : {}) };
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
export type JobStatus = "QUEUING" | "RUNNING" | "COMPLETED" | "FAILED";
|
||||
export type JobKind = "image" | "video";
|
||||
|
||||
export interface ToolArgument {
|
||||
name: string;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
export interface StoredOutput {
|
||||
index: number;
|
||||
path: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
export interface InlineReferenceImage {
|
||||
base64: string;
|
||||
mime_type: "image/png" | "image/jpeg" | "image/webp";
|
||||
}
|
||||
|
||||
export interface GenerationReferenceImage {
|
||||
generation_id: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export type ReferenceImage = InlineReferenceImage | GenerationReferenceImage;
|
||||
|
||||
export interface VideoOverlay {
|
||||
text: string;
|
||||
kicker?: string;
|
||||
style: "normal" | "cta";
|
||||
start_time: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export interface JobError {
|
||||
code: string;
|
||||
message: string;
|
||||
providerStatus?: number;
|
||||
retryable: false;
|
||||
}
|
||||
|
||||
export interface GenerationJob {
|
||||
generationId: string;
|
||||
taskTraceId?: string;
|
||||
kind: JobKind;
|
||||
model: string;
|
||||
canonicalModel: string;
|
||||
arguments: Record<string, unknown>;
|
||||
estimatedCostUsd: number;
|
||||
status: JobStatus;
|
||||
createdAt: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
updatedAt: string;
|
||||
operation?: unknown;
|
||||
outputs?: StoredOutput[];
|
||||
error?: JobError;
|
||||
}
|
||||
|
||||
export interface ArgumentSpec {
|
||||
name: string;
|
||||
required: boolean;
|
||||
description: string;
|
||||
allowedValues?: Array<string | number | boolean>;
|
||||
default?: string | number | boolean;
|
||||
minimum?: number;
|
||||
maximum?: number;
|
||||
maximumItems?: number;
|
||||
format?: string;
|
||||
}
|
||||
|
||||
export interface ModelSpec {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
description: string;
|
||||
type: JobKind;
|
||||
canonicalApiModel: string;
|
||||
arguments: ArgumentSpec[];
|
||||
pricing: {
|
||||
currency: "USD";
|
||||
referenceDate: string;
|
||||
basis: string;
|
||||
rates: Record<string, number>;
|
||||
source: string;
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user