emovi-mcp
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., "@emovi-mcp ¿Cuál es la distribución educativa por sexo?"
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.
emovi-mcp
Servidor MCP para la encuesta ESRU-EMOVI 2023 de movilidad social en México.
MCP server for the ESRU-EMOVI 2023 social mobility survey (Mexico).
¿Qué es esto?
emovi-mcp permite que asistentes de IA (Claude, ChatGPT, etc.) consulten la encuesta de movilidad social más completa de México mediante lenguaje natural. Expone cómputos estadísticos ponderados, matrices de transición intergeneracional y exploración de variables como herramientas MCP.
Related MCP server: MoSPI MCP Server
Sobre la ESRU-EMOVI 2023
La encuesta ESRU-EMOVI 2023, levantada por el Centro de Estudios Espinosa Yglesias (CEEY), es representativa a nivel nacional sobre movilidad social en México. Cubre 17,843 entrevistados de 25 a 64 años, con factores de expansión que representan ~60 millones de personas.
Bases de datos incluidas:
Base de datos | Descripción | Registros | Variables |
| Datos del entrevistado principal | 17,843 | ~296 |
| Roster del hogar | 55,477 | ~56 |
| Ingreso imputado 2017 (comparación temporal) | 17,665 | ~2 |
| Módulo de inclusión financiera | 5,976 | ~109 |
Instalación
# Clonar el repositorio
git clone https://github.com/Lalitronico/emovi-mcp.git
cd emovi-mcp
# Crear entorno virtual
python -m venv .venv
source .venv/bin/activate # Linux/Mac
.venv\Scripts\activate # Windows
# Instalar en modo editable con dependencias de desarrollo
pip install -e ".[dev]"
# Opcional: soporte de visualización
pip install -e ".[dev,viz]"O instalar directamente desde PyPI:
pip install emovi-mcp
# Con soporte de visualización
pip install emovi-mcp[viz]Prerrequisitos
Python >= 3.10
Archivos .dta de la ESRU-EMOVI 2023 (obtener del CEEY)
Configuración
Establecer la variable de entorno EMOVI_DATA_DIR apuntando al directorio con los archivos .dta:
# Linux/Mac
export EMOVI_DATA_DIR="/ruta/a/Esru Emovi 2023/_extracted/3 BASES DE DATOS/Data"
# Windows (PowerShell)
$env:EMOVI_DATA_DIR = "C:\ruta\a\Esru Emovi 2023\_extracted\3 BASES DE DATOS\Data"
# Windows (cmd)
set EMOVI_DATA_DIR=C:\ruta\a\Esru Emovi 2023\_extracted\3 BASES DE DATOS\DataUso con Claude Desktop
Agregar lo siguiente al archivo claude_desktop_config.json:
Windows: %APPDATA%\Claude\claude_desktop_config.json
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"emovi-mcp": {
"command": "C:/ruta/a/emovi-mcp/.venv/Scripts/python.exe",
"args": ["-m", "emovi_mcp"],
"env": {
"EMOVI_DATA_DIR": "C:/ruta/a/3 BASES DE DATOS/Data"
}
}
}
}En macOS/Linux, reemplazar Scripts/python.exe por bin/python.
Herramientas
El servidor expone 11 herramientas MCP:
Herramienta | Descripción |
| Panorama de la encuesta: bases de datos, tamaño muestral, diseño, dimensiones |
| Explorar variables por base, sección o palabra clave |
| Información completa de una variable: etiqueta, valores, sección, base |
| Tabulación cruzada ponderada (fila x columna con factores de expansión) |
| Matriz de movilidad intergeneracional con índices formales (Shorrocks, Prais, razón de momios) y errores estándar opcionales vía linealización de Taylor |
| Estadísticas descriptivas: media, mediana, desviación estándar, cuantiles (ponderados) |
| Comparar una variable entre grupos (media, mediana o distribución) |
| Extraer registros con filtros opcionales (máximo 100 filas) |
| Análisis de inclusión financiera: ahorro, crédito, banca, alfabetización, discriminación |
| Comparación temporal de ingreso 2017 vs 2023 con clasificación por línea de pobreza |
| Generar heatmaps, diagramas Sankey o gráficas de barras para matrices de movilidad (requiere |
Ejemplos de consultas
Una vez conectado, puedes preguntar al asistente de IA cosas como:
"¿Cuál es la distribución educativa por sexo?" → Usa
tabulate(row_var="educ", col_var="sexo")"Muéstrame la matriz de movilidad educativa intergeneracional" → Usa
transition_matrix(dimension="education")"¿Cuál es el ingreso promedio por región?" → Usa
weighted_stats(variable="ingc_pc", by="region_14")"Compara la movilidad educativa entre hombres y mujeres" → Usa
transition_matrix(dimension="education", by="sexo")"¿Qué variables hay sobre educación?" → Usa
list_variables(search="educ")
Diccionario de variables
El proyecto incluye un diccionario preconstruido con 792 variables extraídas de la documentación oficial del CEEY y los metadatos de los archivos .dta. Soporta búsqueda por nombre, descripción, base de datos y sección.
Para reconstruir el diccionario desde los datos fuente:
python scripts/build_dictionary.pyEsto requiere el archivo Diccionario ESRU EMOVI 2023.xlsx en el directorio de datos.
Ejecutar pruebas
pytestLas 96 pruebas cubren estadísticas ponderadas, matrices de transición, índices de movilidad, errores estándar por linealización de Taylor, inclusión financiera, comparación temporal de ingreso, visualización y funcionalidad del diccionario de variables, todo con datos sintéticos (no se requieren microdatos reales).
Notas técnicas
Todas las estadísticas son ponderadas usando la variable de expansión
factor(ofac_incpara el módulo de inclusión financiera)pyreadstat carga los .dta con
apply_value_formats=Falsepara evitar crashes por etiquetas duplicadas de municipiospadres_eduse construye comomax(educp, educm)siguiendo la metodología del .do del CEEYÍndice de riqueza usa PCA sobre indicadores binarios de activos del hogar (Filmer & Pritchett, 2001), como alternativa al enfoque MCA del CEEY
Errores estándar usan linealización de Taylor para estimadores de razón bajo muestreo estratificado por conglomerados (UPM/estrato)
Índices de movilidad: Shorrocks M, probabilidad de escape de Prais, correlación intergeneracional de Pearson r, razón de momios de esquina
Transporte STDIO: El servidor se comunica por entrada/salida estándar, compatible con Claude Desktop y otros clientes MCP
Estructura del proyecto
emovi-mcp/
├── pyproject.toml
├── README.md
├── LICENSE
├── CONTRIBUTING.md
├── .github/workflows/
│ ├── ci.yml # CI: pytest en Python 3.10/3.11/3.12
│ └── publish.yml # Publicar en PyPI al crear release
├── scripts/
│ └── build_dictionary.py # Constructor del diccionario
├── src/emovi_mcp/
│ ├── __init__.py
│ ├── __main__.py # python -m emovi_mcp
│ ├── main.py # Punto de entrada del servidor FastMCP
│ ├── config.py # Entorno, mapeos, constantes
│ ├── data_loader.py # Cargador lazy de .dta con caché
│ ├── dictionary.py # Diccionario de variables (JSON)
│ ├── stats_engine.py # Matrices de transición, descriptivas
│ ├── data/
│ │ └── dictionary.json # 792 variables
│ ├── helpers/
│ │ ├── formatting.py # Formateadores Markdown para salida LLM
│ │ ├── labels.py # Resolución de etiquetas de valor
│ │ ├── mobility_indices.py # Shorrocks, Prais, razón de momios
│ │ ├── survey_variance.py # Linealización de Taylor para SE/CI
│ │ ├── validation.py # Validación de columnas y filtros
│ │ ├── visualization.py # Heatmaps, Sankey, gráficas de barras
│ │ └── weights.py # Media, mediana, cuantil, frecuencia ponderados
│ └── tools/
│ ├── __init__.py # Registro de herramientas (11 tools)
│ ├── compare.py # compare_groups
│ ├── describe.py # describe_survey
│ ├── financial.py # financial_inclusion_summary
│ ├── mobility.py # transition_matrix
│ ├── stats.py # weighted_stats
│ ├── subset.py # filter_data
│ ├── tabulate.py # tabulate
│ ├── temporal.py # income_comparison
│ ├── variables.py # list_variables, variable_detail
│ └── visualize.py # visualize_mobility
└── tests/
├── conftest.py # Fixtures compartidos (datos sintéticos)
├── test_dictionary.py
├── test_financial.py
├── test_mobility.py
├── test_mobility_indices.py
├── test_stats_engine.py
├── test_survey_variance.py
├── test_temporal.py
├── test_visualization.py
└── test_wealth_index.pyLicencia
MIT
Agradecimientos
Datos de la encuesta: Centro de Estudios Espinosa Yglesias (CEEY) — ESRU-EMOVI 2023.
Available Tools
11 toolscompare_groupsA
Compare a variable across groups defined by another variable.
Args: variable: The variable to compare (e.g., 'ingc_pc', 'educ'). group_var: The grouping variable (e.g., 'sexo', 'region', 'cohorte'). metric: Which metric to compute: 'mean', 'median', or 'distribution'. filter: Optional filter expression. dataset: Which dataset to use (default: entrevistado).
Returns a comparison table showing the metric for each group.
Inputs: variable (required), group_var (required), metric, filter, +1 more. Returns: result
describe_surveyA
Get an overview of the ESRU-EMOVI 2023 social mobility survey.
Returns information about available datasets, survey design, mobility dimensions, and key variables.
Inputs: no named parameters. Returns: result
filter_dataA
Extract a subset of raw data for specific variables.
Args: variables: List of variable names to include (e.g., ["sexo", "educ", "ingc_pc"]). filter: Optional filter expression (e.g., "sexo == 2 and cohorte == 1"). limit: Maximum number of rows to return (default: 20, max: 100). dataset: Which dataset to use (default: entrevistado).
Returns a markdown table with the requested data. Use this to inspect raw values or extract data for custom analysis.
Inputs: variables (required), filter, limit, dataset. Returns: result
financial_inclusion_summaryA
Analyze financial inclusion from the ESRU-EMOVI 2023 inclusion module.
Args: dimension: Financial inclusion dimension to analyze. - "savings": Formal and informal savings behavior - "credit": Access to credit and debt - "banking": Banking services and financial products - "literacy": Financial education and knowledge - "discrimination": Discrimination in financial services filter: Optional filter expression (e.g., "sexo == 1"). by: Optional grouping variable (e.g., "sexo", "entidad").
Returns markdown summary with weighted proportions for each variable in the selected dimension.
Inputs: dimension, filter, by. Returns: result
income_comparisonA
Compare income between 2017 and 2023 for matched respondents.
Merges the 2017 income module with the 2023 respondent data on folio.
Args: metric: What to compute. - "change": Income change statistics (absolute and relative). - "poverty": Poverty transition rates using CEEY poverty lines. - "summary": Full summary with both income change and poverty. filter: Optional filter expression (e.g., "sexo == 1", "rururb == 1"). by: Optional grouping variable (e.g., "sexo", "rururb", "cohorte").
Returns markdown summary with weighted statistics on temporal income dynamics.
Inputs: metric, filter, by. Returns: result
list_variablesA
List available variables in the survey.
Args: dataset: Which dataset to list variables from. Options: entrevistado, hogar, inclusion_financiera. section: Filter by questionnaire section (optional). search: Search term to filter by variable name or description (optional).
Returns a list of variables with their labels.
Inputs: dataset, section, search. Returns: result
tabulateA
Compute a weighted crosstab between two variables.
Args: row_var: Variable for rows (e.g., 'educ', 'region'). col_var: Variable for columns (e.g., 'sexo', 'cohorte'). filter: Optional filter expression (e.g., "sexo == 1", "cohorte == 3"). normalize: How to normalize: 'row' (default), 'col', 'all', or 'none'. dataset: Which dataset to use (default: entrevistado).
Returns a markdown table with weighted proportions.
Inputs: row_var (required), col_var (required), filter, normalize, +1 more. Returns: result
transition_matrixA
Compute an intergenerational mobility transition matrix.
This is the core analysis tool for social mobility research.
Args: dimension: Type of mobility to analyze. - "education": Educational mobility (4x4 matrix). Origin = max(father, mother) education; Destination = respondent education. - "occupation": Occupational class mobility. Origin = father's class; Destination = respondent's class. - "wealth": Wealth quintile mobility (5x5 matrix). Based on PCA wealth index from household assets (origin vs current). filter: Optional filter expression. Examples: "sexo == 2" (women only), "cohorte == 1" (ages 25-34), "region_14 == 5" (Southern region of origin). by: Optional grouping variable to produce separate matrices. Examples: "sexo" (by gender), "region_14" (by region of origin), "cohorte" (by age cohort). origin_category: Optional origin quintile/category to filter. Example: 1 for Q1 (poorest) in wealth, or 1 for "Primaria o menos" in education. Returns only the destination distribution for that origin. include_se: If True, compute Taylor-linearized standard errors and 95% confidence intervals for each matrix cell.
Returns markdown transition matrix with row percentages (origin -> destination), summary statistics, formal mobility indices, and optionally standard errors.
Inputs: dimension, filter, by, origin_category, +1 more. Returns: result
variable_detailA
Get detailed information about a specific variable.
Args: variable: The variable name (e.g., 'educ', 'ingc_pc', 'sexo').
Returns the variable label, value labels, dataset, and section.
Inputs: variable (required). Returns: result
visualize_mobilityA
Generate a visualization of mobility transition matrix.
Args: dimension: Mobility dimension — "education", "occupation", or "wealth" chart_type: Type of chart — "heatmap", "sankey", or "prais_bar" filter: Optional filter expression (e.g., "sexo == 1") by: Optional grouping variable
Inputs: dimension, chart_type, filter, by. Returns: result
weighted_statsB
Compute weighted descriptive statistics for a variable.
Args: variable: The numeric variable to analyze (e.g., 'ingc_pc', 'educ'). filter: Optional filter expression (e.g., "sexo == 1"). by: Optional grouping variable (e.g., "region", "sexo", "cohorte"). dataset: Which dataset to use (default: entrevistado).
Returns weighted mean, median, std, percentiles (25th, 75th), min, max, and sample sizes. If 'by' is specified, returns stats per group.
Inputs: variable (required), filter, by, dataset. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
Each tool has a clearly distinct purpose: compare_groups, tabulate, and weighted_stats all handle different analyses; transition_matrix is unique; list_variables and variable_detail are complementary but not overlapping. No two tools could be confused.
All names use snake_case with a mostly verb_noun pattern (e.g., compare_groups, describe_survey). A few names like financial_inclusion_summary break the pattern but style remains consistent.
11 tools cover data exploration, filtering, statistics, specialized analyses, and visualization. The scope is well-matched to the survey domain without unnecessary excess or deficiency.
Core workflows (variable exploration, cross-tabulation, mobility analysis, visualizations) are covered. Missing advanced modeling or export options, but the set handles essential research tasks.
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
MCP server unifying ERPs, CRMs, APIs and knowledge base for Claude, ChatGPT and Gemini.
Official Microsoft MCP Server to query Microsoft Entra data using natural language
Related MCP Servers
- AlicenseBqualityDmaintenanceMCP server for accessing Japanese government statistics portal 'e-Stat' API, enabling language models to search and retrieve statistical data.597 PyPI21MIT
- AlicenseNot gradedqualityDmaintenanceMCP server for accessing India's Ministry of Statistics and Programme Implementation (MoSPI) data APIs. Enables natural language queries for economic, demographic, and social indicators via a 4-tool workflow.MIT
- AlicenseAqualityDmaintenanceAn MCP server that exposes the IPUMS API as LLM tools for browsing metadata, creating and downloading extracts, and generating reproducible R/Python code.23MIT
- AlicenseAqualityCmaintenanceMCP server for ENAHO (Peru's national household survey) microdata. Enables discovery, download, merging, and complex-survey statistical estimation of official poverty and income indicators, with report generation.321MIT