Skip to main content
Glama
Microfinance Warehouse MCP Server

Microfinance Warehouse MCP Server

Microfinance Warehouse MCP Server

CI Python License: MIT

An MCP server that lets any AI agent (Claude Desktop, Cursor, an agent framework) analyse a microfinance loan-portfolio data warehouse safely: read-only, with official KPI definitions, and with every query checked before it runs.

"What is PAR30 by region at the end of 2025?" → the agent calls compute_kpi(kpi="par30", group_by=["region"]) and gets the figures, the official definition and the SQL that produced them.

Result: the semantic layer is what makes answers correct

Same model (qwen3.8-27b), 20 business questions with expected results, three ways of giving it the warehouse:

What the model gets

Standard KPI questions (PAR30, portfolio, write-offs…)

One-off questions

All

Raw tables only

5 of 14

6 of 6

11 of 20

Tables + KPI glossary

12 of 14

6 of 6

18 of 20

Tables + glossary + compute_kpi tool

13 of 14

6 of 6

19 of 20

Simple questions ("how many branches in the North?") are answered well either way. Business indicators are not: with raw tables the model invents its own definition of "overdue" and gets PAR30 wrong. With the glossary it can still improvise: one answer recomputed overdue days itself, counted loans paid late as overdue, and reported a PAR30 of 41% instead of 5%. Through compute_kpi, the definition is not the model's to choose.

Read with care: one run per question, one model, 20 questions I wrote, and two grading bugs in my harness were fixed after the first run (KPI calls wrapped in a ```json block were sent to the SQL guard, and correct quarterly figures labelled as dates were marked wrong). No prompt was changed. Every wrong answer is listed in eval/results.md.

Related MCP server: sql-guard-mcp

Why

Giving an AI agent a database raises two problems:

  1. Safety. A model can be talked into writing DROP TABLE, reading files on the server, or leaking environment variables. A system prompt saying "please only read" is not a control.

  2. Consistency. Ask three people for "portfolio at risk" and you get three numbers: do written-off loans count? Overdue by days or by instalments? Agents improvising SQL have the same problem.

This server addresses both, and measures the second.

What the agent gets

Tool

Purpose

list_tables

Schema with column descriptions

get_glossary

Official KPI definitions and the dimensions they can be split by

compute_kpi

One of 10 vetted KPIs (PAR30, PAR90, outstanding portfolio, disbursements, write-offs, on-time repayment…), grouped by branch, region, segment, gender, month, quarter…

run_sql

Any read-only query, through the guard, for questions the KPIs do not cover

Plus a warehouse://glossary resource and a portfolio_review prompt. Every tool is marked read-only (readOnlyHint).

Security: three independent layers

flowchart LR
    A[Agent SQL] --> P{1. Parse<br/>one SELECT only}
    P -- no --> R[Refused with a reason]
    P -- yes --> L{2. Allowlist<br/>warehouse tables only,<br/>no file or env functions}
    L -- no --> R
    L -- yes --> C[3. Locked connection<br/>read-only, no external access,<br/>row limit, 10 s timeout]
    C --> D[(DuckDB)]
  1. Parse with sqlglot: exactly one statement, and it must be a query.

  2. Allowlist: only warehouse tables, CTEs and the loan_position() macro. DuckDB can read files directly (FROM 'C:/data.csv', read_csv(...)) and environment variables (getenv): all refused.

  3. Locked connection: opened read-only with enable_external_access = false and lock_configuration = true, so even a query that slipped past the guard could not write or read files. A row limit and a timeout apply to every query.

tests/test_security.py runs 25 attacks: writes, stacked statements, file reads, file paths as tables, getenv, ATTACH, COPY, INSTALL, settings changes, system catalogs. Every one is refused, and a separate test bypasses the guard to show the connection alone still refuses writes and file reads.

The warehouse

Synthetic, seeded data shaped like a Tunisian microfinance institution: 12 branches, 5 loan products, 8,000 clients, about 9,000 loans (2023–2025) and 127,000 instalments, in a star schema. Some patterns are planted so analysis has something to find: two weaker branches, riskier agricultural loans, a small portfolio-quality gap between women and men.

The semantic layer lives in the warehouse itself: loan_position(date) computes each loan's outstanding principal and days overdue at any date, and every KPI is built on it. PAR30 is the standard microfinance definition: outstanding principal of loans with an instalment more than 30 days overdue, divided by the total outstanding portfolio.

No real person or institution is represented.

Quick start

python -m venv .venv
.venv/Scripts/activate              # Linux/macOS: source .venv/bin/activate
pip install -e ".[dev]"
python -m mfi_mcp.generate          # builds data/warehouse.duckdb in a few seconds
pytest                              # security, server and KPI tests

Use it from Claude Desktop

Add to claude_desktop_config.json (Settings → Developer → Edit config), with your own path:

{
  "mcpServers": {
    "microfinance-warehouse": {
      "command": "C:\\path\\to\\mfi-warehouse-mcp\\.venv\\Scripts\\mfi-mcp.exe"
    }
  }
}

Then ask, for example: "Review the loan portfolio quality at the end of 2025 and name the three weakest branches."

Use it from Python

import asyncio
from mcp import Client, StdioServerParameters

async def main():
    async with Client(StdioServerParameters(command="mfi-mcp")) as client:
        result = await client.call_tool("compute_kpi", {"kpi": "par30", "group_by": ["segment"]})
        print(result.content[0].text)

asyncio.run(main())

Evaluation

python eval/eval_text2sql.py     # needs a Groq or Gemini key in .env

20 business questions with expected results, three setups with the same model: raw schema only, schema plus glossary, and the compute_kpi tool. Results and every wrong answer: eval/results.md.

Layout

src/mfi_mcp/
  server.py     MCP server: tools, resource, prompt
  guard.py      SQL guard: parse + allowlist
  db.py         locked DuckDB connection, row limit, timeout
  semantic.py   KPI definitions and the loan_position macro
  generate.py   synthetic warehouse generator
tests/          security attacks, server tests through a real MCP client
eval/           business questions, evaluation script, results

Limitations

  • Synthetic data. Patterns are planted, so findings illustrate the method, not a real institution.

  • One snapshot. The warehouse is regenerated, not loaded incrementally.

  • The guard is an allowlist for one warehouse. Pointing it at another database means updating the table list.

Available Tools

4 tools
compute_kpiA
Read-onlyIdempotent

Compute an official KPI.

kpi: one of outstanding_portfolio, par30, par90, active_loans, active_clients, disbursed_amount, disbursed_loans, average_loan_size, written_off_amount, on_time_repayment_rate. as_of: date for snapshot KPIs (YYYY-MM-DD, default 2025-12-31). start, end: period for flow KPIs (YYYY-MM-DD, inclusive). group_by: dimensions among branch, governorate, region, product, segment, gender, sector, and for flow KPIs month, quarter, year. filters: dimension -> value, e.g. {"region": "South"}.

Inputs: kpi (required), end, as_of, start, +2 more.

get_glossaryA
Read-onlyIdempotent

Official definitions of the business KPIs, the dimensions they can be split by, and the loan_position(date) SQL macro that implements outstanding principal and days overdue.

Inputs: no named parameters. Returns: result

list_tablesB
Read-onlyIdempotent

The warehouse schema: every table with its columns, types and short descriptions.

Inputs: no named parameters. Returns: result

run_sqlA
Read-onlyIdempotent

Run one read-only DuckDB SELECT query (at most 200 rows returned).

Only warehouse tables and the loan_position(DATE 'YYYY-MM-DD') macro can be read. Writes, file access and settings are refused with an explanation.

Inputs: sql (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 4 tools

    Disambiguation5/5

    Each tool occupies a clearly distinct layer: schema introspection (list_tables), business semantics (get_glossary), governed metric computation (compute_kpi), and ad-hoc exploration (run_sql). The only potential confusion—compute_kpi vs run_sql—is explicitly resolved, since one is the official KPI path and the other is a raw read-only query escape hatch.

    Naming Consistency5/5

    All four names follow a strict snake_case verb_noun pattern (list_tables, get_glossary, compute_kpi, run_sql). The verbs are meaningful and non-overlapping, so the convention is both consistent and self-documenting.

    Tool Count5/5

    Four tools is lean but fully justified for a warehouse/KPI server: metadata, definitions, governed metrics, and a general query fallback, with no redundant or filler tools. The surface is compact yet capable of answering any read-only analytical question.

    Completeness4/5

    The lifecycle is well covered—discover schema, understand KPIs, compute them, and fall back to SQL for anything else—with no obvious dead ends. Minor gaps include no tool to enumerate available filter values (e.g. known regions/branches) or relationship/join metadata, though both can be worked around via run_sql or list_tables.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to explore and query a SQL database safely, answering questions with real data while blocking writes, hiding protected columns, restricting results to one tenant's rows, and logging every call to an audit trail.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to query DuckDB, Postgres, and BigQuery through a governed, read-only layer with a semantic model, SQL guard, role-based row policies, PII pseudonymization, audit logging, and cost caps.
      17 PyPI
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Gives AI agents governed context about a data warehouse — table meaning, ownership, lineage, freshness, and PII flags — plus read-only, row-limited, PII-protected querying across DuckDB, Snowflake, and Databricks. Guardrails enforced at parsing, connection, and result layers keep agents from writing, running away, or leaking personal data.
      32 PyPI
      MIT