Logo di MoSPI MCP Server

MoSPI MCP Server

Community
nso-india

This repository consists of Source Code for Model Context Protocol (MCP) Pilot Project being undertaken by Ministry of Statistics and Programme Implementation and source code for the same is being shared under MIT License.

Pubblicato danso-india
Repositoryesankhyiki-mcp
LinguaPython
Fork
29
Stelle
138
Strumenti disponibili
0
Tipo di trasportostdio, streamable-http
Categorie
LicenzaMIT
Link
  • Collega gli strumenti ai flussi di lavoro IA

    MoSPI MCP Server mette a disposizione funzionalità MCP utilizzabili da client e agenti IA compatibili.

  • Strumenti disponibili: 0

    Esplora le azioni richiamabili qui sotto, con nomi e descrizioni se il server li fornisce.

  • Configurazione pronta da copiare

    Usa gli esempi di installazione per configurare questo server nel tuo client MCP preferito.

  • Indicatori di interesse della comunità open source

    Stelle: 138; fork: 29 (repository collegato).

MoSPI MCP Server

License: MIT Python 3.11+ FastMCP MCP Server Tests

MCP (Model Context Protocol) server for accessing India's Ministry of Statistics and Programme Implementation (MoSPI) data APIs. Built with FastMCP 3.3.


Table of Contents


Overview

This server provides AI-ready access to official Indian government statistics through the Model Context Protocol (MCP). It acts as a bridge between AI assistants (Claude, ChatGPT, Cursor, etc.) and MoSPI's open data APIs, enabling natural language queries for economic, demographic, and social indicators.

Key Features:

  • Following statistical datasets covering employment, unemployment, inflation, industrial and services production, GDP and national accounts, energy and renewable energy, higher and school education, gender, health and nutrition, disability, housing and sanitation, household consumption and expenditure, time use, agriculture and livestock, land holdings, debt and investment, AYUSH, environment and climate, banking and financial statistics, economic census, unincorporated enterprises, telecom and digital connectivity.
  • Sequential 4-tool workflow designed for LLM consumption
  • Swagger-driven parameter validation
  • Full OpenTelemetry integration for observability
  • Production-ready Docker deployment
  • Note: Some NSS rounds include sub-parts (NSS77A, NSS79C, NSS76C, NSS80E), which are shown as separate entries in the README for user understanding. On the server, however, these sub-parts are accessible through their respective parent NSS round dataset (NSS77, NSS79, NSS76, NSS80) itself, rather than as independent datasets.

Dataset Reference

