From 736419c39557fa30a5bbba3af69924b567afab32 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Sun, 18 Oct 2026 15:11:20 +0200 Subject: [PATCH 1/2] chore: bootstrap Claude setup Co-Authored-By: Claude Sonnet 5 --- .claude/bootstrap-version | 1 + .claude/settings.json | 25 +++++++ .github/workflows/ci.yml | 29 ++++++++ .github/workflows/version.yml | 59 +++++++++++++++++ CLAUDE.md | 33 ++++++++++ LESSONS.md | 5 ++ README.md | 121 ++++------------------------------ docs/api.md | 63 ++++++++++++++++++ docs/deployment.md | 35 ++++++++++ docs/integration.md | 8 +++ docs/media-delivery.md | 13 ++++ 11 files changed, 282 insertions(+), 110 deletions(-) create mode 100644 .claude/bootstrap-version create mode 100644 .claude/settings.json create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/version.yml create mode 100644 CLAUDE.md create mode 100644 LESSONS.md create mode 100644 docs/api.md create mode 100644 docs/deployment.md create mode 100644 docs/integration.md create mode 100644 docs/media-delivery.md diff --git a/.claude/bootstrap-version b/.claude/bootstrap-version new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/.claude/bootstrap-version @@ -0,0 +1 @@ +2 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..3ce0934 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,25 @@ +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "file=$(jq -r '.tool_input.file_path // empty'); if [ -n \"$file\" ] && [ \"${file##*.}\" = \"ts\" ]; then cd \"$CLAUDE_PROJECT_DIR\" && npx tsc --noEmit -p tsconfig.json; fi" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "cd \"$CLAUDE_PROJECT_DIR\" && npm run build && PUBLIC_MEDIA_SIGNING_SECRET=12345678901234567890123456789012 npm test" + } + ] + } + ] + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b002fa8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: CI + +on: + pull_request: + branches: [development] + push: + branches: [development, main] + +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Build (type-check) + run: npm run build + + - name: Unit tests + env: + PUBLIC_MEDIA_SIGNING_SECRET: "ci-dummy-secret-at-least-32-chars" + run: npm test diff --git a/.github/workflows/version.yml b/.github/workflows/version.yml new file mode 100644 index 0000000..98b4573 --- /dev/null +++ b/.github/workflows/version.yml @@ -0,0 +1,59 @@ +name: Version + +on: + push: + branches: [development, main] + +permissions: + contents: write + +jobs: + bump: + if: github.actor != 'github-actions[bot]' && !contains(github.event.head_commit.message, '[skip ci]') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Configure git identity + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Determine bump type + id: bump + run: | + if [ "${{ github.ref_name }}" = "development" ]; then + echo "type=patch" >> "$GITHUB_OUTPUT" + else + # main: a merge commit (2 parents) means this came from an approved + # development -> main PR; anything else is a direct hotfix push. + parents=$(git rev-list --parents -n 1 HEAD | wc -w) + if [ "$parents" -gt 2 ]; then + echo "type=minor" >> "$GITHUB_OUTPUT" + else + echo "type=patch" >> "$GITHUB_OUTPUT" + fi + fi + + - name: Bump version + id: version + run: | + new_version=$(npm version "${{ steps.bump.outputs.type }}" --no-git-tag-version) + echo "new_version=${new_version#v}" >> "$GITHUB_OUTPUT" + + - name: Commit version bump + run: | + git add package.json package-lock.json + git commit -m "chore(release): v${{ steps.version.outputs.new_version }} [skip ci]" + git push origin "${{ github.ref_name }}" + + - name: Merge main back into development + if: github.ref_name == 'main' + run: | + git fetch origin development + git checkout development + git merge --no-edit origin/main + git push origin development diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..13778ec --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,33 @@ +# CLAUDE.md + +## Overview +Remote, stateless Streamable HTTP MCP server exposing Google Gemini image generation and Veo 3.1 video generation, plus local video-overlay composition. Follows a submit+poll contract: `generate_image`/`generate_video` return a UUID immediately, `query_tasks` returns the final result. + +## Commands +- Install: `npm ci` +- Dev: `npm run dev` (tsx, no build step) +- Build: `npm run build` (tsc -> `dist/`) +- Start (built): `npm start` +- Unit tests: `npm test` (requires `PUBLIC_MEDIA_SIGNING_SECRET` >= 32 chars in the environment — see LESSONS.md) +- Paid integration tests (real Gemini/Veo calls, require `GEMINI_API_KEY`): `npm run test:integration`, `npm run test:integration:compose` +- No linter/formatter is configured; `npm run build` (`tsc --strict`) is the only static check. + +## Architecture +MCP tool handlers in `src/tools.ts` dispatch to `src/provider.ts` (Gemini/Veo API calls) and `src/compositor.ts` (ffmpeg/Pillow overlay composition via `scripts/make_overlay_card.py`). `src/jobs.ts` tracks in-memory job state for the submit+poll pattern; `src/media.ts` persists completed outputs to disk (`MEDIA_DIR`) with a manifest, and `src/public-media.ts` signs time-limited public download URLs (HMAC). `src/catalog.ts` and `src/arguments.ts` define/validate the model catalog and tool arguments. Entry point: `src/index.ts` (Express + MCP SDK). Details: `docs/`. + +## Conventions +- TypeScript, ESM (`"type": "module"`), strict mode, Node >= 20. +- Secrets (API keys, signing secret, HTTP Basic credentials) are never logged, never part of MCP schemas/responses. +- Prompts, reference-image bytes and overlay card text are never written to logs. + +## Workflow quirks +- `.env` / `deploy/gemini-veo-mcp.env` / `deploy/*.htpasswd` / `deploy/.*-password` are untracked (see `.gitignore`) and deploy-specific; `.env.example` and `deploy/gemini-veo-mcp.env.template` list variable names only. +- No `development` branch exists yet; branch from `main` until one is created. + +## Deployment +Deployed to an Alpine LXC container (OpenRC service `gemini-veo-mcp`, bound to `127.0.0.1:8087`, nginx reverse-proxying `/zenvairogoogle/`). See `README.md` for the update/restart commands and `docs/deployment.md` for full details. + +## Gotchas +- Veo 3.1 always generates audio; `with_audio=false` is rejected explicitly. +- `query_tasks` defaults to `include_base64=false`; base64 is only returned when the job's aggregate binary size is <= 25 MiB. +- A single media artifact over 300 MiB is rejected outright (`MAX_MEDIA_MB`). diff --git a/LESSONS.md b/LESSONS.md new file mode 100644 index 0000000..e425650 --- /dev/null +++ b/LESSONS.md @@ -0,0 +1,5 @@ +# Lessons + +Recurring mistakes and how to avoid them. + +- The unit test suite (`npm test`) requires `PUBLIC_MEDIA_SIGNING_SECRET` (>=32 chars) to be set in the environment; without it, the "compact payload" test fails with `PUBLIC_MEDIA_SIGNING_SECRET must contain at least 32 characters`. Export a dummy value before running tests locally or in CI. diff --git a/README.md b/README.md index 8b78a16..238993f 100644 --- a/README.md +++ b/README.md @@ -2,119 +2,20 @@ 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": "", "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": "", - "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: +## Quick start ```sh -pct exec 210 -- vi /opt/gemini-veo-mcp/gemini-veo-mcp.env -pct exec 210 -- rc-service gemini-veo-mcp restart +npm ci +cp .env.example .env # rellena GEMINI_API_KEY y los demás valores +npm run dev # o: npm run build && npm start ``` -Comprobaciones: +Tools disponibles: `who_am_i`, `generate_image`, `generate_video`, `compose_video_overlay`, `query_tasks`, `get_usage`. -```sh -pct exec 210 -- rc-service gemini-veo-mcp status -pct exec 210 -- tail -f /var/log/gemini-veo-mcp.log -``` +## Documentación -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. +- [`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. diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..38f97fc --- /dev/null +++ b/docs/api.md @@ -0,0 +1,63 @@ +# 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": "", "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": "", + "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. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..ec0568a --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,35 @@ +# 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. + +Referencia de los ficheros de despliegue en `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. + +## 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. diff --git a/docs/integration.md b/docs/integration.md new file mode 100644 index 0000000..a5176d2 --- /dev/null +++ b/docs/integration.md @@ -0,0 +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. + +Para vídeo, espera entre 11 segundos y 6 minutos según la documentación oficial. Evita polling agresivo; 10–15 segundos es razonable. diff --git a/docs/media-delivery.md b/docs/media-delivery.md new file mode 100644 index 0000000..b4d5b6c --- /dev/null +++ b/docs/media-delivery.md @@ -0,0 +1,13 @@ +# 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. From abf556349ff6eb5cf64fe945e3017a45c0617661 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 18:24:34 +0000 Subject: [PATCH 2/2] docs: translate documentation to English Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01LwH1wvgEjBPsXzWWiTYMyM --- README.md | 22 +++++++++---------- docs/api.md | 50 +++++++++++++++++++++--------------------- docs/deployment.md | 24 ++++++++++---------- docs/integration.md | 10 ++++----- docs/media-delivery.md | 14 ++++++------ 5 files changed, 60 insertions(+), 60 deletions(-) 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.