nan-mcp-server
NaN MCP Server exposes NaN media/API tools to any MCP client for image, audio, embeddings, reranking, and account inspection workflows.
Generate images from text with
flux-2-kleinorqwen-image-2.1, with optional size, seed, count, guidance, and output naming.Edit 1–4 local reference images with
flux-2-kleinimage-to-image.Synthesize speech with
kokoroand list available voices by language.Transcribe local audio files with
whisper, optionally with verbose timings and language selection.Create 4096-dimension embeddings with
qwen3-embeddingfor RAG or semantic search.Rerank documents by relevance with Qwen3-Reranker-8B.
List models accessible with the configured NaN API key.
Check legacy per-model quota and real usage/credit consumption, read-only.
Save generated images/audio under
NAN_OUTPUT_DIRwithout overwriting; API tools requireNAN_API_KEY.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@nan-mcp-server Generate an image of a cozy cabin in the snowy mountains"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
NaN MCP Server
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 |
| Generar imagen desde texto |
|
| Editar imagen (imagen→imagen) |
|
| Sintetizar audio desde texto |
|
| Listar voces kokoro por idioma | — |
| Transcribir audio a texto |
|
| Embeddings vectoriales (4096 dims) |
|
| Reordenar documentos por relevancia (RAG) |
|
| Listar modelos disponibles con tu key | — |
| 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 | — |
| Consumo real y fondo de créditos ( | — |
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,seedentero de 0 a 2147483647 y singuidance. No admite imágenes de referencia; para eso usaedit_image, que siempre trabaja conflux-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.0Con 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 # bunO instálalo globalmente:
npm install -g nan-mcp-server@1.5.0 # o: pnpm add -g / bun add -g
nan-mcp-serverSobre 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@latesten 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.0O 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_varsno es opcional: codex no propaga su propio entorno a los servidores MCP, así que sin esa línea el servidor arranca sinNAN_API_KEYy cada llamada falla con «NAN_API_KEY environment variable is required».env_varsnombra las variables que debe heredar;envsolo 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-adapterCrea ~/.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 |
Tamaños de imagen |
|
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 |
| Sí, para llamar a la API | API key de NaN. Sin ella el servidor arranca y lista sus herramientas, pero solo |
| No | Base URL de la API (default |
| No | Directorio de salida (default |
| No | Timeout por petición en ms (default |
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.mdTesting
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 testPara probar el servidor manualmente contra la API real (requiere key):
NAN_API_KEY=sk-tu-key-aqui node server.jsY 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.jsPublicación / CI
El código no contiene secretos:
NAN_API_KEYse lee solo del entorno.El
.gitignoreexcluyenode_modules/, logs y.env..github/workflows/ci.ymlejecuta los tests en cada push y PR amainsobre Node 18, 20, 22 y 24, más un jobstrict-depscon pnpm: sunode_modulessin hoisting hace fallar cualquier import de un paquete no declarado enpackage.json(npm lo dejaría pasar silenciosamente)..github/workflows/publish.ymlpublica 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 conNAN_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_KEYdel entorno.
Licencia
MIT — ver LICENSE.
Available Tools
10 toolsedit_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
Scored across 10 tools
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.
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.
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.
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
Related MCP Connectors
MCP server for OpenAI API (chat completions, image generation, embeddings) via AceDataCloud
Focused MCP server for OpenAI image/audio generation (v2.0.0). Wraps endpoints via HAPI CLI.
MCP server exposing the YourImageShare upload API (upload/list/delete) as tools for AI agents.
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
Related MCP Servers
- AlicenseAqualityCmaintenanceMCP server for AI-powered image, audio, and video generation, enabling media creation directly from Claude, Cursor, and other MCP clients.1141 npmMIT
- AlicenseNot gradedqualityDmaintenanceModel Context Protocol server exposing MiniMax's image, speech, music, and video generation APIs as MCP tools for use with any MCP-aware host.MIT
- AlicenseAqualityDmaintenanceMulti-provider media generation MCP server that generates images, videos, audio, and transcriptions from text prompts using OpenAI, xAI, Gemini, ElevenLabs, and BFL through a single unified interface.6169 npm2MIT
- AlicenseAqualityAmaintenanceStateless MCP server that wraps OpenAI's Sora, Whisper, GPT-4o Audio, and TTS APIs for generating videos, images, and processing audio.933 PyPI6MIT