Sr. No.DatasetFull NameUse For
1PLFSPeriodic Labour Force SurveyEmployment, unemployment, labour force participation, worker population ratio, wages, employment by industry and occupation
2CPIConsumer Price IndexRetail inflation, cost of living, inflation by commodity group, state-wise and rural/urban price indices
3IIPIndex of Industrial ProductionIndustrial growth, manufacturing output, mining, electricity generation, sector-wise production indices
4ASIAnnual Survey of IndustriesFactory performance, industrial employment, wages, fixed capital, output, value added, productivity
5NASNational Accounts StatisticsGDP, GVA, national income, sector-wise economic growth, savings, capital formation
6WPIWholesale Price IndexWholesale inflation, producer prices, commodity price indices, inflation trends
7ENERGYEnergy StatisticsEnergy production, consumption, installed capacity, fuel mix, energy intensity, renewable energy statistics
8AISHEAll India Survey on Higher EducationUniversities, colleges, enrolment, teachers, Gross Enrolment Ratio (GER), Gender Parity Index (GPI), higher education infrastructure
9ASUSEAnnual Survey of Unincorporated Sector EnterprisesUnincorporated enterprises, MSMEs, employment, output, value added, informal sector statistics
10GENDERGender StatisticsGender indicators, women empowerment, sex ratio, labour participation, education, health, crimes against women
11NFHSNational Family Health SurveyFertility, family planning, maternal and child health, nutrition, infant mortality, health indicators
12ENVSTATSEnvironment StatisticsClimate, biodiversity, forests, air and water quality, environmental resources, pollution indicators
13RBIRBI StatisticsBanking, money supply, foreign exchange reserves, exchange rates, balance of payments, external sector, financial indicators
14NSS77NSS 77th Round – Land and Livestock HoldingsAgricultural households, land holdings, livestock ownership, crop insurance, farming assets
15NSS77AAll India Debt and Investment Survey (AIDIS) – NSS 77th RoundHousehold assets, liabilities, debt, investment, borrowing patterns, wealth distribution
16NSS78NSS 78th Round – Multiple Indicator SurveyDrinking water, sanitation, housing amenities, migration, digital connectivity, household living conditions
17CPIALRLConsumer Price Index for Agricultural and Rural LabourersRural inflation, agricultural labourer cost of living, rural wage index, inflation trends
18HCESHousehold Consumption Expenditure SurveyHousehold consumption, expenditure patterns, poverty estimation, inequality, consumer behaviour
19TUSTime Use SurveyTime allocation, unpaid care work, paid work, household activities, gender time-use patterns
20ECEconomic CensusEstablishments, enterprises, employment, ownership, economic activity, district-wise business statistics
21NSS79NSS 79th Round – Survey on AYUSHAYUSH awareness, AYUSH utilisation, treatment preferences, expenditure on AYUSH services
22NSS79CComprehensive Annual Modular Survey (CAMS) – NSS 79th RoundEducation, health expenditure, financial inclusion, digital literacy, household living conditions
23UDISEUDISE+ (Unified District Information System for Education Plus)Schools, enrolment, dropout, teachers, PTR, GER, NER, GPI, CWSN, ICT facilities, school infrastructure
24MNRERenewable Energy Statistics (Ministry of New and Renewable Energy)Installed renewable energy capacity, solar, wind, hydro, bioenergy, state-wise renewable energy generation
25NSS76NSS 76th Round – Drinking Water, Sanitation, Hygiene and Housing ConditionsDrinking water sources, water treatment, sanitation, housing characteristics, toilets, flood experience
26NSS76CPersons with Disabilities in India – NSS 76th RoundDisability prevalence, education, employment, accessibility, assistive devices, care arrangements
27NSS75ENSS 75th Round – Social Consumption on EducationLiteracy, educational attainment, school attendance, education expenditure, internet and computer access, GER/NAR
28NSS80NSS 80th Round – Comprehensive Modular Survey: Telecom (CMST)Mobile phone ownership, internet usage, telecom access, digital services, online banking, cyber security awareness
29NSS80ENSS 80th Round – Comprehensive Modular Survey: Education (CMSE)School enrolment, education expenditure, tuition fees, private coaching, scholarships, sources of education funding
30NSS73NSS 73rd Round – Unincorporated Non-Agricultural EnterprisesEnterprise type, enterprise ownership, hired workers, annual emoluments, GVA per worker, employment type, working hours, activity category, sector-wise and state-wise enterprise statistics
31ISPIndex of Service ProductionServices sector growth, monthly services output, sub-sector indices

MCP Tools

The server exposes 4 tools that follow a sequential workflow:

list_datasets  →  get_indicators  →  get_metadata  →  get_data
StepToolDescription
1list_datasets()Overview of all datasets. Start here to find the right dataset.
2get_indicators(dataset)List available indicators for the chosen dataset.
3get_metadata(dataset, ...)Get valid filter values (states, years, categories) and API parameters.
4get_data(dataset, filters)Fetch data using filter key-value pairs from metadata.

Important: Tools must be called in order. Skipping get_metadata will result in invalid filter codes.


Quick Start

If you want to connect your AI agent of choice with the MCP server, you can directly connect it with MOSPI's MCP server. Video Guides to connect ChatGPT or Claude to MCP are available here -

https://github.com/user-attachments/assets/a08376ca-8835-479f-9374-1cca63d5631c

https://github.com/user-attachments/assets/a2d65b8f-c938-43fa-856c-35088063f4bd

To get more information, visit - https://www.datainnovation.mospi.gov.in/mospi-mcp

The instructions below are for self-hosting the MCP server.

Installation

bash
# Clone the repository
git clone https://github.com/nso-india/esankhyiki-mcp.git
cd esankhyiki-mcp

# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Running the Server

bash
# HTTP transport (remote access)
python mospi_server.py

# OR using FastMCP CLI
fastmcp run mospi_server.py:mcp --transport http --port 8000

# stdio transport (local MCP clients)
fastmcp run mospi_server.py:mcp

Server runs at http://localhost:8000/mcp

Connecting from CLI Tools

Server URL: https://mcp.mospi.gov.in/

Claude Code

bash
claude mcp add esankhyiki-mcp --transport http https://mcp.mospi.gov.in/

Verify with claude mcp list.

Cursor / Windsurf

Add to .cursor/mcp.json or .windsurf/mcp.json:

json
{
  "mcpServers": {
    "esankhyiki-mcp": {
      "command": "npx",
      "args": ["mcp-remote", "https://mcp.mospi.gov.in/"]
    }
  }
}

Antigravity

Add to your Antigravity MCP settings:

json
{
  "mcpServers": {
    "mospi_api": {
      "serverUrl": "https://mcp.mospi.gov.in/"
    }
  }
}

Verify Connection

bash
curl -s -X POST https://mcp.mospi.gov.in/ \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"0.1"}}}'

A successful response returns serverInfo with "name": "MoSPI Data Server".

Local Server

If running locally:

bash
claude mcp add esankhyiki-mcp --transport http http://localhost:8000/mcp

Or with the FastMCP Python client:

python
import asyncio
from fastmcp import Client

async def main():
    async with Client("http://localhost:8000/mcp") as client:
        overview = await client.call_tool("list_datasets", {})
        print(overview)

asyncio.run(main())

Deployment

Docker

bash
# Build the image
docker build -t mospi-mcp .

# Run the container
docker run -d -p 8000:8000 --name mospi-server mospi-mcp

Docker Compose

Includes Jaeger for distributed tracing visualization:

bash
docker-compose up -d

Services:

FastMCP Cloud

  1. Push code to GitHub
  2. Sign in to FastMCP Cloud
  3. Create project with entrypoint mospi_server.py:mcp

Architecture

mospi-mcp-api/
Γö£ΓöÇΓöÇ mospi_server.py          # FastMCP server - tools, validation, routing
Γö£ΓöÇΓöÇ mospi/
Γöé   ΓööΓöÇΓöÇ client.py            # MoSPI API client - HTTP requests to api.mospi.gov.in
Γö£ΓöÇΓöÇ swagger/                 # Swagger YAML specs per dataset (source of truth for params)
Γöé   ΓööΓöÇΓöÇ swagger_user_*.yaml
Γö£ΓöÇΓöÇ observability/
Γöé   ΓööΓöÇΓöÇ telemetry.py         # OpenTelemetry middleware for tracing
Γö£ΓöÇΓöÇ tests/                   # Pytest suite (covering all datasets)
Γö£ΓöÇΓöÇ Dockerfile               # Production container with OTEL instrumentation
Γö£ΓöÇΓöÇ docker-compose.yml       # Full stack with Jaeger
ΓööΓöÇΓöÇ requirements.txt

Design Principles

PrincipleImplementation
Swagger as Source of TruthAPI parameters validated against YAML specs in swagger/, not hardcoded
Auto-routingCPI routes to Group/Item endpoint based on filters; IIP routes to Annual/Monthly
Validation FirstAll filters validated before API calls with clear error messages
LLM-OptimizedTool docstrings document parameters, return values, and workflow sequence

Testing

bash
pip install -r tests/requirements-test.txt
pytest tests/ -v -p no:anyio

Runs in-process against the MCP server (no running server needed). Covers all datasets across all 4 tools. See CONTRIBUTING.md for details.


Configuration

Environment variables for OpenTelemetry:

VariableDescriptionDefault
OTEL_SERVICE_NAMEService name in tracesmospi-mcp-server
OTEL_EXPORTER_OTLP_ENDPOINTOTLP collector endpointhttp://localhost:4317
OTEL_EXPORTER_OTLP_PROTOCOLProtocol (grpc or http/protobuf)grpc
OTEL_TRACES_EXPORTERExporter type (otlp, console, none)otlp

See .env.example for full configuration options.


Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines on:

  • Adding new datasets
  • Project structure
  • Development setup
  • Code style

Resources


License

This project is licensed under the MIT License - see the LICENSE file for details.


DIID

The Data Innovation Lab aims to promote innovation and the use of Information Technology in official statistics, including modernizing survey methods. It seeks to address the current challenges faced by the National Statistical System (NSS). The lab will serve as a platform for testing and developing new ideas through proof-of-concept projects. It will foster collaboration with a wide range of participants such as entrepreneurs, researchers, start-ups, academic institutions, and renowned national and international organizations. By creating an open and dynamic environment, the lab will support the advancement of statistical systems and help improve the quality and efficiency of data collection and analysis.

Know more: https://www.datainnovation.mospi.gov.in/home

Acknowledgments

Made in partnership with Bharat Digital in pursuit of modernising and humanising how governments use technology in service of the public.

Installazione

TypingMind
{
  "mcpServers": {
    "esankhyiki-mcp": {
      "command": "fastmcp",
      "args": [
        "run",
        "mospi_server.py:mcp"
      ]
    }
  }
}

Usa MoSPI MCP Server MCP con più modelli AI

TypingMind collega gli strumenti MCP a livello di area di lavoro: una volta connesso MoSPI MCP Server, puoi usarlo con diversi modelli IA in TypingMind, senza configurarlo separatamente per ogni modello. Puoi eseguire MCP localmente sul tuo dispositivo o connetterti all'URL di un server MCP remoto.

Opzione 1: usa il connettore locale

Usa questo metodo quando il server MCP deve accedere a file locali, app o risorse private sul tuo computer.

1

Apri le impostazioni MCP

In TypingMind, vai su Impostazioni, Impostazioni avanzate, poi su Model Context Protocol e scegli Configura connettore.

  1. Apri TypingMind nel tuo browser.
  2. Fai clic sull'icona Impostazioni.
  3. Vai a Impostazioni avanzate.
  4. Apri la sezione Model Context Protocol.
  5. Fai clic su Configura connettore e scegli Questo dispositivo.
Schermata di configurazione del connettore MCP di TypingMind con l’opzione «Questo dispositivo» selezionata
2

Esegui il comando del connettore

Scegli Questo dispositivo, copia il comando da TypingMind ed eseguilo nel terminale. Lascia il processo in esecuzione mentre usi MCP.

  1. Copia il comando di configurazione mostrato da TypingMind.
  2. Apri Terminale su macOS o Windows Terminal su Windows.
  3. Incolla ed esegui il comando.
  4. Conferma l'installazione del pacchetto se il terminale ti chiede di procedere.
  5. Tieni aperta la finestra del terminale con il processo in esecuzione mentre usi gli strumenti MCP.
3

Aggiungi MoSPI MCP Server come server

Quando lo stato del connettore è Pronto, fai clic su Modifica server e incolla la configurazione del server MCP.

  1. Attendi che lo stato del connettore sia Pronto.
  2. Fai clic su Modifica server.
  3. Incolla la configurazione del server MCP di MoSPI MCP Server.
  4. Salva l'elenco dei server.
  5. Se vuoi verificare che il connettore sia ancora pronto, aggiorna la pagina.
Impostazioni MCP di TypingMind con un server attivo e il pulsante Modifica server
{
  "mcpServers": {
    "esankhyiki-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Usa la connessione con diversi modelli

Salva l'elenco dei server, apri Plugin, abilita gli strumenti MCP di MoSPI MCP Server, poi seleziona un modello IA supportato in TypingMind e usa gli strumenti in chat o assegnali a un agente IA.

  1. Apri la pagina Plugin in TypingMind.
  2. Abilita gli strumenti MCP di MoSPI MCP Server.
  3. Avvia una chat e scegli il modello IA che vuoi usare.
  4. Usa gli strumenti MCP in chat o assegnali a un agente IA.
  5. Passa a un altro modello IA quando serve, senza riconnettere MCP.
Chat di TypingMind che usa gli strumenti MCP abilitati con un modello IA selezionato
Puoi usare MoSPI MCP Server per aiutarmi con questa attività?
MoSPI MCP Server
Certo. L’ho letto.
Ecco cosa ho trovato con MoSPI MCP Server.

Opzione 2: aggiungi l'URL di un server MCP

Usa questo metodo se MoSPI MCP Server è già ospitato in remoto o se il tuo team vuole un unico connettore condiviso accessibile a più utenti.

1

Apri Connettori MCP

In TypingMind, vai su Plugin, apri Connettori MCP e scegli Aggiungi URL.

  1. Apri TypingMind nel tuo browser.
  2. Vai a Plugin.
  3. Apri Connettori MCP.
  4. Fai clic su Aggiungi URL.
Modulo di TypingMind per aggiungere l'URL di un server MCP personalizzato
2

Incolla l'URL del server

Inserisci l'URL del server MCP fornito dal provider nel campo URL del server. Aggiungi un nome per la connessione, una descrizione, un'icona, header HTTP personalizzati o le impostazioni del client OAuth se richiesti dal server.

  1. Incolla l'URL del server MCP fornito dal provider nel campo URL del server.
  2. Inserisci un nome per la connessione a MoSPI MCP Server.
  3. Se vuoi riconoscere più facilmente la connessione, aggiungi una descrizione e un’icona.
  4. Aggiungi header HTTP personalizzati o i dati del client OAuth se il server richiede l'autenticazione.
3

Crea la connessione

Fai clic su Crea connessione, poi torna all'elenco dei plugin e verifica che la nuova connessione MCP sia attiva.

  1. Fai clic su Crea connessione.
  2. Torna all'elenco dei connettori MCP.
  3. Verifica che la connessione MoSPI MCP Server risulti attiva.
  4. Aggiorna l'elenco dei plugin se la connessione non appare subito.
4

Cambia modello senza dover ristabilire la connessione MCP

Avvia una chat con il tuo modello preferito, abilita gli strumenti di MoSPI MCP Server dalla sezione Plugin e passa a un altro modello quando serve. La connessione MCP rimane disponibile nell'area di lavoro di TypingMind.

  1. Avvia una nuova chat in TypingMind.
  2. Seleziona il modello IA che vuoi usare.
  3. Abilita gli strumenti di MoSPI MCP Server dalla sezione Plugin.
  4. Chiedi al modello di usare lo strumento quando serve.
  5. Passa a un altro modello IA e riutilizza la stessa connessione MCP.
Chat di TypingMind che usa gli strumenti MCP abilitati con un modello IA selezionato
Puoi usare MoSPI MCP Server per aiutarmi con questa attività?
MoSPI MCP Server
Certo. L’ho letto.
Ecco cosa ho trovato con MoSPI MCP Server.

Domande frequenti

A cosa serve il server MCP MoSPI MCP Server?

MoSPI MCP Server è un server MCP che consente ai client IA compatibili di accedere a strumenti e informazioni di contesto esterni. In TypingMind puoi aggiungere questo server MCP una sola volta e rendere disponibili i suoi strumenti nella tua area di lavoro IA.

Posso usare il server MCP MoSPI MCP Server con più modelli IA in TypingMind?

Sì. TypingMind collega gli strumenti MCP a livello di area di lavoro, quindi puoi usare MoSPI MCP Server con diversi modelli IA come Claude, ChatGPT, Gemini o altri modelli che hai configurato in TypingMind, senza dover configurare il server MCP separatamente per ogni modello.

Perché usare il connettore MCP MoSPI MCP Server con TypingMind?

TypingMind è una delle migliori interfacce per chattare con gli LLM perché riunisce più modelli IA, prompt, plugin, agenti IA, chiavi API e strumenti MCP in un'unica area di lavoro. Collegando MoSPI MCP Server, puoi usare i suoi strumenti MCP con i tuoi modelli preferiti e mantenere organizzato il tuo flusso di lavoro in chat su TypingMind.

Come collego il server MCP MoSPI MCP Server a TypingMind?

Puoi collegare MoSPI MCP Server a TypingMind con il connettore MCP locale oppure aggiungendo l'URL di un server MCP remoto. Usa il connettore locale quando il server deve accedere a file, app o risorse private sul tuo dispositivo; usa invece l'URL del server quando il server MCP è ospitato in remoto.

Quali strumenti offre il server MCP MoSPI MCP Server in TypingMind?

MoSPI MCP Server mette a disposizione funzionalità MCP che puoi attivare dalla pagina Plugin di TypingMind e usare in chat o assegnare agli agenti IA.

Devo condividere le mie chiavi API con TypingMind per usare il server MCP MoSPI MCP Server?

No. TypingMind privilegia il funzionamento in locale e ti permette di mantenere il controllo su fornitori di modelli, chiavi API, prompt e configurazione MCP. Se MoSPI MCP Server richiede l'autenticazione, aggiungi le intestazioni, le impostazioni OAuth o la configurazione locale necessarie per quel server MCP quando crei la connessione.

Server MCP correlati

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