Metadata-Version: 2.5
Name: india-gov-data-mcp
Version: 0.2.0
Summary: MCP server for India's Open Government Data portal (api.data.gov.in) — discover, inspect, query, and aggregate 150 000+ public datasets via any AI agent.
Author: india-gov-data-mcp Contributors
License: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: duckdb>=1.0.0
Requires-Dist: fastmcp>=2.0.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# india-gov-data-mcp

**MCP server for India's Open Government Data portal (`api.data.gov.in`)**

> Unlike basic data.gov.in wrappers that require memorizing dataset UUIDs, this server lets any AI agent **discover** datasets by keyword, **inspect** messy schemas, **auto-paginate** past the 100-row API limit, **normalize** Indian State/District names, and run **deterministic DuckDB aggregations** so the LLM never hallucinates math.

---

## ✨ Features

| Tool | What it does |
|---|---|
| `search_catalog` | Discover datasets by keyword (local SQLite FTS5 seed/cache first, 5s remote fallback) |
| `inspect_schema` | See column names, types, and sample values before querying |
| `find_filter_values` | Discover exact, case-sensitive filter strings via substring & fuzzy matching |
| `query_records` | Auto-paginates past the 100-row limit, normalizes field names, auto-resolves unambiguous filters |
| `aggregate_dataset` | Exact `SUM`/`AVG`/`MIN`/`MAX`/`COUNT` via DuckDB — no hallucinated math |
| `join_on_geography` | Merges two datasets on state/district with 100+ Indian name-variant mappings |
| `export_dataset` | Export normalized records to CSV, JSON, or Parquet with official citation |
| `get_citation` | Generates a proper citation with URL, timestamp, and filters |

## 🚀 Quick Start

### 1. Get an API Key

Register at [data.gov.in](https://data.gov.in/ogpl_apis) to get a free API key.

### 2. Clone & Install

```bash
git clone https://github.com/your-username/india-gov-data-mcp.git
cd india-gov-data-mcp

# Create virtual environment and install
python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS/Linux
source .venv/bin/activate

pip install -e ".[dev]"
```

### 3. Set Your API Key

```bash
# Copy the template
cp .env.example .env

# Edit .env and add your key
DATA_GOV_API_KEY=your_key_here
```

Or set it as an environment variable:

```bash
export DATA_GOV_API_KEY=your_key_here        # macOS/Linux
set DATA_GOV_API_KEY=your_key_here            # Windows CMD
$env:DATA_GOV_API_KEY="your_key_here"         # PowerShell
```

### 4. Run Tests

```bash
pytest -v
```

### 5. Launch the Server (or run via `uvx`)

```bash
# Run without manual venv setup via uvx (from PyPI or local checkout)
uvx india-gov-data-mcp
uvx --from . india-gov-data-mcp

# Or via the installed entry-point
india-gov-data-mcp

# Or directly
python -m datagov_mcp.server
```

### 6. Sync Additional Catalog Metadata (`datagov-sync-catalog`)

Pre-populate the local SQLite FTS5 catalog cache from `api.data.gov.in`:

```bash
datagov-sync-catalog --pages 10
datagov-sync-catalog --pages 5 --query agriculture
```

---

## 🔌 Client Configuration

### Claude Desktop

Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "india-gov-data-mcp": {
      "command": "india-gov-data-mcp",
      "env": {
        "DATA_GOV_API_KEY": "your_key_here"
      }
    }
  }
}
```

Or if using `uv`:

```json
{
  "mcpServers": {
    "india-gov-data-mcp": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/india-gov-data-mcp", "india-gov-data-mcp"],
      "env": {
        "DATA_GOV_API_KEY": "your_key_here"
      }
    }
  }
}
```

### Cursor

Add to your Cursor MCP settings (`.cursor/mcp.json`):

```json
{
  "mcpServers": {
    "india-gov-data-mcp": {
      "command": "india-gov-data-mcp",
      "env": {
        "DATA_GOV_API_KEY": "your_key_here"
      }
    }
  }
}
```

### Antigravity

Create a file at `.gemini/config/mcp/datagov.json`:

```json
{
  "mcpServers": {
    "india-gov-data-mcp": {
      "command": "india-gov-data-mcp",
      "env": {
        "DATA_GOV_API_KEY": "your_key_here"
      }
    }
  }
}
```

### FastMCP Inspector

```bash
# List all tools
fastmcp list src/datagov_mcp/server.py

# Interactive inspector
fastmcp dev src/datagov_mcp/server.py
```

---

## 🛠️ Tool Reference

### `search_catalog(query, limit=10)`

Search for datasets by keyword. Start here to find `resource_id` values.

```
query: "mandi prices agricultural commodities"
→ Returns resource_id, title, ministry, description
```

### `inspect_schema(resource_id)`

Inspect column names, inferred types, and sample values before querying.

```
resource_id: "9ef84268-d588-465a-a308-a864a43d0070"
→ Returns columns with types (numeric, date, state, district, text)
         + sample values for each column
```

### `query_records(resource_id, filters=None, max_rows=500)`

Fetch records with auto-pagination and name normalization.

```
resource_id: "9ef84268-...", filters: {"State": "Maharashtra"}, max_rows: 1000
→ Returns cleaned records with snake_case keys and normalized state names
```

### `aggregate_dataset(resource_id, group_by, metric_column, operation="sum", filters=None)`

Run exact aggregations via DuckDB — never hallucinates math.

```
group_by: "state_name", metric_column: "production_tonnes", operation: "sum"
→ Returns deterministic SUM grouped by state, sorted descending
```

### `join_on_geography(resource_id_a, resource_id_b, geo_level="state", ...)`

Join two datasets on normalized Indian geography (state or district).

```
Merges "Orissa" ↔ "Odisha", "Bangalore" ↔ "Bengaluru", etc.
→ Returns inner-joined records from both datasets
```

### `get_citation(resource_id, filters=None)`

Generate a proper citation for data attribution.

```
→ 'Government of India, Open Government Data Portal. "Daily Wholesale Prices...".
   Resource ID: 9ef84268-... URL: https://data.gov.in/resource/9ef84268-...
   Retrieved: 2024-01-15T12:00:00+00:00.'
```

### `find_filter_values(resource_id, column, search_term, sample_size=300)`

Resolve exact, case-sensitive filter strings required by `api.data.gov.in` (e.g., `"Gram"` → `"Bengal Gram(Gram)(Whole)"`, `"Kozhikode"` → `"Kozhikode(Calicut)"`).

### `export_dataset(resource_id, output_path, format="csv", filters=None, max_rows=2000)`

Export normalized records locally to `csv`, `json`, or `parquet` (via DuckDB `COPY ... TO`), creating parent directories automatically and returning file size + citation.

---

## 📦 MCP Resources & Prompts

### Resources
- `datagov://geography/states` — Canonical 36 Indian States/UTs and known spelling/legacy variants (e.g., `Orissa` → `Odisha`, `Keralam` → `Kerala`).
- `datagov://catalog/featured` — Curated featured datasets from `data.gov.in`.

### Prompts
- `compare_states(topic, state_a, state_b)` — Step-by-step workflow to discover, inspect, deterministically aggregate, and cite state comparisons.
- `mandi_price_check(commodity, state="Gujarat")` — Step-by-step workflow to inspect Daily Mandi Prices, resolve exact commodity spelling via `find_filter_values`, aggregate district-wise `modal_price`, and cite the source.

---

## 📁 Project Structure

```
india-gov-data-mcp/
├── pyproject.toml               # Hatchling build config (v0.2.0)
├── .env.example                 # API key template
├── README.md
├── src/
│   └── datagov_mcp/
│       ├── __init__.py
│       ├── client.py            # Async HTTP/1.1 httpx client with auto-pagination & retries
│       ├── catalog.py           # Local-first SQLite FTS5 cache + seed index + 5s remote fallback
│       ├── indexer.py           # CLI catalog sync (datagov-sync-catalog)
│       ├── normalizer.py        # Snake_case + Indian State/District canonicalizer + fuzzy matcher
│       ├── analytics.py         # DuckDB aggregation engine, geographic joins & CSV/JSON/Parquet export
│       └── server.py            # FastMCP server with 8 tools, 2 resources, and 2 prompts
└── tests/
    ├── test_normalizer.py       # Name normalization & type inference tests
    ├── test_analytics.py        # DuckDB aggregation & join tests
    └── test_v2.py               # V2 tests (filter discovery, export, indexer, resources, prompts)
```

## 📄 License

MIT
