Skip to main content
Glama

NaN MCP Server

npm Descargas Node CI License MCP

Servidor MCP (Model Context Protocol) que expone las herramientas de media de la API de NaN (api.nan.builders) para cualquier cliente compatible con MCP.

Al ser un estándar abierto, funciona con opencode, Claude Code, Codex, Pi, Cursor, Windsurf, Zed, etc.

Herramientas

Herramienta

Descripción

Modelo

generate_image

Generar imagen desde texto

flux-2-klein (default) o qwen-image-2.1

edit_image

Editar imagen (imagen→imagen)

flux-2-klein

text_to_speech

Sintetizar audio desde texto

kokoro

list_voices

Listar voces kokoro por idioma

—

speech_to_text

Transcribir audio a texto

whisper

embed_text

Embeddings vectoriales (4096 dims)

qwen3-embedding

rerank_documents

Reordenar documentos por relevancia (RAG)

rerank

list_models

Listar modelos disponibles con tu key

—

get_quota

Cuota de tokens por modelo (backend del dashboard, solo lectura). Desde el fondo de créditos sus contadores pueden estar congelados; avisa cuando lo detecta

—

get_usage

Consumo real y fondo de créditos (GET /v1/usage, solo lectura): créditos usados/restantes, y peticiones, tokens y créditos por modelo

—

generate_image acepta el parámetro opcional model:

  • flux-2-klein (por defecto): texto→imagen, 256–1536 px.

  • qwen-image-2.1: texto→imagen con mejor renderizado de texto dentro de la imagen, 512–1280 px, seed entero de 0 a 2147483647 y sin guidance. No admite imágenes de referencia; para eso usa edit_image, que siempre trabaja con flux-2-klein.

Ambos modelos comparten la misma cuota mensual de imágenes.

Related MCP server: mmxomni

Requisitos

  • Node.js >= 18

  • Una API key de NaN (sk-...)

Instalación

El paquete se distribuye por npm. La forma más simple de usarlo en cualquier cliente MCP es sin instalarlo: npx lo ejecuta al vuelo.

export NAN_API_KEY="sk-tu-key-aqui"
npx -y nan-mcp-server@1.5.0

Con otro gestor de paquetes, si ya lo usas:

pnpm dlx nan-mcp-server@1.5.0    # pnpm
yarn dlx nan-mcp-server@1.5.0    # yarn
bunx nan-mcp-server@1.5.0        # bun

O instálalo globalmente:

npm install -g nan-mcp-server@1.5.0   # o: pnpm add -g / bun add -g
nan-mcp-server

Sobre la versión fijada: los ejemplos fijan una versión exacta en lugar de @latest, a propósito. Con @latest, cada arranque descarga la última versión publicada, así que cualquier versión futura —incluida una publicada por una cuenta comprometida— se ejecutaría en tu máquina automáticamente. Fijar la versión te deja decidir cuándo actualizar; consulta las releases y sube el número cuando quieras. Si prefieres actualizaciones automáticas, sustituye la versión por @latest en cualquiera de los ejemplos.

Configuración

El servidor se ejecuta vía stdio (proceso local). Solo necesita una variable de entorno: NAN_API_KEY. Sin ella arranca igualmente y publica su catálogo —para que cualquier inspector pueda leerlo—, pero toda herramienta que llame a la API falla indicando que falta.

Las imágenes y audios generados se guardan en ~/nan-mcp-output/ (configurable con NAN_OUTPUT_DIR).

Configuración por cliente

Añade a tu opencode.jsonc (o créalo en ~/.config/opencode/):

{
  "mcp": {
    "nan-media": {
      "type": "local",
      "command": ["npx", "-y", "nan-mcp-server@1.5.0"],
      "environment": {
        "NAN_API_KEY": "{env:NAN_API_KEY}"
      }
    }
  }
}

Instalar vía CLI:

claude mcp add nan-media --scope user -e NAN_API_KEY='${NAN_API_KEY}' -- \
  npx -y nan-mcp-server@1.5.0

O en .mcp.json:

{
  "mcpServers": {
    "nan-media": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "nan-mcp-server@1.5.0"],
      "env": {
        "NAN_API_KEY": "${NAN_API_KEY}"
      }
    }
  }
}

En ~/.codex/config.toml:

[mcp_servers.nan-media]
command = "npx"
args = ["-y", "nan-mcp-server@1.5.0"]
env_vars = ["NAN_API_KEY"]

env_vars no es opcional: codex no propaga su propio entorno a los servidores MCP, así que sin esa línea el servidor arranca sin NAN_API_KEY y cada llamada falla con «NAN_API_KEY environment variable is required». env_vars nombra las variables que debe heredar; env solo admite valores literales, que no conviene escribir en un archivo versionado.

Pi usa pi-mcp-adapter y lee los archivos MCP estándar. Instala el adaptador:

pi install npm:pi-mcp-adapter

