diff --git a/README.md b/README.md index 238993f..c5be0c8 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,21 @@ -# Zenvairo Google Media MCP +# Zenvairo Media Generator 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. +Remote, stateless (Streamable HTTP) MCP server for image generation with Gemini and video generation with Veo 3.1. It follows the `submit + poll` contract: `generate_image`/`generate_video` return a UUID immediately and `query_tasks` delivers the final result. ## Quick start ```sh npm ci -cp .env.example .env # rellena GEMINI_API_KEY y los demás valores -npm run dev # o: npm run build && npm start +cp .env.example .env # fill in GEMINI_API_KEY and the other values +npm run dev # or: npm run build && npm start ``` -Tools disponibles: `who_am_i`, `generate_image`, `generate_video`, `compose_video_overlay`, `query_tasks`, `get_usage`. +Available tools: `who_am_i`, `generate_image`, `generate_video`, `compose_video_overlay`, `query_tasks`, `get_usage`. -## Documentación +## Documentation -- [`docs/api.md`](docs/api.md) — credenciales de Google, tools, referencias de imagen y composición de overlays. -- [`docs/media-delivery.md`](docs/media-delivery.md) — entrega de medios, límites y retención. -- [`docs/deployment.md`](docs/deployment.md) — despliegue en LXC 210 (Alpine/OpenRC) y test de integración pagado. -- [`docs/integration.md`](docs/integration.md) — alta como conector en Claude.ai / Cowork. -- [`CLAUDE.md`](CLAUDE.md) — comandos, arquitectura y convenciones para desarrollo. +- [`docs/api.md`](docs/api.md) - Google credentials, tools, image references and overlay composition. +- [`docs/media-delivery.md`](docs/media-delivery.md) - media delivery, limits and retention. +- [`docs/deployment.md`](docs/deployment.md) - deployment on LXC 210 (Alpine/OpenRC) and the paid integration test. +- [`docs/integration.md`](docs/integration.md) - registering the server as a Claude.ai / Cowork connector. +- [`CLAUDE.md`](CLAUDE.md) - commands, architecture and conventions for development. diff --git a/docs/api.md b/docs/api.md index 38f97fc..a6a0a25 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,39 +1,39 @@ -# API y credenciales de Google +# API and Google credentials -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í. +As of the reference date **2026-08-14**, Veo 3.1 Standard, Fast and Lite are available on the paid tier of the **Gemini Developer API**. Both image and video generation therefore use only `GEMINI_API_KEY`; `GOOGLE_APPLICATION_CREDENTIALS`, `GCP_PROJECT_ID` and `GCP_LOCATION` are not required for the models exposed here. -Fuentes oficiales: +Official sources: -- Imagen: https://ai.google.dev/gemini-api/docs/image-generation +- Image: 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 +- Pricing: 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. +The key is never part of MCP schemas or responses. The process starts without a key so that `who_am_i` and health checks work, but jobs fail with `SERVER_NOT_CONFIGURED` until it is configured. ## 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. +- `who_am_i`: catalog by type, aliases, arguments, constraints and official reference prices. +- `generate_image`: non-blocking submission of one or more images. +- `generate_video`: non-blocking submission of one Veo video. +- `compose_video_overlay`: non-blocking local composition of Pillow cards over a retained video, producing a new `generationId`. +- `query_tasks`: shared polling and final delivery. +- `get_usage`: cumulative estimates since the last start. Google does not expose the remaining billing balance through this 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. +`arguments` is always a list of `{ "name": ..., "value": ... }`, compatible with the Kling connector pattern. Veo 3.1 always generates audio; `with_audio=false` is rejected explicitly. -## Encadenar imágenes de referencia +## Chaining reference images -`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: +`generate_image` accepts `reference_images` in two mixable variants. The recommended one references a finished generation by UUID, so the bytes travel directly from the server disk to Gemini and never pass through the LLM context: ```json { "model": "gemini-3.1-flash-image", "arguments": [ - { "name": "prompt", "value": "Crea la slide 2 manteniendo exactamente el estilo visual de la referencia" }, + { "name": "prompt", "value": "Create slide 2, keeping exactly the visual style of the reference" }, { "name": "reference_images", "value": [ - { "generation_id": "", "index": 0 } + { "generation_id": "", "index": 0 } ] }, { "name": "aspect_ratio", "value": "4:5" }, @@ -42,22 +42,22 @@ La clave nunca forma parte de los schemas o respuestas MCP. El proceso arranca s } ``` -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. +The inline variant remains supported: `{ "base64": "...", "mime_type": "image/png" }`. A single array can mix ID-based and inline references. PNG, JPEG and WebP are accepted, up to 20 MiB per inline reference and 25 MiB aggregate per request. Count limits are 3 references for Gemini 2.5 Flash Image and 14 for the exposed Gemini 3 models. References are never written to 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`. +ID-based references produce clear error codes: `REFERENCE_GENERATION_NOT_FOUND`, `REFERENCE_GENERATION_NOT_COMPLETED`, `REFERENCE_INDEX_OUT_OF_RANGE`, `REFERENCE_GENERATION_EXPIRED` and `REFERENCE_IS_VIDEO`. -## Componer tarjetas sobre un vídeo +## Composing cards over a video -`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`: +`compose_video_overlay` takes the `generationId` of a vertical 9:16 video that is already `COMPLETED`, plus 1 to 10 timed cards. It immediately returns a new `generationId`; the work is done locally with Pillow, Poppins Bold and ffmpeg, keeps the original audio, and is queried with the same `query_tasks`: ```json { - "base_generation_id": "", + "base_generation_id": "", "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 } + { "kicker": "HOOK", "text": "Your team does not need more tools", "style": "normal", "start_time": 0.6, "duration": 2.5 }, + { "kicker": "NEXT STEP", "text": "Automate the repetitive work", "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. +The base video is neither downloaded nor regenerated: its bytes go from the retained store to the ffmpeg process. The result is persisted as another `video/mp4` generation with real size and SHA-256, normal retention and the same `downloadUrl`/`publicUrl`. Timings must fall within the real video duration; errors use explicit `COMPOSE_*` codes. Card texts are not logged. diff --git a/docs/deployment.md b/docs/deployment.md index ec0568a..0a065fe 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1,35 +1,35 @@ -# Despliegue LXC 210 (Alpine/OpenRC) +# Deployment on 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. +The operational install lives in `/opt/gemini-veo-mcp`, runs as `mcp:mcp`, binds to `127.0.0.1:8087` and is supervised by OpenRC (`gemini-veo-mcp`). nginx protects `/zenvairogoogle/` with Basic auth and leaves only `/zenvairogoogle/public-media/` public; the application requires a valid, expiring HMAC signature on that route. -Para añadir la API key: +To add the 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: +Checks: ```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. +Logs are JSON Lines and include model, UUID, duration, output bytes, estimated cost and retries; they do not include prompts or credentials. -Referencia de los ficheros de despliegue en `deploy/`: +Reference for the deployment files in `deploy/`: -- `gemini-veo-mcp.openrc`: servicio OpenRC. -- `gemini-veo-mcp.env.template`: plantilla de variables de entorno (sin secretos reales). -- `default.conf.lxc210`, `nginx-location.conf`: configuración de nginx. +- `gemini-veo-mcp.openrc`: OpenRC service. +- `gemini-veo-mcp.env.template`: environment variable template (no real secrets). +- `default.conf.lxc210`, `nginx-location.conf`: nginx configuration. -## Test real pagado +## Paid integration test -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: +The test uses the full MCP: `generate_image` -> `query_tasks` until `COMPLETED`, decodes base64 and validates the PNG/JPEG signature. After configuring the key and restarting: ```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. +Without credentials the test is marked `SKIP` and incurs no cost. diff --git a/docs/integration.md b/docs/integration.md index a5176d2..ea4729b 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -1,8 +1,8 @@ # 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. +1. In Claude.ai, open **Settings -> Connectors -> Add custom connector**. +2. Use the HTTPS URL provided at the end of the deployment, which already embeds the HTTP Basic username and password. +3. Enable the connector tools in Cowork. +4. Call `who_am_i` first; then submit with `generate_*` and poll the UUID with `query_tasks` until a terminal state. -Para vídeo, espera entre 11 segundos y 6 minutos según la documentación oficial. Evita polling agresivo; 10–15 segundos es razonable. +For video, expect between 11 seconds and 6 minutes according to the official documentation. Avoid aggressive polling; 10-15 seconds is reasonable. diff --git a/docs/media-delivery.md b/docs/media-delivery.md index b4d5b6c..5325bfc 100644 --- a/docs/media-delivery.md +++ b/docs/media-delivery.md @@ -1,13 +1,13 @@ -# Entrega de medios y límites +# Media delivery and limits -`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)**. +`query_tasks` uses `include_base64=false` by default so binaries do not accidentally enter the LLM context. Each output returns `index`, `mimeType`, `sizeBytes`, `sha256`, the protected `downloadUrl` and a signed `publicUrl` that Meta can download without credentials. Base64 remains available explicitly with `include_base64=true` when the job's aggregate binary size is at most **25 MiB exactly (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. +`publicUrl` uses the same domain under `/zenvairogoogle/public-media/...`, carries an HMAC signature bound to the file name and expiry, and lasts 24 hours by default (`PUBLIC_MEDIA_URL_TTL_SECONDS=86400`). The route accepts neither Basic nor Bearer because Meta must read it directly; without a valid signature it responds 403 and an expired signature responds 410. Each later `query_tasks` call issues a fresh URL while the result is still retained. -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. +The `downloadUrl` under `/zenvairogoogle/media/...` stays protected by the connector's HTTP Basic credentials. A Google, GCS or third-party CDN URL is never returned. The HMAC key (`PUBLIC_MEDIA_SIGNING_SECRET`, minimum 32 characters) exists only on the server and never appears in schemas, logs or responses. -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`. +To publish without copying or moving base64, pass `outputs[].publicUrl` directly to SocialMCP's `publish_post` as `imageUrl`, `videoUrl` or `media[].url`. Do not call `upload_media` first. -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. +Completed results are stored on disk, indexed by `generationId`, with bytes, MIME type, SHA-256 and index in an atomic manifest. They are restored after a service restart and kept **7 days (168 hours)** by default via `MEDIA_RETENTION_HOURS`. A task cleans up files and manifests every 15 minutes; small tombstones are kept for 30 days to distinguish purged IDs from nonexistent ones. Jobs still pending remain volatile in-memory state. -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. +A single artifact larger than 300 MiB is rejected to protect the LXC disk. There are no silent retries for moderation or validation failures; only up to 2 retries (3 attempts in total), logged, for 429, 5xx and transient network failures.