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,83 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import test from "node:test";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
test("real Veo generation -> local overlay composition -> signed public URL", { timeout: 900_000 }, async (t) => {
|
||||
if (!process.env.GEMINI_API_KEY || !process.env.MCP_SERVER_TOKEN) {
|
||||
t.skip("Set GEMINI_API_KEY and MCP_SERVER_TOKEN to run the paid real integration test");
|
||||
return;
|
||||
}
|
||||
const endpoint = new URL(process.env.MCP_TEST_URL || "http://127.0.0.1:8087/mcp");
|
||||
const transport = new StreamableHTTPClientTransport(endpoint, {
|
||||
requestInit: { headers: { Authorization: `Bearer ${process.env.MCP_SERVER_TOKEN}` } },
|
||||
});
|
||||
const client = new Client({ name: "gemini-veo-compose-integration", version: "1.0.0" });
|
||||
const taskTraceId = randomUUID();
|
||||
await client.connect(transport);
|
||||
try {
|
||||
const submitted = parseText(await client.callTool({ name: "generate_video", arguments: {
|
||||
model: "veo-3.1-lite",
|
||||
taskTraceId,
|
||||
arguments: [
|
||||
{ name: "prompt", value: "Vertical cinematic brand clip of abstract digital infrastructure, dark navy surfaces with cyan light trails, smooth slow camera motion, subtle electronic ambience, no text, no logos, keep the lower-center area visually uncluttered." },
|
||||
{ name: "resolution", value: "720p" },
|
||||
{ name: "aspect_ratio", value: "9:16" },
|
||||
{ name: "duration_seconds", value: 8 },
|
||||
{ name: "with_audio", value: true },
|
||||
],
|
||||
} }));
|
||||
assert.equal(submitted.status, "QUEUING");
|
||||
const base = await poll(client, submitted.generationId, taskTraceId, 40, 15_000);
|
||||
assert.equal(base.type, "video");
|
||||
assert.equal(base.outputs[0].base64, undefined);
|
||||
|
||||
const composedSubmission = parseText(await client.callTool({ name: "compose_video_overlay", arguments: {
|
||||
base_generation_id: submitted.generationId,
|
||||
taskTraceId,
|
||||
overlays: [
|
||||
{ kicker: "ZENVAIRO", text: "La automatización no debería sentirse genérica", style: "normal", start_time: 0.6, duration: 2.5 },
|
||||
{ kicker: "ACTÚA AHORA", text: "Convierte procesos en ventaja", style: "cta", start_time: 4.8, duration: 2.5 },
|
||||
],
|
||||
} }));
|
||||
assert.equal(composedSubmission.status, "QUEUING");
|
||||
const composed = await poll(client, composedSubmission.generationId, taskTraceId, 90, 2_000);
|
||||
assert.equal(composed.model, "ffmpeg-overlay");
|
||||
assert.equal(composed.outputs[0].mimeType, "video/mp4");
|
||||
assert.equal(composed.outputs[0].base64, undefined);
|
||||
assert.match(composed.outputs[0].publicUrl, /^https:\/\/mcp\.zenvairo\.es\/zenvairogoogle\/public-media\//);
|
||||
|
||||
const publicResponse = await fetch(composed.outputs[0].publicUrl);
|
||||
assert.equal(publicResponse.status, 200);
|
||||
const video = Buffer.from(await publicResponse.arrayBuffer());
|
||||
assert.equal(video.length, composed.outputs[0].sizeBytes);
|
||||
assert.equal(video.subarray(4, 8).toString("ascii"), "ftyp");
|
||||
console.log(JSON.stringify({
|
||||
baseGenerationId: submitted.generationId,
|
||||
composedGenerationId: composedSubmission.generationId,
|
||||
composedSizeBytes: video.length,
|
||||
publicUrl: composed.outputs[0].publicUrl,
|
||||
publicUrlExpiresAt: composed.outputs[0].publicUrlExpiresAt,
|
||||
}));
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
async function poll(client: Client, generationId: string, taskTraceId: string, attempts: number, intervalMs: number): Promise<any> {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const result = parseText(await client.callTool({ name: "query_tasks", arguments: { generationId, taskTraceId, include_base64: false } }));
|
||||
console.log(JSON.stringify({ generationId, attempt, status: result.status }));
|
||||
if (result.status === "FAILED") assert.fail(`Job failed: ${JSON.stringify(result.error)}`);
|
||||
if (result.status === "COMPLETED") return result;
|
||||
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
||||
}
|
||||
assert.fail(`Job ${generationId} did not complete in time`);
|
||||
}
|
||||
|
||||
function parseText(result: any): any {
|
||||
const text = result.content?.find((item: any) => item.type === "text")?.text;
|
||||
assert.ok(text, "tool result did not contain JSON text");
|
||||
return JSON.parse(text);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
test("real MCP generate_image -> query_tasks returns a decodable image", { timeout: 240_000 }, async (t) => {
|
||||
if (!process.env.GEMINI_API_KEY || !process.env.MCP_SERVER_TOKEN) {
|
||||
t.skip("Set GEMINI_API_KEY and MCP_SERVER_TOKEN to run the paid real integration test");
|
||||
return;
|
||||
}
|
||||
const endpoint = new URL(process.env.MCP_TEST_URL || "http://127.0.0.1:8087/mcp");
|
||||
const transport = new StreamableHTTPClientTransport(endpoint, { requestInit: { headers: { Authorization: `Bearer ${process.env.MCP_SERVER_TOKEN}` } } });
|
||||
const client = new Client({ name: "gemini-veo-real-integration", version: "1.0.0" });
|
||||
await client.connect(transport);
|
||||
try {
|
||||
const submitted = parseText(await client.callTool({ name: "generate_image", arguments: {
|
||||
model: "gemini-2.5-flash-image",
|
||||
arguments: [{ name: "prompt", value: "A minimal flat vector blue circle centered on a white background. No text." }, { name: "resolution", value: "1K" }, { name: "aspect_ratio", value: "1:1" }, { name: "image_count", value: 1 }],
|
||||
} }));
|
||||
assert.equal(submitted.status, "QUEUING");
|
||||
assert.match(String(submitted.generationId), /^[0-9a-f-]{36}$/);
|
||||
|
||||
let completed: any;
|
||||
for (let attempt = 0; attempt < 36; attempt += 1) {
|
||||
const polled = parseText(await client.callTool({ name: "query_tasks", arguments: { generationId: submitted.generationId, include_base64: true } }));
|
||||
if (polled.status === "FAILED") assert.fail(`Generation failed: ${JSON.stringify(polled.error)}`);
|
||||
if (polled.status === "COMPLETED") { completed = polled; break; }
|
||||
await new Promise((resolve) => setTimeout(resolve, 5_000));
|
||||
}
|
||||
assert.ok(completed, "generation did not complete within 180 seconds");
|
||||
assert.equal(completed.outputs.length, 1);
|
||||
assert.ok(completed.outputs[0].base64, "expected inline base64 output");
|
||||
const image = Buffer.from(completed.outputs[0].base64, "base64");
|
||||
const isPng = image.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
|
||||
const isJpeg = image[0] === 0xff && image[1] === 0xd8 && image[2] === 0xff;
|
||||
assert.ok(isPng || isJpeg, "decoded base64 is not a valid PNG/JPEG image");
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
function parseText(result: any): any {
|
||||
const text = result.content?.find((item: any) => item.type === "text")?.text;
|
||||
assert.ok(text, "tool result did not contain JSON text");
|
||||
return JSON.parse(text);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { rm } from "node:fs/promises";
|
||||
import test, { after } from "node:test";
|
||||
import { normalizeArguments } from "../src/arguments.js";
|
||||
import { estimateCost, resolveModel } from "../src/catalog.js";
|
||||
import { JobManager } from "../src/jobs.js";
|
||||
import { ensureMediaDir, loadPersistedJob, mediaDir, outputPayload, persistCompletedJob, purgeGeneration, storeBase64 } from "../src/media.js";
|
||||
import { isTransient } from "../src/retry.js";
|
||||
import type { GenerationJob } from "../src/types.js";
|
||||
|
||||
await ensureMediaDir();
|
||||
after(async () => { await rm(mediaDir, { recursive: true, force: true }); });
|
||||
|
||||
test("resolves public aliases and estimates current Veo pricing", () => {
|
||||
const model = resolveModel("veo-3.1-fast", "video");
|
||||
const args = normalizeArguments(model, [
|
||||
{ name: "prompt", value: "A short vertical brand film" },
|
||||
{ name: "resolution", value: "1080p" },
|
||||
{ name: "duration_seconds", value: 8 },
|
||||
]);
|
||||
assert.equal(model.canonicalApiModel, "veo-3.1-fast-generate-preview");
|
||||
assert.equal(estimateCost(model, args), 0.96);
|
||||
});
|
||||
|
||||
test("rejects unsupported Veo combinations and audio=false", () => {
|
||||
const model = resolveModel("veo-3.1-lite", "video");
|
||||
assert.throws(() => normalizeArguments(model, [{ name: "prompt", value: "x" }, { name: "resolution", value: "1080p" }, { name: "duration_seconds", value: 4 }]), /requires duration_seconds=8/);
|
||||
assert.throws(() => normalizeArguments(model, [{ name: "prompt", value: "x" }, { name: "with_audio", value: false }]), /Invalid 'with_audio'.*Allowed: true/);
|
||||
});
|
||||
|
||||
test("only transient provider errors are retryable", () => {
|
||||
assert.equal(isTransient({ status: 429 }), true);
|
||||
assert.equal(isTransient({ status: 503 }), true);
|
||||
assert.equal(isTransient({ status: 400 }), false);
|
||||
});
|
||||
|
||||
test("accepts a valid inline reference image and rejects mismatched MIME", () => {
|
||||
const model = resolveModel("nano-banana-2", "image");
|
||||
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]).toString("base64");
|
||||
const args = normalizeArguments(model, [
|
||||
{ name: "prompt", value: "Continue this visual style" },
|
||||
{ name: "reference_images", value: [{ base64: png, mime_type: "image/png" }] },
|
||||
]);
|
||||
assert.equal((args.reference_images as unknown[]).length, 1);
|
||||
assert.throws(() => normalizeArguments(model, [
|
||||
{ name: "prompt", value: "Continue this visual style" },
|
||||
{ name: "reference_images", value: [{ base64: png, mime_type: "image/jpeg" }] },
|
||||
]), /content does not match image\/jpeg/);
|
||||
});
|
||||
|
||||
test("resolves a generation_id reference and a mixed reference array", async () => {
|
||||
const manager = managerWithJobs();
|
||||
const source = await completedImageJob();
|
||||
injectJob(manager, source);
|
||||
const inline = tinyPng();
|
||||
const resolved = await manager.resolveImageReferences({ reference_images: [
|
||||
{ generation_id: source.generationId, index: 0 },
|
||||
{ base64: inline, mime_type: "image/png" },
|
||||
] });
|
||||
const references = resolved.reference_images as Array<Record<string, unknown>>;
|
||||
assert.equal(references.length, 2);
|
||||
assert.equal(references[0].mime_type, "image/png");
|
||||
assert.equal(references[0].base64, inline);
|
||||
assert.equal(references[1].base64, inline);
|
||||
});
|
||||
|
||||
test("generation_id reference reports nonexistent generation", async () => {
|
||||
const manager = managerWithJobs();
|
||||
await assert.rejects(
|
||||
manager.resolveImageReferences({ reference_images: [{ generation_id: randomUUID(), index: 0 }] }),
|
||||
/REFERENCE_GENERATION_NOT_FOUND/,
|
||||
);
|
||||
});
|
||||
|
||||
test("generation_id reference reports generation not completed", async () => {
|
||||
const manager = managerWithJobs();
|
||||
const source = jobFixture({ status: "RUNNING" });
|
||||
injectJob(manager, source);
|
||||
await assert.rejects(
|
||||
manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 0 }] }),
|
||||
/REFERENCE_GENERATION_NOT_COMPLETED.*RUNNING/,
|
||||
);
|
||||
});
|
||||
|
||||
test("generation_id reference reports output index out of range", async () => {
|
||||
const manager = managerWithJobs();
|
||||
const source = await completedImageJob();
|
||||
injectJob(manager, source);
|
||||
await assert.rejects(
|
||||
manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 7 }] }),
|
||||
/REFERENCE_INDEX_OUT_OF_RANGE/,
|
||||
);
|
||||
});
|
||||
|
||||
test("generation_id reference reports expired or purged generation", async () => {
|
||||
const manager = managerWithJobs();
|
||||
const source = await completedImageJob();
|
||||
await purgeGeneration(source);
|
||||
await assert.rejects(
|
||||
manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 0 }] }),
|
||||
/REFERENCE_GENERATION_EXPIRED/,
|
||||
);
|
||||
});
|
||||
|
||||
test("generation_id reference rejects a video generation", async () => {
|
||||
const manager = managerWithJobs();
|
||||
const source = jobFixture({ kind: "video", status: "COMPLETED", outputs: [] });
|
||||
injectJob(manager, source);
|
||||
await assert.rejects(
|
||||
manager.resolveImageReferences({ reference_images: [{ generation_id: source.generationId, index: 0 }] }),
|
||||
/REFERENCE_IS_VIDEO/,
|
||||
);
|
||||
});
|
||||
|
||||
test("include_base64=false payload is compact and always has a downloadUrl", async () => {
|
||||
const source = await completedImageJob();
|
||||
const payload = await outputPayload(source.outputs!, "https://mcp.example/media-service", false);
|
||||
assert.equal(payload[0].base64, undefined);
|
||||
assert.match(String(payload[0].downloadUrl), /^https:\/\/mcp\.example\/media-service\/media\//);
|
||||
assert.equal(payload[0].sha256, source.outputs![0].sha256);
|
||||
});
|
||||
|
||||
test("completed generation metadata survives a disk round-trip", async () => {
|
||||
const source = await completedImageJob();
|
||||
await persistCompletedJob(source);
|
||||
const restored = await loadPersistedJob(source.generationId);
|
||||
assert.equal(restored?.status, "COMPLETED");
|
||||
assert.equal(restored?.outputs?.[0].sha256, source.outputs?.[0].sha256);
|
||||
assert.equal(restored?.outputs?.[0].index, 0);
|
||||
});
|
||||
|
||||
function managerWithJobs(): JobManager {
|
||||
return new JobManager({} as never);
|
||||
}
|
||||
|
||||
function injectJob(manager: JobManager, job: GenerationJob): void {
|
||||
(manager as unknown as { jobs: Map<string, GenerationJob> }).jobs.set(job.generationId, job);
|
||||
}
|
||||
|
||||
async function completedImageJob(): Promise<GenerationJob> {
|
||||
const generationId = randomUUID();
|
||||
const output = await storeBase64(generationId, 0, tinyPng(), "image/png");
|
||||
return jobFixture({ generationId, status: "COMPLETED", outputs: [output] });
|
||||
}
|
||||
|
||||
function jobFixture(overrides: Partial<GenerationJob> = {}): GenerationJob {
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
generationId: randomUUID(),
|
||||
kind: "image",
|
||||
model: "gemini-2.5-flash-image",
|
||||
canonicalModel: "gemini-2.5-flash-image",
|
||||
arguments: {},
|
||||
estimatedCostUsd: 0.039,
|
||||
status: "QUEUING",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function tinyPng(): string {
|
||||
return Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]).toString("base64");
|
||||
}
|
||||
Reference in new issue
Block a user