Open Data Spain MCP logo

Open Data Spain MCP

Community
AlbertoUAH

MCP that unifies access to the main Spanish open data sources (BOE, INE, AEMET, Datos.gob.es)

PublisherAlbertoUAH
Repositorydatos-gob-es-mcp
LanguagePython
Forks
5
Stars
20
Available tools
0
Transport typestdio
Categories
LicenseMIT
Links
  • Connect tools to AI workflows

    Open Data Spain MCP exposes MCP capabilities that can be used by compatible AI clients and agents.

  • 0 available tools

    Browse the callable actions below, including names and descriptions when provided by the server.

  • Ready-to-copy setup

    Use the installation snippets to configure this server in your preferred MCP client.

  • Open source signals

    20 stars and 5 forks from the linked repository.

datos-gob-es-mcp

Version Python 3.10+ License: MIT MCP Tests

Hub de OpenData Espanol - Servidor MCP (Model Context Protocol) que unifica el acceso a las principales fuentes de datos abiertos de Espana en una sola interfaz.

Descripcion

Este servidor MCP actua como un hub centralizado que conecta multiples APIs de datos publicos espanoles, permitiendo a asistentes de IA como Claude, ChatGPT y otros clientes MCP acceder a toda la informacion desde un unico punto.

Fuentes de datos integradas

FuenteDescripcionAuthDocumentacion
datos.gob.esCatalogo nacional de datos abiertos (+40.000 datasets)NoAPI
INEInstituto Nacional de EstadisticaNoAPI
AEMETAgencia Estatal de MeteorologiaAPI keyAPI
BOEBoletin Oficial del EstadoNoAPI

Caracteristicas

  • 11 herramientas MCP simplificadas para consultar multiples APIs de datos publicos
  • 5 recursos MCP (templates dinamicos) para acceso directo a datos
  • 6 prompts MCP para guias de busqueda detalladas
  • Busqueda semantica: Busqueda por significado usando embeddings (IA)
  • Cache de metadatos: Cache local de 24h para respuestas instantaneas
  • Paginacion paralela: Descarga 5x mas rapida con fetch_all=True
  • Descarga integrada: get(id, include_data=true) en una sola llamada
  • Busqueda AEMET por nombre: Usa nombres de municipio directamente (ej: "Madrid")
  • Retry automatico: Reintentos con backoff exponencial para mayor resiliencia
  • Sinonimos INE: Expansion de consultas para mejores resultados
  • Cliente HTTP asincrono con rate limiting por API
  • Modelos Pydantic para tipado seguro
  • Listo para desplegar en FastMCP Cloud

Instalacion

Requisitos

  • Python 3.10 o superior
  • pip

Instalacion rapida

bash
# Clonar el repositorio
git clone https://github.com/AlbertoUAH/datos-gob-es-mcp.git
cd datos-gob-es-mcp

# Crear entorno virtual e instalar
make dev

Instalacion manual

bash
# Crear entorno virtual
python3 -m venv .venv
source .venv/bin/activate

# Instalar dependencias
pip install -r requirements.txt

Configuracion

Variables de entorno

Crea un archivo .env basandote en .env.example:

bash
cp .env.example .env
VariableRequeridaDescripcion
AEMET_API_KEYPara meteorologiaAPI key de AEMET OpenData (obtener gratis)
PRELOAD_EMBEDDINGS_MODELNoPre-cargar modelo de embeddings en startup (default: true)
LOG_LEVELNoNivel de logging: DEBUG, INFO, WARNING, ERROR (default: INFO)
LOG_FORMATNoFormato de logs: console o json (default: console)
RATE_LIMIT_DATOS_GOB_ESNoPeticiones/segundo a datos.gob.es (default: 10)
RATE_LIMIT_INENoPeticiones/segundo a INE (default: 5)
RATE_LIMIT_AEMETNoPeticiones/segundo a AEMET (default: 10)
RATE_LIMIT_BOENoPeticiones/segundo a BOE (default: 10)

Uso

Ejecutar el servidor MCP

bash
# Modo stdio (para clientes MCP)
make run-stdio

# O directamente
mcp run server.py

Inspeccionar herramientas disponibles

bash
make inspect

Arquitectura

Capacidades MCP

