REE MCP Server
The REE MCP Server enables natural language conversations with Claude to access and analyze Spain's electrical grid data from Red Eléctrica de España (REE), covering real-time operations, historical analysis, and market intelligence.
Core Data Access
Search and retrieve data from 1,967+ electricity indicators using keywords
Get time-series data with customizable granularity (5-minute raw, 15-minute, hourly, or daily)
Browse available indicators with pagination support
Real-Time Grid Monitoring
Query current electricity demand with forecasts and min/max values
View generation mix breakdown by source (nuclear, wind, solar, hydro, coal, gas, etc.)
Track international exchanges (imports/exports) with France, Portugal, Morocco, and Andorra
Monitor renewable energy generation (wind, solar, hydro) and their percentage of total mix
Assess grid stability by comparing synchronous vs variable renewable generation
Environmental Analysis
Calculate and track carbon intensity (gCO₂/kWh) to assess grid cleanliness
Identify periods with lowest emissions
Monitor renewable energy trends and contribution
Market & Pricing
Analyze SPOT market electricity prices with statistics and multi-country comparisons
Identify cheapest consumption hours for optimal timing
Study price correlations with generation mix and demand patterns
Energy Storage
Monitor pumped storage operations (pumping vs turbining)
Calculate storage efficiency and identify arbitrage opportunities
Forecasting & Accuracy
Compare forecasted vs actual demand with accuracy metrics (MAE, RMSE, error rates)
Evaluate prediction performance across time periods
Historical Analysis & Event Investigation
Investigate grid events, anomalies, and critical incidents like blackouts
Analyze peak demand patterns with load factors
Track generation mix evolution over time
Compare periods (year-over-year, weekday vs weekend)
Detect unusual activity in the electrical grid
Conversational Intelligence
Ask questions in natural language without knowing technical API details or indicator IDs
Receive contextual analysis with meaningful insights
Combine multiple metrics for comprehensive analysis
Source code hosted on GitHub with CI/CD workflows and issue tracking for community contributions
Built using Python 3.11+ with async/await support, type checking with mypy, and code formatting with ruff
Educational content and tutorials available on the JavadexAI YouTube channel for learning AI implementation
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., "@REE MCP Server show me Spain's current electricity demand and generation mix"
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.
⚡ REE MCP Server
Habla con la red eléctrica española a través de Claude - sin conocimientos técnicos
Pregunta a Claude sobre demanda, generación, precios y emisiones de electricidad en España usando lenguaje natural. Él se encarga de todos los detalles técnicos.
Construido con Domain-Driven Design y Clean Architecture por Javi Santos - Especialista en IA y Robótica con investigación publicada en visión por computador e interpretabilidad de LLMs.
💡 ¿Quieres aprender a construir proyectos así? Únete a La Escuela de IA - la comunidad donde aprenderás IA práctica, sin humo, con ejemplos reales en español.
🎯 ¿Qué Hace Este Servidor?
Red Eléctrica de España (REE) gestiona la red eléctrica española 24/7, publicando datos cada 5 minutos. Este servidor MCP hace esos datos accesibles mediante conversación natural con Claude.
El Poder de Conversaciones con Datos Reales
Por Javi Santos
En lugar de escribir scripts de Python, imagina conversaciones como esta:
Tú: "Comprueba qué pasó el 28 de abril de 2025"
Claude: Analiza datos de la red...
🚨 EVENTO CRÍTICO DETECTADO - 28 de Abril de 2025 a las 12:35h
Colapso Masivo de la Red:
11.000 MW perdidos en 5 minutos (caída del 43% de capacidad)
El sistema cayó de 25.184 MW → 14.185 MW instantáneamente
Compatible con escenario de apagón en cascada
La recuperación tardó más de 10 horas
Análisis:
11:00-12:30: Sistema estable, sin avisos previos
12:30-12:35: Fallo catastrófico instantáneo
12:35-13:35: Degradación continua hasta mínimo de 9.635 MW
Causa probable: Disparo de planta nuclear → colapso de frecuencia → cascada
Este sería uno de los peores apagones de España en la historia moderna.
Ese es el poder de este servidor. Investiga eventos en la red, analiza tendencias renovables vs fósiles, correlaciona precios con demanda, o sigue la descarbonización de España - todo mediante conversación natural.
Sin documentación de API. Sin scripts. Solo pregunta.
Related MCP server: fronius-mcp
🚀 Instalación (3 minutos)
1️⃣ Clonar e Instalar
# Clonar el repositorio
git clone https://github.com/ESJavadex/ree-mcp.git
cd ree-mcp
# Instalar uv (gestor rápido de paquetes Python)
curl -LsSf https://astral.sh/uv/install.sh | sh
# O en macOS: brew install uv
# Crear entorno virtual e instalar
uv venv
source .venv/bin/activate # En Windows: .venv\Scripts\activate
uv pip install -e ".[dev]"2️⃣ Configurar Token de API
# Copiar el archivo de ejemplo (incluye token demo)
cp .env.example .env
# Editar .env si necesitas tu propio token
# REE_API_TOKEN=tu_token_aquiObtener Token:
Pruebas/Demo: Ya incluido en
.env.exampleProducción: Email a consultasios@ree.es
3️⃣ Añadir a Claude Code
# Ejecutar el script de instalación
./INSTALL_COMMAND.sh
# Verificar
claude mcp listDeberías ver ree-mcp: ✓ Connected.
4️⃣ ¡Listo! Empieza a Preguntar
Abre Claude Code y prueba:
"Muéstrame la demanda eléctrica actual de España"
"¿Cuál es el mix de generación ahora?"
"Compara generación solar vs eólica hoy"
💬 ¿Qué Puedes Preguntar?
📊 Operaciones en Tiempo Real
"¿Cuál es la demanda eléctrica de España ahora mismo?"
"Muéstrame el mix de generación al mediodía"
"¿Cuánta energía exportó España ayer?"
"Compara la demanda de hoy con la semana pasada"
"¿Qué está generando cada central ahora? (nuclear, eólica, solar...)"
🔍 Investigación y Análisis de Eventos
"Investiga qué pasó el 28 de abril de 2025"
"¿Hubo actividad inusual en la red el mes pasado?"
"Encuentra el día de pico de demanda este año y explica por qué"
"Analiza la correlación entre generación eólica y precios"
"Detecta patrones anómalos en la última semana"
"¿Cuándo fue la última vez que hubo un apagón o evento crítico?"
🌱 Energías Renovables y Emisiones
"¿Cuánta energía solar está generando España?"
"Compara generación renovable vs fósil esta semana"
"¿Cuáles son las emisiones de CO₂ actuales? (gCO₂/kWh)"
"Muéstrame la tendencia de energía eólica en los últimos 30 días"
"¿Qué porcentaje de la demanda viene de renovables?"
"¿Cuándo fue el día más limpio (menos CO₂) este mes?"
💰 Análisis de Precios y Mercado
"¿Cuál es el precio SPOT de electricidad ahora?"
"Encuentra las horas más baratas para consumir electricidad hoy"
"Compara tarifas PVPC entre días laborables y fines de semana"
"¿Cuándo fue la electricidad más cara este mes? ¿Por qué?"
"Muéstrame la correlación entre precios y generación renovable"
⚙️ Estabilidad de Red y Almacenamiento
"¿Cómo está la estabilidad de la red ahora? (inercia síncrona vs renovable variable)"
"¿Se están usando las centrales de bombeo para almacenar energía?"
"Muéstrame los flujos de importación/exportación con Francia y Portugal"
"¿Cuándo bombea agua la red y cuándo la turbina?"
🔎 Descubrimiento de Datos
"Busca todos los indicadores relacionados con 'nuclear'"
"¿Qué datos hay disponibles sobre generación hidroeléctrica?"
"Muéstrame todos los indicadores de precios"
"Lista los indicadores disponibles de emisiones y sostenibilidad"
📈 Comparativas y Tendencias
"Compara la demanda de este mes vs el mismo mes del año pasado"
"¿Cómo ha evolucionado la generación solar en los últimos 6 meses?"
"Muéstrame el balance neto de exportación/importación del último mes"
"¿Cuándo alcanzamos el pico histórico de generación renovable?"
Claude usa automáticamente las herramientas correctas, obtiene los datos y los presenta en contexto con análisis detallado.
🎓 Aprende a Construir Proyectos como Este
Este proyecto fue creado por Javi Santos, Especialista en IA y Robótica con investigación publicada en:
🔬 Detección de gasas quirúrgicas usando Redes Neuronales Convolucionales
🧠 Interpretabilidad de Modelos de Lenguaje en escenarios de conocimiento diverso
📚 La Escuela de IA
¿Quieres aprender IA sin humo y construir proyectos como este?
Únete a La Escuela de IA - la comunidad española de aprendizaje de IA donde encontrarás:
🎯 Práctica real - Construye proyectos reales de IA, no ejemplos de juguete
🇪🇸 Contenido en español - Por fin, educación en IA en tu idioma
🛠️ Recursos prácticos - Código, tutoriales y ejemplos hands-on
👥 Comunidad activa - Aprende con otros entusiastas de la IA hispanohablantes
📺 Canal de YouTube
Suscríbete a JavadexAI para:
🎥 Tutoriales de IA y recorridos de proyectos
💡 Aplicaciones de LLMs y servidores MCP
🚀 Estrategias de implementación de IA en el mundo real
🤝 Conecta
LinkedIn: Javi Santos
YouTube: @JavadexAI
Escuela de IA: skool.com/la-escuela-de-ia-9955
🔥 Características Técnicas
✅ Listo para Producción
Reintentos automáticos con backoff exponencial
Manejo exhaustivo de errores y validación
Async/await para rendimiento óptimo
96 tests exhaustivos con 90% cobertura
🏗️ Arquitectura Robusta
Domain-Driven Design - Lógica de negocio pura
Clean Architecture - Separación clara de responsabilidades
Principios SOLID - Código mantenible y extensible
Type Safety - 100% tipado con mypy modo estricto
📊 Datos Completos
Acceso a 1.967+ indicadores de REE
Datos cada 5 minutos en tiempo real
Histórico completo disponible
14 herramientas MCP especializadas
🤝 Contribuir
¡Las contribuciones son bienvenidas! Ver CLAUDE.md para guía detallada de desarrolladores.
Este código sigue principios arquitectónicos estrictos:
Domain-Driven Design
Clean Architecture
Principios SOLID
Testing exhaustivo
💬 Soporte y Recursos
Problemas y Preguntas
Problemas del Servidor: Abrir un issue
Preguntas sobre API REE: consultasios@ree.es
Aprende Más
📚 La Escuela de IA - Aprende IA en español
Recursos
API eSios de REE: https://api.esios.ree.es/
FastMCP: https://github.com/jlowin/fastmcp
Model Context Protocol: https://modelcontextprotocol.io/
📄 Licencia
MIT License con Descargo de Responsabilidad - Ver archivo LICENSE para detalles completos.
⚠️ Proyecto Educativo: Este software se proporciona "tal cual" sin garantías. Úsalo bajo tu propio riesgo.
Construido con ❤️ usando Domain-Driven Design y mejores prácticas modernas de Python
⭐ ¡Dale una estrella al repo si te resulta útil!
Available Tools
18 toolsanalyze_demand_volatilityA
Analyze demand volatility patterns over a period.
Calculates daily demand swings, load factors, and volatility levels to identify high-variability days and overall stability patterns.
Args: start_date: Start date in YYYY-MM-DD format end_date: End date in YYYY-MM-DD format
Returns: JSON string with volatility analysis and stability assessment.
Examples: Analyze volatility for a week: >>> await analyze_demand_volatility("2025-10-01", "2025-10-07")
Analyze volatility for a month:
>>> await analyze_demand_volatility("2025-10-01", "2025-10-31")Inputs: start_date (required), end_date (required). Returns: result
compare_forecast_actualA
Compare forecasted vs actual electricity demand.
Calculates forecast accuracy metrics (error, MAE, RMSE) for demand predictions.
Args: date: Date in YYYY-MM-DD format
Returns: JSON string with forecast comparison and accuracy metrics.
Examples: Compare forecast accuracy for Oct 8: >>> await compare_forecast_actual("2025-10-08")
Inputs: date (required). Returns: result
get_carbon_intensityA
Get carbon intensity over time (gCO2/kWh).
Calculates CO2 emissions per unit of electricity generated. Lower values indicate cleaner energy mix.
Args: start_date: Start datetime in ISO format (YYYY-MM-DDTHH:MM) end_date: End datetime in ISO format (YYYY-MM-DDTHH:MM) time_granularity: Time aggregation (raw, hour, day, fifteen_minutes)
Returns: JSON string with carbon intensity time series and statistics.
Examples: Get hourly carbon intensity for a day: >>> await get_carbon_intensity("2025-10-08T00:00", "2025-10-08T23:59", "hour")
Get daily carbon intensity for a week:
>>> await get_carbon_intensity("2025-10-01T00:00", "2025-10-07T23:59", "day")Inputs: start_date (required), end_date (required), time_granularity. Returns: result
get_daily_demand_statisticsA
Get daily demand statistics for a period.
Provides comprehensive daily demand analysis including maximum, minimum, and sum of generation values for each day in the specified period.
Args: start_date: Start date in YYYY-MM-DD format end_date: End date in YYYY-MM-DD format
Returns: JSON string with daily statistics and overall summary.
Examples: Get statistics for a week: >>> await get_daily_demand_statistics("2025-10-01", "2025-10-07")
Get statistics for a month:
>>> await get_daily_demand_statistics("2025-10-01", "2025-10-31")Inputs: start_date (required), end_date (required). Returns: result
get_demand_summaryA
Get a summary of electricity demand for a specific date.
Convenience tool that fetches key demand indicators (real demand, forecast, max/min) for a given date.
Args: date: Date in YYYY-MM-DD format (default: 2025-10-08)
Returns: JSON string with demand summary.
Examples: Get today's demand summary: >>> await get_demand_summary("2025-10-11")
Inputs: date. Returns: result
get_generation_mixA
Get the electricity generation mix at a specific time.
Returns the power generation breakdown by source (nuclear, wind, solar, etc.) for a specific hour.
Args: date: Date in YYYY-MM-DD format hour: Hour in HH format (00-23, default: 12)
Returns: JSON string with generation mix by source.
Examples: Get generation mix at noon on Oct 8: >>> await get_generation_mix("2025-10-08", "12")
Get overnight generation mix:
>>> await get_generation_mix("2025-10-08", "02")Inputs: date (required), hour. Returns: result
get_generation_mix_timelineA
Get generation mix over time for a full day or period.
Returns generation breakdown by source across multiple time points, useful for visualizing energy transition patterns.
Args: date: Date in YYYY-MM-DD format time_granularity: Time aggregation (hour or day, default: hour)
Returns: JSON string with generation mix timeline.
Examples: Get hourly generation mix for a day: >>> await get_generation_mix_timeline("2025-10-08", "hour")
Get daily generation mix for a month:
>>> await get_generation_mix_timeline("2025-10-01", "day")Inputs: date (required), time_granularity. Returns: result
get_grid_stabilityA
Get grid stability metrics at a specific time.
Analyzes synchronous generation (provides inertia) vs variable renewables (no inertia) to assess grid stability risk.
Args: date: Date in YYYY-MM-DD format hour: Hour in HH format (00-23, default: 12)
Returns: JSON string with grid stability analysis.
Examples: Get grid stability at noon: >>> await get_grid_stability("2025-10-08", "12")
Check overnight stability:
>>> await get_grid_stability("2025-10-08", "02")Inputs: date (required), hour. Returns: result
get_indicator_dataA
Get time-series data for a specific electricity indicator.
Retrieves historical data for any REE indicator (demand, generation, prices, etc.) for a specified date range. Returns the data with statistical summary.
Args: indicator_id: The indicator ID (e.g., 1293 for real demand, 549 for nuclear) start_date: Start datetime in ISO format (YYYY-MM-DDTHH:MM) end_date: End datetime in ISO format (YYYY-MM-DDTHH:MM) time_granularity: Time aggregation level (raw, hour, day, fifteen_minutes)
Returns: JSON string with indicator metadata, time-series values, and statistics.
Examples: Get hourly real demand for Oct 8, 2025: >>> await get_indicator_data(1293, "2025-10-08T00:00", "2025-10-08T23:59", "hour")
Get 5-minute wind generation data:
>>> await get_indicator_data(2038, "2025-10-08T00:00", "2025-10-08T03:00", "raw")Inputs: indicator_id (required), start_date (required), end_date (required), time_granularity. Returns: result
get_international_exchangesA
Get international electricity exchanges at a specific time.
Returns import/export data by country (Andorra, Morocco, Portugal, France) with net balance calculations.
Args: date: Date in YYYY-MM-DD format hour: Hour in HH format (00-23, default: 12)
Returns: JSON string with imports, exports, and net balance by country.
Examples: Get exchanges at noon on Oct 8: >>> await get_international_exchanges("2025-10-08", "12")
Get overnight exchanges:
>>> await get_international_exchanges("2025-10-08", "02")Inputs: date (required), hour. Returns: result
get_peak_analysisB
Get peak demand analysis over a period.
Analyzes daily maximum and minimum demand to identify patterns and calculate load factors.
Args: start_date: Start date in YYYY-MM-DD format end_date: End date in YYYY-MM-DD format
Returns: JSON string with peak demand analysis.
Examples: Get peak analysis for a week: >>> await get_peak_analysis("2025-10-01", "2025-10-07")
Get peak analysis for a month:
>>> await get_peak_analysis("2025-10-01", "2025-10-31")Inputs: start_date (required), end_date (required). Returns: result
get_price_analysisA
Get electricity price analysis over time.
Analyzes SPOT market prices with statistics and multi-country comparison. Note: SPOT price indicator returns data for multiple European countries. Use geo_filter to focus on a specific market.
Args: start_date: Start datetime in ISO format (YYYY-MM-DDTHH:MM) end_date: End datetime in ISO format (YYYY-MM-DDTHH:MM) geo_filter: Optional geographic filter (e.g., "Península", "Portugal", "France") If not specified, returns all countries
Returns: JSON string with price data and analysis.
Examples: Get Spanish hourly prices for a day: >>> await get_price_analysis("2025-10-08T00:00", "2025-10-08T23:59", "Península")
Get all countries' prices for comparison:
>>> await get_price_analysis("2025-10-08T00:00", "2025-10-08T23:59")Inputs: start_date (required), end_date (required), geo_filter. Returns: result
get_pvpc_rateA
Get the PVPC regulated electricity rate at a specific time.
Returns the PVPC (Precio Voluntario para el Pequeño Consumidor) rate, which is the regulated retail electricity price for consumers in Spain.
Args: date: Date in YYYY-MM-DD format hour: Hour in HH format (00-23, default: 12)
Returns: JSON string with PVPC rate data.
Examples: Get PVPC rate at noon on Oct 8: >>> await get_pvpc_rate("2025-10-08", "12")
Get PVPC rate at midnight:
>>> await get_pvpc_rate("2025-10-08", "00")Inputs: date (required), hour. Returns: result
get_renewable_summaryA
Get renewable energy generation summary at a specific time.
Aggregates wind, solar PV, solar thermal, and hydro generation with renewable percentage calculations.
Args: date: Date in YYYY-MM-DD format hour: Hour in HH format (00-23, default: 12)
Returns: JSON string with renewable generation breakdown and percentages.
Examples: Get renewable summary at noon: >>> await get_renewable_summary("2025-10-08", "12")
Get overnight renewable summary:
>>> await get_renewable_summary("2025-10-08", "02")Inputs: date (required), hour. Returns: result
get_spain_hourly_pricesA
Get Spanish hourly electricity prices (SPOT market) for a specific day.
Returns the 24 hourly prices for the Spanish Peninsular market (OMIE/MIBEL). This is the simplified version focused only on Spain, perfect for checking daily electricity costs.
Args: date: Date in YYYY-MM-DD format
Returns: JSON string with hourly prices, min/max/average, and the cheapest/most expensive hours.
Examples: Get today's hourly prices: >>> await get_spain_hourly_prices("2025-10-19")
Inputs: date (required). Returns: result
get_storage_operationsA
Get pumped storage operations for a day.
Shows pumping consumption (storing energy) and turbining (releasing energy) to identify arbitrage opportunities and storage efficiency.
Args: date: Date in YYYY-MM-DD format
Returns: JSON string with storage operations and efficiency metrics.
Examples: Get storage operations for Oct 8: >>> await get_storage_operations("2025-10-08")
Inputs: date (required). Returns: result
list_indicatorsA
List all available electricity indicators from REE.
Returns metadata for all 1,967+ available indicators including their IDs, names, units, frequencies, and geographic scopes.
Args: limit: Maximum number of indicators to return (default: all) offset: Number of indicators to skip for pagination (default: 0)
Returns: JSON string with list of indicator metadata.
Examples: Get first 50 indicators: >>> await list_indicators(limit=50, offset=0)
Get all indicators:
>>> await list_indicators()Inputs: limit, offset. Returns: result
search_indicatorsA
Search for indicators by keyword in their names.
Searches through all available indicators and returns those matching the keyword in their name or short name.
Args: keyword: Keyword to search for (e.g., "demanda", "precio", "solar") limit: Maximum number of results (default: 20)
Returns: JSON string with matching indicator metadata.
Examples: Find all demand-related indicators: >>> await search_indicators("demanda", limit=10)
Find price indicators:
>>> await search_indicators("precio")
Find solar generation indicators:
>>> await search_indicators("solar")Inputs: keyword (required), limit. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Most tools have clearly distinct purposes (demand, generation, prices, etc.), but get_indicator_data is a generic tool that can retrieve many of the same data types as dedicated tools, potentially causing confusion about which to use.
All tool names follow a consistent verb_noun snake_case pattern (e.g., get_carbon_intensity, list_indicators), making the set predictable and easy to navigate.
With 18 tools covering various aspects of electricity grid data (demand, generation, prices, storage, etc.), the count is well-scoped and each tool serves a specific role.
The tool surface covers major domain operations: demand, generation mix, carbon intensity, prices, storage, international exchanges, and indicator discovery. The generic get_indicator_data fills any gaps.
Maintenance
Related MCP Connectors
WHOOP recovery, strain, sleep and workouts in Claude via official WHOOP OAuth. Free, open source.
tri-train is a training platform for triathletes that syncs activities from Strava and Garmin and exposes them to Claude through a remote MCP server. Ask Claude how your last block went, why your run pace dropped, or whether you are fresh enough for Sunday's race, and it answers from your real data: activities with laps and grade-adjusted pace, weekly load and the performance management chart (CTL/ATL/TSB), sleep, HRV and resting heart rate, and your race calendar with predictions. Claude can also act: create and adjust planned workouts with structured intervals, push them to your Garmin watch, add races and write notes. Every change is journaled and can be undone. Read and write access are separate OAuth scopes, and the server enforces them on every call. Built and hosted in Switzerland by a triathlete; data stays on our own servers (Swiss revDSG / GDPR).
Connect Claude to your Platform7n workspaces: chat, links, work and decks. One-click OAuth.
GA4, Google Ads and Search Console in Claude. Read-only OAuth, multi-account for agencies.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables AI-powered analysis and prediction of household energy consumption through machine learning models, providing historical consumption breakdowns, price queries from Spanish electricity markets, and personalized energy optimization recommendations.-
- AlicenseAqualityDmaintenanceEnables real-time solar data from Fronius inverters via Claude, allowing natural language queries about solar production, battery, and grid exchange.51Apache 2.0
- AlicenseNot gradedqualityCmaintenanceEnables real-time access to US electricity generation, fuel mix, and demand data through natural language queries.268 npmMIT
- AlicenseNot gradedqualityBmaintenanceDC Hub is the live data layer for data-center siting that agents can query and cite. Its Data Center Power Index (DCPI) scores where data centers can get grid power across 300+ markets daily. Also 330,000+ mapped power, grid, gas and fiber assets. 94 MCP tools at https://dchub.cloud/mcp plus a REST API at https://dchub.cloud/api/v1. Free tier needs no key; paid plans: dchub.cloud/pricing.MIT