Skip to main content
Glama
MEL Evidence MCP

MEL Evidence MCP

by tiwipaddler
README.md
# MEL Evidence MCP

> An MCP server that lets an AI assistant answer questions about a development programme's evidence (evaluation reports, survey data and indicator targets) with a citation for every claim and no way to expose a respondent's personal data. A LangGraph agent watches survey rounds for silent changes that would break comparisons.

Built for monitoring, evaluation and learning (MEL) teams. Runs entirely on public data.

---

## In plain words

A programme team has piles of reports and spreadsheets of survey answers. Answering *"did farmers get more credit by the end of the project?"* takes hours of digging. This project lets an assistant like Claude do the digging, safely:

1. **Every report gets a label card**: which project, which stage (baseline, midline, endline), where, and how many people were surveyed.
2. **Reports are searchable by meaning**, so asking about "loans" also finds passages about "credit".
3. **Survey answers are locked in a box.** The AI can't open it. It can only ask for totals and averages. If a group has fewer than 10 people, the box refuses, because you could work out who they are.
4. **A scorecard** shows what each project promised and what it achieved, from public aid data.
5. **MCP is the menu of buttons** the AI is allowed to press. There are seven, all read-only.
6. **Every answer comes with receipts**: report, page, stage and sample size.
7. **An agent checks for silent changes.** If a survey question is renamed or recoded between rounds, comparisons quietly break. The agent spots it and raises an alert.

---

## Architecture

```
Claude Desktop (or any MCP client)
        │  MCP over stdio
        ▼
mel-evidence server ─────────────────────────────── audit log (who, what, outcome)
  ├─ Documents   search_reports
  │                Chroma vector search, filtered by phase, country, project, year;
  │                results carry citations and index freshness, and gaps are named
  └─ Data        list_datasets · describe_dataset · aggregate · compare_rounds
                 find_indicators · get_indicator
                   DuckDB over Parquet; aggregates only; small groups suppressed;
                   queries time out
                      ▲
                      │ reports/  (read through mel://drift/latest)
Drift agent (LangGraph, scheduled) ── plan → detect → investigate → summarise → alert
```

### MCP features

| Feature | Who controls it | Used for |
|---|---|---|
| **Tools** (7) | The model decides when to call them | Searching reports, aggregating survey data, comparing rounds, looking up indicators |
| **Resources** (4) | The application or user attaches them | Document catalog, valid filter values, data dictionaries, latest drift report |
| **Prompts** (3) | The user picks them | `compare_phases`, `indicator_report`, `evidence_summary` |

Resources are attached by the client, not fetched by the model, so information the model needs to work on its own, such as each dataset's variables, is also available as a tool (`describe_dataset`).

---

## Design principles

These follow practices that teams running MCP in production describe. For example, Jacaranda Health's talk at MCP Dev Summit Nairobi (November 2026), *Map the journey, not the API*, showed the same principles on maternal-health systems.

| Principle | How it's built here |
|---|---|
| **Fixed operations only** | Seven fixed tools. The model never writes SQL; it picks a dataset, variable, statistic and breakdown, and the tested query does the rest. |
| **No personal data ever returned** | The data dictionary is the access policy: every variable is `group`, `measure`, `id` or `exclude`, and `id`/`exclude` variables are never listed, queried or profiled. Groups under `MIN_CELL_SIZE` (10) are suppressed without revealing their size. |
| **Access follows the rules, not what the AI is told** | Rules are enforced in code (dictionary roles, typed parameters, value checks), not by prompt instructions. |
| **Read-only** | Every tool is annotated `readOnlyHint`, and none can write. |
| **Source-linked evidence** | Citations are part of the tool output (title, page, phase, year, n), not just requested in the prompt. |
| **Who? What? Logged** | Every call goes to `logs/audit.jsonl` with user, tool, arguments, outcome, result count and duration. Results themselves are not logged. |
| **Protect the system** | Data queries stop after `QUERY_TIMEOUT_SECONDS`, and breakdowns are capped at 50 groups. |
| **Show freshness and gaps** | Search results include when the index was built; aggregates include when the data last changed. An empty search says whether *no documents* match the filters (a gap in the evidence) or none were relevant. |
| **Configuration shows intent; evidence shows what happened** | Indicator targets (intent) sit next to actuals (observed). The drift agent compares what analysis expects (`variable_usage.csv`) with what each survey round contains. |

### Why no LangChain in the server?

The MCP client (Claude Desktop) is the agent: it decides which tools to call. The server only provides fixed tools, so it uses `chromadb`, `sentence-transformers` and `duckdb` directly, which keeps every step visible and easy to explain. LangGraph is used where an agent actually runs inside this project: the drift agent.

---

## The drift agent

A survey form changes between rounds: `yield_kg` becomes `maize_yield_kg`, "Female" becomes "F", land is recorded in square metres instead of acres. Nothing errors. The comparison is simply wrong.

```
plan ─► detect ─┬─ nothing changed ─► record_all_clear ─► END
                └─ drift found ─► investigate ─► summarise ─► alert ─► END
```

- **plan**: pairs consecutive rounds of each project (baseline → midline → endline)
- **detect**: compares the rounds and finds possible renames, removed or added variables, recoded categories, type changes, likely unit changes (averages 5x apart) and jumps in missing answers
- **investigate**: looks up which indicators or scripts read each changed variable (`data/variable_usage.csv`) and raises the severity when something depends on it
- **summarise**: writes a plain-language alert with Claude if `ANTHROPIC_API_KEY` is set, otherwise with a template. Only findings are sent, never survey rows. If the API call fails, the template is used.
- **alert**: writes `reports/drift_<time>.md` and `.json`. `reports/last_run.json` always records when it last checked.

`mel-drift` exits with code 2 when high-severity drift is found, so a scheduler or CI job can react. To run it every hour with cron:

```
0 * * * * cd /path/to/mel-evidence-mcp && venv/bin/mel-drift >> logs/drift.log 2>&1
```

The assistant can run the same checks on demand with `compare_rounds`, and read the latest report through `mel://drift/latest`.

---

## Setup

Requires Python 3.11.

```bash
git clone https://github.com/<you>/mel-evidence-mcp.git
cd mel-evidence-mcp
python3.11 -m venv venv
source venv/bin/activate

pip install -r requirements.txt     # tested versions
pip install -e . --no-deps          # installs the mel-* commands
cp .env.example .env
```

### Add evidence (all public; see [data_sources.md](data_sources.md))

```bash
# 1. Reports: put PDFs in docs/ and describe each in docs/manifest.csv
#    (template: examples/manifest.example.csv), then build the index
mel-ingest

# 2. Survey rounds: convert each cleaned file, then REVIEW data/<name>.dictionary.csv
mel-prepare-survey baseline_clean.dta --name credit_baseline --title "Rural credit RCT, baseline" \
    --phase baseline --project "Rural credit RCT" --country Kenya --year 2017
mel-prepare-survey endline_clean.dta --name credit_endline --title "Rural credit RCT, endline" \
    --phase endline --project "Rural credit RCT" --country Kenya --year 2020

# 3. Indicator tracker from IATI (needs a free IATI_API_KEY), or from a downloaded XML file
mel-fetch-iati --country KE --sector 311 --since 2018-01-01
mel-prepare-iati downloaded_activities.xml

# 4. Optional: list which indicators/scripts read which variables (examples/variable_usage.example.csv)
#    then check the rounds for drift
mel-drift
```

### Connect an assistant

Try the server in the MCP Inspector first:

```bash
npx @modelcontextprotocol/inspector venv/bin/mel-mcp-server
```

Then add it to Claude Desktop's `claude_desktop_config.json` using full paths (template: `examples/claude_desktop_config.example.json`) and restart Claude Desktop.

### Commands

| Command | What it does |
|---|---|
| `mel-mcp-server` | Runs the MCP server (stdio) |
| `mel-ingest` | Builds the document index from `docs/` |
| `mel-search "query" --phase endline` | Searches the index from the terminal |
| `mel-prepare-survey` | Survey file (.dta/.csv/.parquet) → Parquet + data dictionary |
| `mel-fetch-iati` | IATI Datastore API → raw XML → indicator tracker |
| `mel-prepare-iati` | IATI XML file → indicator tracker |
| `mel-drift` | Runs the drift agent once |

---

## Example questions

- *"Compare what the baseline and endline reports say about access to credit."* (or the `compare_phases` prompt)
- *"What share of households used fertiliser at endline, by gender?"*
- *"Can I compare yields between baseline and endline?"* → the assistant calls `compare_rounds` and warns about the rename first
- *"How is the maize yield indicator doing against target, and do the reports explain why?"*

---

## Tests

```bash
pytest
```

44 tests run in a few seconds, without API keys, model downloads or network access, using a fake embedding model and synthetic data with planted drift. They cover chunking, filtered search and citations; that names, phone numbers and IDs can never be queried; small-group suppression; query timeouts; drift detection and the agent's alert, all-clear and fallback paths; the audit log; IATI fetching against a fake API; and the server through a real MCP client session.

---

## Project structure

```
src/mel_mcp/
├── config.py          settings from .env
├── metadata.py        document manifest and MEL vocabularies
├── documents.py       chunking, embeddings, Chroma index, filters, citations
├── data_engine.py     aggregate-only DuckDB queries, profiles, indicator tracker
├── drift.py           comparing survey rounds; affected readers
├── audit.py           audit log
├── server.py          the MCP server: tools, resources, prompts
├── agents/
│   └── drift_agent.py LangGraph drift agent
├── ingest.py, search.py, prepare_survey.py, prepare_iati.py, fetch_iati.py   commands
tests/                 44 tests, synthetic data only
examples/              manifest, variable usage and Claude Desktop config templates
data_sources.md        the public documents and datasets used
```

---

## Known limitations

- **Differencing.** Aggregates aren't perfectly safe: comparing an overall result with visible groups can reveal something about a suppressed group. Production mitigations include rate-limiting overlapping queries or adding statistical noise.
- **Drift heuristics.** Renames are matched on label, type, categories and name similarity, and unit changes on a 5x change in the average. A real programme change can look like drift, and the agent flags it for a person to check.
- **Single user.** The audit log records the local user; a shared deployment would need real authentication.
- **No evaluation set yet**, so retrieval quality is untested on real documents. This is the next step.

## Roadmap

- [ ] Evaluation set with gold answers; retrieval and answer-quality metrics
- [ ] Hybrid keyword + semantic search, for indicator codes like "IR 2.1"
- [ ] FGD and KII transcripts chunked by speaker turn
- [ ] Personal-data screening at ingestion (e.g. Microsoft Presidio) for non-public data
- [ ] Drift alerts to Slack or email

## License

MIT. See [LICENSE](LICENSE).