CapacidadCantidadDescripcion
Tools11Funciones que el LLM puede invocar
Resources5Templates dinamicos para acceso directo
Prompts6Guias de busqueda predefinidas

Tools (Herramientas)

datos.gob.es (2 herramientas)

HerramientaDescripcion
searchBusqueda unificada de datasets: por filtros (titulo, tema, publicador, formato, fecha), semantica (IA con embeddings) o hibrida. Soporta multi-tema con logica OR y paginacion paralela
getObtiene metadatos de un dataset y opcionalmente descarga sus datos. Con include_data=true descarga y parsea CSV/JSON (hasta 50MB)

INE - Instituto Nacional de Estadistica (2 herramientas) - FUENTE PRINCIPAL DE ESTADISTICAS

El INE es la fuente oficial principal de estadisticas en Espana. Contiene datos de empleo (EPA), poblacion, precios (IPC), PIB, turismo, censos, y mas.

HerramientaDescripcion
ine_searchBusca operaciones estadisticas o lista tablas. Usa query para buscar operaciones, operation_id para listar tablas
ine_downloadObtiene datos estadisticos reales de una tabla del INE

AEMET - Meteorologia (3 herramientas)

HerramientaDescripcion
aemet_list_locationsLista municipios y/o estaciones meteorologicas. Usa location_type para filtrar
aemet_get_observationsObtiene observaciones meteorologicas actuales de una estacion
aemet_get_forecastObtiene la prediccion meteorologica para un municipio (acepta nombre o codigo)

BOE - Boletin Oficial del Estado (3 herramientas)

HerramientaDescripcion
boe_get_summaryObtiene el sumario del BOE. Si no se especifica fecha, devuelve el BOE mas reciente
boe_get_documentObtiene metadatos completos de un documento del BOE por su ID
boe_searchBusca documentos en el BOE por texto en un rango de fechas

Referencia de IDs

Los IDs de temas, publicadores y provincias estan incluidos en las instrucciones del servidor MCP.

Temas (usar con theme=)

economia, hacienda, educacion, salud, medio-ambiente, transporte, turismo, empleo, sector-publico, ciencia-tecnologia, cultura-ocio, urbanismo-infraestructuras, energia

Publicadores principales (usar con publisher=)

IDOrganizacion
EA0010587INE (Instituto Nacional de Estadistica)
E05024401Ministerio de Hacienda
E05024301Ministerio de Economia
E00003901AEMET
L01280796Ayuntamiento de Madrid
L01080193Ajuntament de Barcelona

Resources (Recursos)

Templates dinamicos para acceso directo a datos de datos.gob.es:

URI TemplateDescripcionEjemplo
dataset://{dataset_id}Informacion de un datasetdataset://l01280066-presupuestos
theme://{theme_id}Datasets de una tematicatheme://economia
publisher://{publisher_id}Datasets de un publicadorpublisher://E00003901
format://{format_id}Datasets en un formatoformat://csv
keyword://{keyword}Datasets con una palabra clavekeyword://presupuestos

Prompts (Guias de Busqueda)

Los prompts proporcionan guias estructuradas para tareas comunes de busqueda:

PromptDescripcion
buscar_datos_por_temaBusqueda guiada de datasets por tematica y formato
datasets_recientesEncontrar datasets actualizados en los ultimos dias
explorar_catalogoExploracion guiada del catalogo de datos abiertos
analisis_datasetAnalisis detallado de un dataset especifico
guia_herramientasDocumentacion de todas las herramientas MCP
buscar_estadisticasBusqueda de estadisticas oficiales consultando INE y datos.gob.es

Ejemplos de Uso

Buscar datasets por texto

Usuario: Busca datasets sobre empleo en Andalucia
Asistente: [Usa search(title="empleo Andalucia")]

Buscar por significado (semantica)

Usuario: Encuentra datos sobre desempleo juvenil
Asistente: [Usa search(query="desempleo juvenil")]

Buscar por multiples temas

Usuario: Busca datasets de economia o hacienda
Asistente: [Usa search(themes=["economia", "hacienda"])]

Obtener y descargar datos en una sola llamada

Usuario: Descarga los datos del dataset de presupuestos
Asistente: [Usa get(dataset_id="l01280066-presupuestos", include_data=true)]

Buscar estadisticas del INE

Usuario: Busca estadisticas sobre empleo
Asistente: [Usa ine_search(query="empleo")]
           -> Obtiene operacion EPA (id: 30308)
           [Usa ine_search(operation_id="30308")]
           -> Lista tablas disponibles
           [Usa ine_download(table_id="4247", n_last=12)]
           -> Obtiene datos reales

Obtener el BOE mas reciente

Usuario: Dame el BOE de hoy
Asistente: [Usa boe_get_summary()]

Usuario: Dame el BOE del 2 de enero de 2025
Asistente: [Usa boe_get_summary(date="20250102")]

Obtener prediccion meteorologica

Usuario: Que tiempo hara manana en Madrid?
Asistente: [Usa aemet_get_forecast(location="Madrid")]

Usuario: Que tiempo hara en Sevilla?
Asistente: [Usa aemet_get_forecast(location="Sevilla")]

Nota: aemet_get_forecast acepta tanto nombres de municipio como codigos (ej: "28079" para Madrid).

Configuracion en Clientes MCP

Claude Desktop

Anade a tu archivo de configuracion claude_desktop_config.json:

json
{
  "mcpServers": {
    "datos-gob-es": {
      "command": "mcp",
      "args": ["run", "/ruta/a/datos-gob-es-mcp/server.py"]
    }
  }
}

Desarrollo

Comandos disponibles

bash
make help          # Mostrar ayuda
make dev           # Instalar en modo desarrollo
make run           # Ejecutar servidor
make run-stdio     # Ejecutar en modo stdio
make inspect       # Inspeccionar herramientas MCP
make test          # Ejecutar tests
make lint          # Verificar codigo con ruff
make format        # Formatear codigo con ruff
make clean         # Limpiar archivos de cache
make notebooks     # Iniciar servidor Jupyter

# Benchmark de latencia
python scripts/latency_benchmark.py

Estructura del proyecto

datos-gob-es-mcp/
├── server.py                 # Servidor MCP principal
├── core/                     # Modulo central
│   ├── logging.py           # Logging estructurado (structlog)
│   ├── ratelimit.py         # Rate limiting (aiolimiter)
│   ├── config.py            # Configuracion centralizada
│   └── http.py              # Cliente HTTP centralizado
├── integrations/             # APIs externas
│   ├── ine.py               # Instituto Nacional de Estadistica
│   ├── aemet.py             # Agencia de Meteorologia
│   └── boe.py               # Boletin Oficial del Estado
├── prompts/                  # Guias de busqueda MCP
├── scripts/                  # Scripts de utilidad
│   └── latency_benchmark.py # Benchmark de latencia
├── examples/                 # Jupyter notebooks de ejemplo
├── tests/                    # Tests automatizados
├── docs/                     # Documentacion adicional
│   └── latency_report.md    # Informe de latencia
├── requirements.txt         # Dependencias Python
├── Makefile                 # Comandos de desarrollo
└── README.md

Rendimiento

Latencia por herramienta

ToolLatencia PromedioClasificacion
boe_get_summary54 ms🟢 Rapido
get (metadata)80 ms🟢 Rapido
search (titulo)127 ms🟢 Rapido
boe_search142 ms🟢 Rapido
search (tema)174 ms🟢 Rapido
ine_download197 ms🟢 Rapido
search (keyword)805 ms🟡 Moderado
ine_search1,368 ms🟡 Moderado
search (semantica)125 ms*🟢 Rapido

* Con PRELOAD_EMBEDDINGS_MODEL=true (habilitado por defecto). Ver informe completo.

Optimizaciones implementadas

MejoraDescripcionImpacto
Pre-carga de embeddingsModelo ML se carga en startupBusqueda semantica: 35s → 125ms
Cache de metadatosPublishers, themes, provincias y regiones se cachean 24hRespuestas instantaneas en llamadas repetidas
Cache de municipios AEMETLista de municipios cacheada 24hEvita rate limits en busquedas por nombre
Paginacion paralelafetch_all=True descarga 5 paginas en paralelo~5x mas rapido
Descarga integradaget(id, include_data=true) combina metadatos + datosUna sola llamada
HTTP/2Conexiones multiplexadasMenor latencia en llamadas concurrentes
Retry con backoffReintentos automaticos (max 3) con backoff exponencialMayor resiliencia ante errores transitorios
Sinonimos INEExpansion automatica de consultas con sinonimosMejores resultados de busqueda

Licencia

MIT License - ver LICENSE para mas detalles.

Contribuciones

Las contribuciones son bienvenidas. Por favor, abre un issue o pull request en el repositorio.

Enlaces

Use Open Data Spain MCP MCP with multiple AI models

TypingMind connects MCP tools at the workspace level, so once Open Data Spain MCP is connected, you can use it with different AI models in TypingMind instead of setting it up separately for each model. This MCP runs locally through the TypingMind MCP connector on your device.

Setup guide to use the local connector

Use this when the MCP server needs access to local files, apps, or private resources on your computer.

1

Open the MCP settings

In TypingMind, go to Settings, Advanced Settings, then Model Context Protocol and choose Setup Connector.

  1. Open TypingMind in your browser.
  2. Click the Settings icon.
  3. Go to Advanced Settings.
  4. Open the Model Context Protocol section.
  5. Click Setup Connector and choose This Device.
TypingMind MCP connector setup screen with This Device selected
2

Run the connector command

Choose This Device, copy the command from TypingMind, and run it in Terminal. Keep the process running while you use MCP.

  1. Copy the setup command shown by TypingMind.
  2. Open Terminal on macOS or Windows Terminal on Windows.
  3. Paste and run the command.
  4. Approve the package install if Terminal asks you to proceed.
  5. Keep the Terminal window running while using MCP tools.
3

Add Open Data Spain MCP as a server

When the connector status is Ready, click Edit Servers and paste the MCP server configuration.

  1. Wait until the connector status shows Ready.
  2. Click Edit Servers.
  3. Paste the Open Data Spain MCP MCP server configuration.
  4. Save the server list.
  5. Refresh if you want to confirm the connector is still ready.
TypingMind MCP settings showing active server and Edit Servers button
{
  "mcpServers": {
    "datos-gob-es-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Use it across models

Save the server list, open Plugins, enable the Open Data Spain MCP MCP tools, then select any supported AI model in TypingMind and use the tools in chat or assign them to an AI agent.

  1. Open the Plugins page in TypingMind.
  2. Enable the Open Data Spain MCP MCP tools.
  3. Start a chat and choose the AI model you want to use.
  4. Use the MCP tools in chat or assign them to an AI agent.
  5. Switch to another AI model whenever needed without reconnecting MCP.
TypingMind chat using enabled MCP tools with a selected AI model
Can you use Open Data Spain MCP to help me with this task?
Open Data Spain MCP
Sure. I read it.
Here is what I found using Open Data Spain MCP.

Frequently asked questions

What is the Open Data Spain MCP MCP server used for?

Open Data Spain MCP is an MCP server that lets compatible AI clients connect to external tools and context. In TypingMind, you can add this MCP server once and make its tools available in your AI workspace.

Can I use Open Data Spain MCP MCP with multiple AI models in TypingMind?

Yes. TypingMind connects MCP tools at the workspace level, so you can use Open Data Spain MCP with different AI models such as Claude, ChatGPT, Gemini, or other models you have configured in TypingMind without setting up the MCP server separately for each model.

Why use Open Data Spain MCP MCP with TypingMind?

TypingMind is one of the best frontends for LLM chat because it brings multiple AI models, prompts, plugins, AI agents, API keys, and MCP tools into one workspace. With Open Data Spain MCP connected, you can use its MCP tools across your preferred models while keeping your chat workflow organized in TypingMind.

How do I connect Open Data Spain MCP MCP to TypingMind?

Open Data Spain MCP runs through the TypingMind local MCP connector. This is best when the MCP server needs access to local files, desktop apps, command-line tools, or private resources on your computer.

What tools does Open Data Spain MCP MCP provide in TypingMind?

Open Data Spain MCP exposes MCP capabilities that can be enabled from the TypingMind Plugins page and used in chat or assigned to AI agents.

Do I need to share my API keys with TypingMind to use Open Data Spain MCP MCP?

No. TypingMind is local-first and lets you keep your model providers, API keys, prompts, and MCP configuration under your control. If Open Data Spain MCP requires authentication, add the required headers, OAuth settings, or local configuration for that MCP server when you create the connection.

Related MCP Servers

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