Crea ~/.config/mcp/mcp.json (config compartido MCP estándar):

{
  "mcpServers": {
    "nan-media": {
      "command": "npx",
      "args": ["-y", "nan-mcp-server@1.5.0"],
      "env": {
        "NAN_API_KEY": "$env:NAN_API_KEY"
      }
    }
  }
}

La key se interpola con $env:NAN_API_KEY, así que ningún secreto queda en el archivo.

Para usar los modelos de NaN en Pi, define el proveedor en ~/.pi/agent/models.json:

{
  "providers": {
    "nan": {
      "baseUrl": "https://api.nan.builders/v1",
      "api": "openai-completions",
      "apiKey": "$NAN_API_KEY",
      "models": [
        { "id": "deepseek-v4-flash", "name": "DeepSeek V4 Flash", "reasoning": true, "input": ["text", "image"], "contextWindow": 1048576 },
        { "id": "qwen3.6", "name": "Qwen 3.6", "reasoning": true, "input": ["text", "image"], "contextWindow": 262144 }
      ]
    }
  }
}

Luego usa --provider nan --model <id> (p.ej. pi --provider nan --model deepseek-v4-flash).

En la configuración de MCP del cliente, añade un servidor stdio:

Comando: npx -y nan-mcp-server@1.5.0
Variables: NAN_API_KEY=tu-clave-de-nan-builders (no la incluyas en el config versionado)

Uso

Una vez conectado, pide al agente:

  • "Genera una imagen de un faro al atardecer con nan-media"

  • "Genera un cartel con la frase «Abierto» usando qwen-image-2.1"

  • "Sintetiza en español: Hola mundo, voz ef_dora"

  • "Transcribe el audio /ruta/audio.mp3"

  • "Reordena estos documentos según la query X"

Límites de la API

Recurso

Límite

Generación/edición de imágenes

100 req/mes por usuario (pool compartido entre flux-2-klein y qwen-image-2.1), 20 req/min

Tamaños de imagen

flux-2-klein: 256–1536 px; qwen-image-2.1: 512–1280 px; ambos múltiplos de 16 y ratio entre 1:3 y 3:1

Tamaño máximo archivo (STT / edit_image)

25 MB por archivo

Audios para transcripción

máx. ~2 min por archivo (timeout 524 si supera)

Imágenes de referencia (edit_image)

hasta 4

Variables de entorno

Variable

Obligatoria

Descripción

NAN_API_KEY

Sí, para llamar a la API

API key de NaN. Sin ella el servidor arranca y lista sus herramientas, pero solo list_voices responde

NAN_BASE_URL

No

Base URL de la API (default https://api.nan.builders/v1)

NAN_OUTPUT_DIR

No

Directorio de salida (default ~/nan-mcp-output)

NAN_TIMEOUT_MS

No

Timeout por petición en ms (default 180000, 3 min)

Desarrollo

Estructura

nan-mcp-server/
├── server.js            # Servidor MCP + herramientas
├── test/server.test.js  # Tests (node:test, sin dependencias extra)
├── .github/workflows/   # ci.yml (tests) + publish.yml (npm)
├── package.json
└── README.md

Testing

Los tests usan el test runner nativo de Node (node:test), sin dependencias adicionales. No hacen llamadas a la API (usan un valor de prueba para NAN_API_KEY), así que se ejecutan sin red ni credenciales.

npm test

Para probar el servidor manualmente contra la API real (requiere key):

NAN_API_KEY=sk-tu-key-aqui node server.js

Y luego una llamada de ejemplo vía stdio:

printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}\n{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}\n' \
  | node server.js

Publicación / CI

  • El código no contiene secretos: NAN_API_KEY se lee solo del entorno.

  • El .gitignore excluye node_modules/, logs y .env.

  • .github/workflows/ci.yml ejecuta los tests en cada push y PR a main sobre Node 18, 20, 22 y 24, más un job strict-deps con pnpm: su node_modules sin hoisting hace fallar cualquier import de un paquete no declarado en package.json (npm lo dejaría pasar silenciosamente).

  • .github/workflows/publish.yml publica en npm al crear un release en GitHub, vía trusted publishing (OIDC), sin token en secrets.

Notas

  • Las imágenes y audios se guardan en ~/nan-mcp-output/ (configurable con NAN_OUTPUT_DIR). Los nombres se sanitizan (sin path traversal) y nunca se sobrescriben archivos existentes: si el nombre ya está ocupado se añade -2, -3, etc.

  • Los archivos de entrada (STT / edit_image) se cargan en memoria; para archivos muy grandes conviene dividirlos.

  • El servidor no contiene ningún secreto en el código: solo lee NAN_API_KEY del entorno.

Licencia

MIT — ver LICENSE.

Available Tools

10 tools
edit_imageEdit ImageA

Transform existing images with flux-2-klein image-to-image (NaN API). Use generate_image instead when starting from text alone. Takes 1 to 4 local reference files (PNG, JPEG or WebP, each under 25MB), saves the result under NAN_OUTPUT_DIR (default ~/nan-mcp-output) without overwriting anything, and returns the saved path and the temporary source URL. Counts against the shared account image quota (100/month, flux-2-klein and qwen-image-2.1).

Inputs: images (required), prompt (required), n, seed, +3 more.

embed_textEmbed TextA

Turn text into 4096-dimension vectors with qwen3-embedding (NaN API) for RAG or semantic search; rerank_documents then orders whatever a search over those vectors brings back. Returns only a summary — item count, dimensions and input tokens — because the vectors are far too large to put in the conversation, so use this to populate a store rather than to read values.

Inputs: input (required), encoding_format.

generate_imageGenerate ImageA

Generate an image from a text prompt with flux-2-klein (default) or qwen-image-2.1 (NaN API). qwen-image-2.1 is text-to-image only and renders text inside the image more cleanly; use edit_image when you already have reference images to transform. Saves each image under NAN_OUTPUT_DIR (default ~/nan-mcp-output) and never overwrites: a taken name gets -2, -3, and so on. Returns the saved path and the temporary source URL. Counts against the account image quota (100/month, shared by both image models).

Inputs: prompt (required), n, seed, size, +3 more.

get_quotaGet QuotaA

Report the legacy per-model token quota from the NaN dashboard backend (GET /api/usage/quota): used, cap, remaining and reset date, worst-utilised model first. Since NaN moved to a credit pool these counters can be frozen, and a line is flagged when its counter lags behind real activity; use get_usage for real consumption and the credit balance. Read-only and free. Undocumented route that accepts the same sk- key; it may change without notice.

Inputs: no named parameters.

get_usageGet UsageA

Report real consumption and the credit pool from NaN (GET /v1/usage): credits used, remaining and reset date, then per-model requests, input/output/cached tokens and credits, with totals. Defaults to the current credit period. Prefer this over get_quota, whose counters can be stale. Read-only and free. Undocumented endpoint that accepts the same sk- key; it may change without notice.

Inputs: end_date, start_date.

list_modelsList ModelsA

List the NaN API model ids the configured key can reach, one per line with its owner. Useful to confirm access or spot a retired model before calling another tool.

Inputs: no named parameters.

list_voicesList VoicesA

List the kokoro voice ids that text_to_speech accepts, grouped by language. Answered from the catalog bundled with the server, so it costs no API call and takes no arguments.

Inputs: no named parameters.

rerank_documentsRerank DocumentsA

Order documents by how well they answer a query, with Qwen3-Reranker-8B (NaN API). This is the second half of a RAG pipeline: embed_text builds the vectors a search runs over, and this one ranks what that search returns. Returns one line per document with its relevance score and its position in the input list, in the order the reranker gives them back.

Inputs: query (required), documents (required), top_n.

speech_to_textSpeech To TextA

Transcribe a local audio file with whisper (NaN API STT); text_to_speech does the opposite. The file must exist on this machine and stay under 25MB and about 2 minutes, or the request times out. Returns the plain transcript, or the full JSON with per-segment timings when verbose is set. Writes nothing to disk.

Inputs: file (required), verbose, language.

text_to_speechText To SpeechA

Synthesize speech from text with kokoro (NaN API TTS); speech_to_text does the opposite. Call list_voices first to pick a voice id. Writes the audio under NAN_OUTPUT_DIR (default ~/nan-mcp-output) without overwriting anything, and returns the saved path and its size in bytes.

Inputs: text (required), speed, voice, format, +1 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 10 tools

    Disambiguation5/5

    Every tool has a distinct purpose, and potentially overlapping pairs are explicitly differentiated in their descriptions: get_quota vs get_usage (legacy vs real consumption), generate_image vs edit_image (text-to-image vs image-to-image), and embed_text vs rerank_documents (the two halves of a RAG pipeline). speech_to_text and text_to_speech are clearly opposite directions, and list_models vs list_voices target different catalogs.

    Naming Consistency5/5

    All ten tools use snake_case with a predictable verb_noun or noun_relation pattern (get_quota, generate_image, list_models, speech_to_text). No mixing of camelCase, casing, or verb styles.

    Tool Count5/5

    Ten tools is well within the ideal 3-15 range and each maps to a distinct capability of a multi-modal API (image gen/edit, embeddings, reranking, TTS, STT, model/voice listing, usage/quota). Nothing feels padded or missing at the count level.

    Completeness4/5

    The surface covers image generation/editing, embeddings, reranking, speech in both directions, catalog listing, and usage reporting, which is broad lifecycle coverage for a multi-modal API. A text-generation/chat completion tool and any way to inspect or manage saved output files are notable gaps, but agents can work around them for the stated modalities.

    Maintenance

    ActivityActive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers