mirror of
https://github.com/Dasemu/gemini-media-mcp.git
synced 2026-11-26 07:16:09 +00:00
Initial commit
This commit is contained in:
commit
85fbc8b05a
27 files changed
+4465
No files matched your search
@@ -0,0 +1,18 @@
|
||||
GEMINI_API_KEY=
|
||||
MCP_SERVER_TOKEN=replace-with-a-long-random-secret
|
||||
HOST=127.0.0.1
|
||||
PORT=8087
|
||||
PUBLIC_BASE_URL=https://mcp.zenvairo.es/zenvairogoogle
|
||||
PUBLIC_MEDIA_SIGNING_SECRET=replace-with-at-least-32-random-characters
|
||||
PUBLIC_MEDIA_URL_TTL_SECONDS=86400
|
||||
MEDIA_DIR=/opt/gemini-veo-mcp/media
|
||||
MAX_INLINE_MEDIA_MB=25
|
||||
MAX_MEDIA_MB=300
|
||||
MAX_REFERENCE_INPUT_MB=25
|
||||
MAX_MCP_REQUEST_MB=40
|
||||
MEDIA_RETENTION_HOURS=168
|
||||
TOMBSTONE_RETENTION_DAYS=30
|
||||
PYTHON_BIN=python3
|
||||
FFMPEG_BIN=ffmpeg
|
||||
FFPROBE_BIN=ffprobe
|
||||
OVERLAY_CARD_SCRIPT=/opt/gemini-veo-mcp/scripts/make_overlay_card.py
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
deploy/.basic-password
|
||||
deploy/.server-token
|
||||
deploy/gemini-veo-mcp.env
|
||||
deploy/zenvairogoogle.conf
|
||||
deploy/zenvairogoogle.htpasswd
|
||||
media/*
|
||||
!media/.gitkeep
|
||||
gemini-veo-mcp.env
|
||||
@@ -0,0 +1,120 @@
|
||||
# Zenvairo Google Media MCP
|
||||
|
||||
Servidor MCP remoto y *stateless* (Streamable HTTP) para generación de imágenes con Gemini y vídeo con Veo 3.1. Sigue el contrato `submit + poll`: `generate_image`/`generate_video` devuelven inmediatamente un UUID y `query_tasks` entrega el resultado final.
|
||||
|
||||
## API y credenciales de Google
|
||||
|
||||
A fecha de referencia **2026-08-14**, Veo 3.1 Standard, Fast y Lite están disponibles en la capa de pago de la **Gemini Developer API**. Por tanto, tanto imagen como vídeo usan únicamente `GEMINI_API_KEY`; no se requieren `GOOGLE_APPLICATION_CREDENTIALS`, `GCP_PROJECT_ID` ni `GCP_LOCATION` para los modelos expuestos aquí.
|
||||
|
||||
Fuentes oficiales:
|
||||
|
||||
- Imagen: https://ai.google.dev/gemini-api/docs/image-generation
|
||||
- Veo: https://ai.google.dev/gemini-api/docs/veo
|
||||
- Precios: https://ai.google.dev/gemini-api/docs/pricing
|
||||
|
||||
La clave nunca forma parte de los schemas o respuestas MCP. El proceso arranca sin clave para permitir `who_am_i` y health checks, pero los jobs fallarán con `SERVER_NOT_CONFIGURED` hasta configurarla.
|
||||
|
||||
## Tools
|
||||
|
||||
- `who_am_i`: catálogo por tipo, alias, argumentos, restricciones y precios oficiales de referencia.
|
||||
- `generate_image`: envío no bloqueante de una o varias imágenes.
|
||||
- `generate_video`: envío no bloqueante de un vídeo Veo.
|
||||
- `compose_video_overlay`: composición local no bloqueante de tarjetas Pillow sobre un vídeo retenido, con un nuevo `generationId`.
|
||||
- `query_tasks`: polling compartido y entrega final.
|
||||
- `get_usage`: estimaciones acumuladas desde el último arranque. Google no expone el saldo restante de facturación mediante esta API.
|
||||
|
||||
`arguments` siempre es una lista `{ "name": ..., "value": ... }`, compatible con el patrón del conector Kling. Veo 3.1 siempre genera audio; `with_audio=false` se rechaza explícitamente.
|
||||
|
||||
### Encadenar imágenes de referencia
|
||||
|
||||
`generate_image` acepta `reference_images` con dos variantes mezclables. La recomendada referencia una generación terminada por UUID, de modo que los bytes viajan directamente del disco del servidor a Gemini y nunca pasan por el contexto del LLM:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "gemini-3.1-flash-image",
|
||||
"arguments": [
|
||||
{ "name": "prompt", "value": "Crea la slide 2 manteniendo exactamente el estilo visual de la referencia" },
|
||||
{
|
||||
"name": "reference_images",
|
||||
"value": [
|
||||
{ "generation_id": "<generationId de la slide anterior>", "index": 0 }
|
||||
]
|
||||
},
|
||||
{ "name": "aspect_ratio", "value": "4:5" },
|
||||
{ "name": "resolution", "value": "1K" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
La variante inline anterior sigue siendo compatible: `{ "base64": "...", "mime_type": "image/png" }`. Un mismo array puede mezclar referencias por ID e inline. Se admiten PNG, JPEG y WebP, hasta 20 MiB por referencia inline y 25 MiB agregados por request. Los límites de cantidad son 3 referencias para Gemini 2.5 Flash Image y 14 para los modelos Gemini 3 expuestos. Las referencias nunca se escriben en logs.
|
||||
|
||||
Las referencias por ID producen códigos claros: `REFERENCE_GENERATION_NOT_FOUND`, `REFERENCE_GENERATION_NOT_COMPLETED`, `REFERENCE_INDEX_OUT_OF_RANGE`, `REFERENCE_GENERATION_EXPIRED` y `REFERENCE_IS_VIDEO`.
|
||||
|
||||
### Componer tarjetas sobre un vídeo
|
||||
|
||||
`compose_video_overlay` recibe el `generationId` de un vídeo vertical 9:16 ya `COMPLETED` y entre 1 y 10 tarjetas temporizadas. Devuelve inmediatamente un `generationId` nuevo; el trabajo se realiza localmente con Pillow, Poppins Bold y ffmpeg, conserva el audio original y se consulta con el mismo `query_tasks`:
|
||||
|
||||
```json
|
||||
{
|
||||
"base_generation_id": "<generationId del video Veo>",
|
||||
"overlays": [
|
||||
{ "kicker": "GANCHO", "text": "Tu equipo no necesita más herramientas", "style": "normal", "start_time": 0.6, "duration": 2.5 },
|
||||
{ "kicker": "SIGUIENTE PASO", "text": "Automatiza lo repetitivo", "style": "cta", "start_time": 4.8, "duration": 2.5 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
El vídeo base no se descarga ni regenera: sus bytes pasan del almacén retenido al proceso ffmpeg. El resultado se persiste como otra generación `video/mp4`, con tamaño y SHA-256 reales, retención normal y las mismas `downloadUrl`/`publicUrl`. Los timings deben quedar dentro de la duración real del vídeo; los errores usan códigos `COMPOSE_*` explícitos. Los textos de las tarjetas no se registran en logs.
|
||||
|
||||
## Entrega de medios y límites
|
||||
|
||||
`query_tasks` usa `include_base64=false` por defecto para que los binarios no entren accidentalmente en el contexto del LLM. Cada output devuelve `index`, `mimeType`, `sizeBytes`, `sha256`, el `downloadUrl` protegido anterior y una `publicUrl` firmada que Meta puede descargar sin credenciales. El base64 continúa disponible de forma explícita con `include_base64=true` cuando el tamaño binario agregado del job es como máximo **25 MiB exactos (26.214.400 bytes)**.
|
||||
|
||||
`publicUrl` usa el mismo dominio bajo `/zenvairogoogle/public-media/...`, lleva una firma HMAC ligada al nombre y caducidad, y dura 24 horas por defecto (`PUBLIC_MEDIA_URL_TTL_SECONDS=86400`). La ruta no acepta Basic ni Bearer porque Meta debe leerla directamente; sin firma válida responde 403 y una firma caducada responde 410. Cada llamada posterior a `query_tasks` emite una URL nueva mientras el resultado siga retenido.
|
||||
|
||||
El `downloadUrl` anterior bajo `/zenvairogoogle/media/...` continúa protegido por las credenciales HTTP Basic del conector. Nunca se devuelve una URL de Google, GCS o un CDN tercero. La clave HMAC (`PUBLIC_MEDIA_SIGNING_SECRET`, mínimo 32 caracteres) solo existe en el servidor y no aparece en schemas, logs o respuestas.
|
||||
|
||||
Para publicar sin copiar ni mover base64, pasa `outputs[].publicUrl` directamente a `publish_post` de SocialMCP como `imageUrl`, `videoUrl` o `media[].url`. No llames antes a `upload_media`.
|
||||
|
||||
Los resultados completados se guardan en disco, indexados por `generationId`, con bytes, MIME, SHA-256 e índice en un manifiesto atómico. Se restauran después de reiniciar el servicio y se conservan **7 días (168 horas)** por defecto mediante `MEDIA_RETENTION_HOURS`. Una tarea limpia archivos y manifiestos cada 15 minutos; conserva tombstones pequeños durante 30 días para distinguir IDs purgados de IDs inexistentes. Los jobs todavía pendientes siguen siendo memoria volátil.
|
||||
|
||||
Un artefacto individual mayor de 300 MiB se rechaza para proteger el disco del LXC. No hay reintentos silenciosos de moderación o validación; solo hasta 2 reintentos (3 intentos totales), registrados en log, para 429, 5xx y fallos transitorios de red.
|
||||
|
||||
## Despliegue LXC 210 (Alpine/OpenRC)
|
||||
|
||||
La instalación operativa está en `/opt/gemini-veo-mcp`, ejecutada como `mcp:mcp`, ligada a `127.0.0.1:8087` y supervisada por OpenRC (`gemini-veo-mcp`). nginx protege `/zenvairogoogle/` con Basic y deja pública únicamente `/zenvairogoogle/public-media/`; la aplicación exige en esa ruta una firma HMAC válida y caducable.
|
||||
|
||||
Para añadir la API key:
|
||||
|
||||
```sh
|
||||
pct exec 210 -- vi /opt/gemini-veo-mcp/gemini-veo-mcp.env
|
||||
pct exec 210 -- rc-service gemini-veo-mcp restart
|
||||
```
|
||||
|
||||
Comprobaciones:
|
||||
|
||||
```sh
|
||||
pct exec 210 -- rc-service gemini-veo-mcp status
|
||||
pct exec 210 -- tail -f /var/log/gemini-veo-mcp.log
|
||||
```
|
||||
|
||||
Los logs son JSON Lines e incluyen modelo, UUID, duración, bytes de salida, coste estimado y reintentos; no incluyen prompts ni credenciales.
|
||||
|
||||
## Test real pagado
|
||||
|
||||
El test usa el MCP completo: `generate_image` → `query_tasks` hasta `COMPLETED`, decodifica base64 y valida la firma PNG/JPEG. Tras configurar la key y reiniciar:
|
||||
|
||||
```sh
|
||||
pct exec 210 -- /bin/sh -lc 'cd /opt/gemini-veo-mcp && set -a && . ./gemini-veo-mcp.env && set +a && npm run test:integration'
|
||||
```
|
||||
|
||||
Sin credenciales el test se marca como `SKIP` y no incurre en coste.
|
||||
|
||||
## Claude.ai / Cowork
|
||||
|
||||
1. En Claude.ai, abre **Settings → Connectors → Add custom connector**.
|
||||
2. Usa la URL HTTPS proporcionada al finalizar el despliegue, que ya incorpora el usuario y contraseña HTTP Basic.
|
||||
3. Activa las tools del conector en Cowork.
|
||||
4. Llama primero a `who_am_i`; después envía con `generate_*` y consulta el UUID con `query_tasks` hasta estado terminal.
|
||||
|
||||
Para vídeo, espera entre 11 segundos y 6 minutos según la documentación oficial. Evita polling agresivo; 10–15 segundos es razonable.
|
||||
@@ -0,0 +1,148 @@
|
||||
server {
|
||||
listen 80 default_server;
|
||||
server_name _;
|
||||
|
||||
location /zenvairogit/ {
|
||||
auth_basic "ZenvairoGit MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairogit;
|
||||
|
||||
proxy_pass http://127.0.0.1:8081/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
proxy_set_header Mcp-Protocol-Version $http_mcp_protocol_version;
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
|
||||
location /zenvairocloud/ {
|
||||
auth_basic "ZenvairoCloud MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairocloud;
|
||||
|
||||
proxy_pass http://127.0.0.1:8082/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8082;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
|
||||
location /zenvairoanalytics/ {
|
||||
auth_basic "ZenvairoAnalytics MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairoanalytics;
|
||||
|
||||
proxy_pass http://127.0.0.1:8083/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8083;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
|
||||
location /zenvairomail/ {
|
||||
auth_basic "ZenvairoMail MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairomail;
|
||||
|
||||
proxy_pass http://127.0.0.1:8084/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8084;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
|
||||
location /zenvairocrm/ {
|
||||
auth_basic "ZenvairoCRM MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairocrm;
|
||||
|
||||
proxy_pass http://127.0.0.1:8085/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8085;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
|
||||
# Archivos subidos con upload_media: SIN Basic Auth, para que Meta pueda
|
||||
# descargarlos al publicar (nombre de archivo aleatorio tipo UUID).
|
||||
location /zenvairosocial/media/ {
|
||||
proxy_pass http://127.0.0.1:8086/media/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8086;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
|
||||
location /zenvairosocial/ {
|
||||
auth_basic "ZenvairoSocial MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairosocial;
|
||||
|
||||
proxy_pass http://127.0.0.1:8086/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8086;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
proxy_set_header Mcp-Protocol-Version $http_mcp_protocol_version;
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
|
||||
include /etc/nginx/http.d/zenvairogoogle.inc;
|
||||
|
||||
location = / {
|
||||
return 404;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
GEMINI_API_KEY=
|
||||
MCP_SERVER_TOKEN=__MCP_SERVER_TOKEN__
|
||||
HOST=127.0.0.1
|
||||
PORT=8087
|
||||
PUBLIC_BASE_URL=https://mcp.zenvairo.es/zenvairogoogle
|
||||
PUBLIC_MEDIA_SIGNING_SECRET=replace-with-at-least-32-random-characters
|
||||
PUBLIC_MEDIA_URL_TTL_SECONDS=86400
|
||||
MEDIA_DIR=/opt/gemini-veo-mcp/media
|
||||
MAX_INLINE_MEDIA_MB=25
|
||||
MAX_MEDIA_MB=300
|
||||
MAX_REFERENCE_INPUT_MB=25
|
||||
MAX_MCP_REQUEST_MB=40
|
||||
MEDIA_RETENTION_HOURS=168
|
||||
TOMBSTONE_RETENTION_DAYS=30
|
||||
PYTHON_BIN=python3
|
||||
FFMPEG_BIN=ffmpeg
|
||||
FFPROBE_BIN=ffprobe
|
||||
OVERLAY_CARD_SCRIPT=/opt/gemini-veo-mcp/scripts/make_overlay_card.py
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/sbin/openrc-run
|
||||
|
||||
name="gemini-veo-mcp"
|
||||
description="Gemini and Veo MCP server (Streamable HTTP, 127.0.0.1:8087)"
|
||||
command="/usr/bin/node"
|
||||
command_args="/opt/gemini-veo-mcp/dist/index.js"
|
||||
directory="/opt/gemini-veo-mcp"
|
||||
command_user="mcp:mcp"
|
||||
command_background="yes"
|
||||
pidfile="/run/${RC_SVCNAME}.pid"
|
||||
output_log="/var/log/${RC_SVCNAME}.log"
|
||||
error_log="/var/log/${RC_SVCNAME}.log"
|
||||
env_file="/opt/gemini-veo-mcp/gemini-veo-mcp.env"
|
||||
|
||||
start_pre() {
|
||||
checkpath -d -m 0750 -o mcp:mcp /opt/gemini-veo-mcp/media
|
||||
checkpath -f -m 0640 -o mcp:mcp "${output_log}"
|
||||
set -a
|
||||
[ -f "${env_file}" ] && . "${env_file}"
|
||||
set +a
|
||||
}
|
||||
|
||||
depend() {
|
||||
need net
|
||||
after nginx
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Public only when the application validates the expiring HMAC signature.
|
||||
location /zenvairogoogle/public-media/ {
|
||||
auth_basic off;
|
||||
|
||||
proxy_pass http://127.0.0.1:8087/public-media/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8087;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 600s;
|
||||
}
|
||||
|
||||
location /zenvairogoogle/media/ {
|
||||
auth_basic "Zenvairo Google Media MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairogoogle;
|
||||
|
||||
proxy_pass http://127.0.0.1:8087/media/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8087;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-MCP-Server-Token "__MCP_SERVER_TOKEN__";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
}
|
||||
|
||||
location /zenvairogoogle/ {
|
||||
auth_basic "Zenvairo Google Media MCP";
|
||||
auth_basic_user_file /etc/nginx/htpasswd/zenvairogoogle;
|
||||
client_max_body_size 40m;
|
||||
|
||||
proxy_pass http://127.0.0.1:8087/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1:8087;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Origin "";
|
||||
proxy_set_header X-MCP-Server-Token "__MCP_SERVER_TOKEN__";
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
|
||||
proxy_set_header Mcp-Protocol-Version $http_mcp_protocol_version;
|
||||
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
Generated
+2110
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@zenvairo/gemini-veo-mcp",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Remote Streamable HTTP MCP server for Google Gemini image and Veo video generation",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx src/index.ts",
|
||||
"test": "MEDIA_DIR=/tmp/gemini-veo-mcp-tests-$$ node --import tsx --test test/unit.test.ts",
|
||||
"test:integration": "node --import tsx --test test/integration-real.test.ts",
|
||||
"test:integration:compose": "node --import tsx --test test/integration-compose-real.test.ts"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@google/genai": "2.17.1",
|
||||
"@modelcontextprotocol/sdk": "1.30.0",
|
||||
"dotenv": "16.6.1",
|
||||
"express": "5.2.1",
|
||||
"zod": "3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "5.0.3",
|
||||
"@types/node": "24.3.0",
|
||||
"tsx": "4.20.5",
|
||||
"typescript": "5.9.2"
|
||||
}
|
||||
}
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
import sys, json
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
W, H = 720, 1280
|
||||
POPPINS_BOLD = "/usr/share/fonts/zenvairo/Poppins-Bold.ttf"
|
||||
NAVY = (10, 22, 48)
|
||||
CYAN = (45, 224, 234)
|
||||
WHITE = (255, 255, 255)
|
||||
|
||||
def wrap_text(draw, text, font, max_width):
|
||||
words = text.split()
|
||||
lines, cur = [], ""
|
||||
for w in words:
|
||||
trial = (cur + " " + w).strip()
|
||||
bbox = draw.textbbox((0,0), trial, font=font)
|
||||
if bbox[2] - bbox[0] <= max_width or not cur:
|
||||
cur = trial
|
||||
else:
|
||||
lines.append(cur)
|
||||
cur = w
|
||||
if cur:
|
||||
lines.append(cur)
|
||||
return lines
|
||||
|
||||
def rounded_rect_with_shadow(size, radius, fill, shadow_blur=18, shadow_offset=(0,10), shadow_opacity=110):
|
||||
w, h = size
|
||||
pad = shadow_blur * 3
|
||||
canvas = Image.new("RGBA", (w + pad*2, h + pad*2), (0,0,0,0))
|
||||
shadow = Image.new("RGBA", canvas.size, (0,0,0,0))
|
||||
sd = ImageDraw.Draw(shadow)
|
||||
sx, sy = pad + shadow_offset[0], pad + shadow_offset[1]
|
||||
sd.rounded_rectangle([sx, sy, sx+w, sy+h], radius=radius, fill=(0,0,0,shadow_opacity))
|
||||
shadow = shadow.filter(ImageFilter.GaussianBlur(shadow_blur))
|
||||
canvas = Image.alpha_composite(canvas, shadow)
|
||||
box = Image.new("RGBA", canvas.size, (0,0,0,0))
|
||||
bd = ImageDraw.Draw(box)
|
||||
bd.rounded_rectangle([pad, pad, pad+w, pad+h], radius=radius, fill=fill)
|
||||
canvas = Image.alpha_composite(canvas, box)
|
||||
return canvas, pad
|
||||
|
||||
def make_card(text, out_path, kicker=None, style="normal", max_text_width=560):
|
||||
img = Image.new("RGBA", (W, H), (0,0,0,0))
|
||||
font_size = 50 if len(text) < 40 else (44 if len(text) < 70 else 38)
|
||||
font = ImageFont.truetype(POPPINS_BOLD, font_size)
|
||||
tmp_draw = ImageDraw.Draw(img)
|
||||
lines = wrap_text(tmp_draw, text, font, max_text_width - 80)
|
||||
line_h = font.getbbox("Ay")[3] - font.getbbox("Ay")[1]
|
||||
line_spacing = int(line_h * 1.35)
|
||||
kicker_h = 0
|
||||
kfont = None
|
||||
if kicker:
|
||||
kfont = ImageFont.truetype(POPPINS_BOLD, 26)
|
||||
kicker_h = 50
|
||||
text_block_h = len(lines) * line_spacing + kicker_h
|
||||
pill_h = text_block_h + 70
|
||||
pill_w = max_text_width
|
||||
if style == "cta":
|
||||
fill = (*CYAN, 255); text_color = NAVY; kicker_color = NAVY; accent = None
|
||||
else:
|
||||
fill = (*NAVY, 235); text_color = WHITE; kicker_color = CYAN; accent = CYAN
|
||||
pill, pad = rounded_rect_with_shadow((pill_w, pill_h), radius=34, fill=fill)
|
||||
if accent:
|
||||
ad = ImageDraw.Draw(pill)
|
||||
ad.rounded_rectangle([pad, pad, pad+10, pad+pill_h], radius=5, fill=(*accent,255))
|
||||
py = pad + 35
|
||||
if kicker:
|
||||
kd = ImageDraw.Draw(pill)
|
||||
kd.text((pad + pill_w/2, py), kicker, font=kfont, fill=(*kicker_color,255), anchor="ma")
|
||||
py += kicker_h
|
||||
dd = ImageDraw.Draw(pill)
|
||||
for line in lines:
|
||||
dd.text((pad + pill_w/2, py), line, font=font, fill=(*text_color,255), anchor="ma")
|
||||
py += line_spacing
|
||||
px = (W - pill.width) // 2
|
||||
py_pos = int(H * 0.62) - pill.height // 2
|
||||
img.alpha_composite(pill, (px, py_pos))
|
||||
img.save(out_path)
|
||||
|
||||
if __name__ == "__main__":
|
||||
cfg = json.loads(sys.argv[1])
|
||||
make_card(cfg["text"], cfg["out"], kicker=cfg.get("kicker"), style=cfg.get("style","normal"))
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user