Skip to main content
Glama
eil-mcp

eil-mcp

Official
README.md
# Enterprise Intelligence Lab

A governed platform for conversational business intelligence: an AI assistant asks business
questions through **MCP tools**, and **deterministic SQL over PostgreSQL** answers them, using
least-privilege, read-only access, with every call audited.

The design rule, carried over from my [Agentic Reliability Lab](https://github.com/minimascientific/agentic-reliability-lab):
**the model asks; deterministic code decides what runs and computes every number.**

> **Status: Milestone 02, Conversational BI.** A command-line assistant: Claude picks tools by
> native tool calling, a real MCP client executes them against the Milestone 01 server, and the
> answer is checked so that every figure comes from a tool result. Tested end to end with a
> deterministic model stand-in (114 tests). **Validated with live Claude (`claude-opus-5-5`) on
> 2026-11-30: all 8 acceptance scenarios passed** in a local run on the author's machine (run 2,
> after fixing two grounding false positives found by run 1). All data is **synthetic**: the company "Bristlecone Analytical LLC" and
> its vendors are fictional. See [Status](#status).

**Stack:** Python 3.12 · Anthropic Claude API (native tool use) · official MCP Python SDK (v2) · PostgreSQL 16 · psycopg 3 · Pydantic ·
pytest · Docker Compose · GitHub Actions · uv

## Ask a question (Milestone 02)

```bash
make ask Q="Which month in 2025 had the highest spending, and what drove it?"
```

```
<Claude's answer; every figure checked against the tool results>  (output shape; see docs/acceptance-tests.md for live results)

Sources (generated from the tool calls, not by the model):
- spending_trend(start_date=2025-01-01, end_date=2025-12-31, granularity=month) · finance-metrics/1 · audit run_id=run-…, client_call_id=toolu_…
- category_breakdown(start_date=2025-01-01, end_date=2025-01-31) · …

[status: answered · run_id: run-… · tool calls: N · model calls: N · tokens: … · …s]
```

How it works: [architecture, Milestone 02](docs/architecture.md#milestone-02-conversational-bi-claude--mcp).
The model asks; code decides what runs, enforces budgets, checks every figure, and writes the
sources. If the period is unclear, it asks. If the request is to change data, it declines: there are
no write tools, and an invented tool name is refused before it reaches the server. If the audit log
is down, there is no data. ADRs [0004](docs/adr/0004-agent-owns-the-loop-mcp-client-plus-native-tool-calling.md),
[0005](docs/adr/0005-figures-must-come-from-tool-results.md), [0006](docs/adr/0006-no-silent-model-fallback.md).

## What Milestone 01 does

```mermaid
flowchart LR
    client["MCP client<br/>(demo client today,<br/>Claude in Milestone 02)"] -- "stdio · JSON-RPC<br/>tools/list, tools/call" --> server
    subgraph server["eil-mcp server process"]
      validate["Validate input<br/>(Pydantic)"] --> run["Fixed, parameterised SQL<br/>(eil.finance.metrics)"]
      run --> audit["Audit record"]
    end
    run -- "eil_reader<br/>SELECT only, read-only session" --> fin[("finance.*")]
    audit -- "eil_audit_writer<br/>INSERT only" --> aud[("audit.tool_calls")]
```

| Tool | Answers | Example |
| --- | --- | --- |
| `expense_summary` | Total, count, average, largest, vendors, missing receipts | "What did we spend in 2025?" |
| `category_breakdown` | Spend per category with share of total | "Where does the money go?" |
| `spending_trend` | Monthly or quarterly totals with period-over-period change | "Is lab-supply spend rising?" |
| `compare_periods` (M02) | Two periods' totals with the change in USD and percent | "Software spend 2025 vs 2024?" |
| `search_transactions` | Individual expenses by date, vendor, category, amount, missing receipt | "Which Q4 expenses have no receipt?" |

All five are annotated `readOnlyHint: true`. Contracts: [docs/architecture.md](docs/architecture.md#mcp-tool-contracts).
Metric definitions: [docs/metrics.md](docs/metrics.md).

## Controls

- **No generated SQL.** Tools run fixed queries. User values travel only as bound parameters, and
  filters are composed from constant SQL fragments ([ADR 0001](docs/adr/0001-fixed-sql-tools-not-text-to-sql.md)).
- **Validated input, typed output.** Every request is checked by a Pydantic model before any SQL
  runs: date order, a maximum range, result limits, amount precision, unknown fields and unknown
  categories. Money is integer cents in the database and exact decimals in responses.
- **Least privilege in the database, not just the code.** The server holds two credentials:
  `eil_reader` (SELECT on `finance.*`, read-only sessions by default, 5 s statement timeout) and
  `eil_audit_writer` (INSERT on `audit.tool_calls` only). Neither can read the other's tables, and
  the server never receives admin credentials ([ADR 0002](docs/adr/0002-separate-reader-and-audit-roles.md)).
- **Every call is audited**, including refusals and failures: arguments, outcome, row count,
  SHA-256 of the exact result returned, and duration. If the audit write fails, the tool
  returns an error instead of data (fail closed).
- **No internals leak.** Database errors reach the client only as "internal error, audit call_id …".
- **Private data stays out.** `.gitignore` rules, a test that fails if data-like files or
  secrets are tracked, and gitleaks in CI ([security and governance](docs/security-and-governance.md)).

## Quickstart (macOS with Colima or Docker Desktop)

```bash
cp .env.example .env      # set your own local passwords
uv sync
make up                   # PostgreSQL 16 (pgvector image) on 127.0.0.1:5442
make bootstrap            # schema, least-privilege roles, 659 synthetic expenses
make demo                 # real MCP client -> stdio -> server -> PostgreSQL
make audit                # see what was recorded
echo "ANTHROPIC_API_KEY=..." >> .env   # Milestone 02 (or `ant auth login`)
make ask Q="What was our total spending in 2025?"
```

Sample output from a real run: [docs/demo/milestone-01-demo-output.txt](docs/demo/milestone-01-demo-output.txt).

### Use it from Claude Desktop or Claude Code (Milestone 02 will verify this)

The server speaks standard MCP over stdio, so any MCP host can launch it. For example, in
`claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "eil-finance": {
      "command": "uv",
      "args": ["--directory", "/path/to/enterprise-intelligence-lab", "run", "eil-mcp"],
      "env": {
        "EIL_READER_DSN": "postgresql://eil_reader:<password>@localhost:5442/eil",
        "EIL_AUDIT_DSN": "postgresql://eil_audit_writer:<password>@localhost:5442/eil"
      }
    }
  }
}
```

## Tests

```bash
make test        # 114 tests: needs PostgreSQL (EIL_TEST_ADMIN_DSN, created by `make up`); no API key, no cost
make test-unit   # without a database: 57 run, 57 database tests skip
make test-live   # 8 live Claude acceptance scenarios: needs an Anthropic credential, costs money
make lint        # ruff, including bandit security rules
```

| Suite | Proves |
| --- | --- |
| `test_metrics_fixture.py` | Every metric matches values worked out by hand from 10 known rows (`tests/fixture_data.py`) |
| `test_synthetic.py` | The generator is deterministic and plausible; SQL totals equal an independent Python sum |
| `test_validation.py` | Bad dates, ranges, limits, amounts and unknown fields are rejected before SQL |
| `test_privileges.py` | PostgreSQL itself refuses writes by the reader, and reads, updates and deletes by the audit role |
| `test_audit.py` | Successful, refused and failed calls are all recorded; audit failure fails closed |
| `test_mcp_e2e.py` | A real MCP client lists the 4 tools, calls each over stdio, and gets refusals for bad input |
| `test_repo_hygiene.py` | No private-data file types or secrets are tracked |
| `test_agent_scenarios.py` | The 8 M02 acceptance scenarios through the real loop, MCP client, server and database, with a scripted model |
| `test_grounding_regressions.py` | The two live-run false positives (receipt references, account name, query threshold) stay fixed, and invented figures are still caught |
| `test_redaction.py` | Passwords and API keys are removed from test output, reports and traces |
| `test_agent_units.py` | Grounding check, MCP→Anthropic tool translation, unknown-tool refusal, budgets, refusals, API errors |
| `test_claude_request_shape.py` | The exact Messages API request and response handling (mock transport, no network) |
| `tests/live/` | The same 8 scenarios with real Claude (`make test-live`), figures checked against independent Python |

Each test database is created fresh and dropped afterwards. CI runs the full suite against a
PostgreSQL 16 service container.

## Status

| Capability | State |
| --- | --- |
| Synthetic dataset, schema, least-privilege roles | Implemented, locally tested |
| 4 MCP tools with validation, structured output, audit | Implemented, locally tested |
| Demonstration through a real MCP client (stdio) | Demonstrated locally (see demo output) |
| CI on GitHub Actions (PostgreSQL service, pip-audit, gitleaks) | Passing (scripted suite; live suite runs locally only) |
| Claude native tool calling through a real MCP client, budgets, grounding check, audit correlation | Implemented, locally tested with a scripted model (114 tests) |
| Live Claude acceptance scenarios (8) | **Validated locally with live Claude, 8/8** (2026-11-30, run 2). Run 1: 6/8, two grounding false positives, fixed in PR #3. Not run in CI (costs money, needs a key) |
| Follow-up questions (multi-turn), pgvector document retrieval, UI | Planned |
| Private Minima Scientific records | Planned; will be imported outside this repository |

Roadmap: [docs/roadmap.md](docs/roadmap.md). Engineering journal: [docs/journal/engineering-journal.md](docs/journal/engineering-journal.md).

## Project layout

```
src/eil/
  server.py          MCP server: tool definitions and the validate -> run -> audit runner
  finance/models.py  tool input and output contracts (Pydantic)
  finance/metrics.py deterministic SQL metrics
  audit.py           insert-only audit logger
  synthetic.py       seeded synthetic data generator
  db/                schema.sql and bootstrap (roles, grants, data load)
  demo_client.py     MCP client demonstration
  agent/             M02: loop (budgets, grounding, sources), MCP bridge, Claude client, prompts, CLI
tests/               unit, database, privilege, audit and end-to-end tests
docs/                architecture, ADRs, metrics, acceptance tests, security, roadmap, journal
```

## License

MIT

TDQS

A3.9/5.0

Scored across 5 tools

Disambiguation4/5

Each tool has a distinct reporting focus: summary, category breakdown, trend, period comparison, and transaction search. There is some conceptual overlap because expense_summary and compare_periods both return totals, and spending_trend also reports changes, but the descriptions make the boundaries reasonably clear.

Naming Consistency4/5

All names use consistent snake_case, which is good. However, the set mixes noun-phrase names like expense_summary/category_breakdown/spending_trend with verb-phrase names like compare_periods/search_transactions, so the pattern is not perfectly uniform.

Tool Count5/5

Five tools is well-scoped for an expense reporting/analytics server. Each tool covers a distinct analysis need without obvious redundancy or bloat.

Completeness5/5

The surface covers aggregate summaries, category breakdowns, temporal trends, period comparisons, and individual transaction search. For a read-only expense analytics server, this is a complete lifecycle of likely reporting queries with no obvious dead ends.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues