Metadata-Version: 2.4
Name: erdos-renyi
Version: 0.2.0
Summary: MCP connector: run Erdos queries on Reyni-registered EHR exports.
Author-email: Krv Labs <team@krv.ai>
License: Apache-2.0
Requires-Python: <3.15,>=3.11
Description-Content-Type: text/markdown
Requires-Dist: fastmcp<5,>=4.0.4
Requires-Dist: polars>=1.0.0
Requires-Dist: sqlglot>=23.0.0
Requires-Dist: pyarrow>=15.0.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=8.3; extra == "dev"
Requires-Dist: ruff>=0.9; extra == "dev"

# erdos-renyi

`erdos-renyi` is a FastMCP 4 server connecting Erdos queries to Reyni-registered cohort exports. Agents inspect schema metadata and approved categorical vocabulary, then stage results locally in Arrow IPC for clinician review. MCP never returns patient rows. Counts and vocabulary require support from enough distinct patients; these suppression rules are not a general anonymization guarantee against arbitrary repeated queries.

## Quickstart

```bash
# Install dependencies
uv sync --extra dev

# Run test suite
uv run pytest

# Run the MCP server over stdio
uv run er-mcp
```

## Reyni Gateway Setup

Add `erdos-renyi` to `~/Library/Application Support/reyni/servers.toml` (Windows: `%APPDATA%\reyni\servers.toml`):

```toml
[[server]]
name       = "erdos"
launch     = ["uv", "tool", "run", "--python", "3.12", "--from", "erdos-renyi", "er-mcp"]
phi_access = true
```

During local development, point `--from` to the local repository path:

```toml
[[server]]
name       = "erdos"
launch     = ["uv", "tool", "run", "--python", "3.12", "--from", "/path/to/erdos-renyi", "er-mcp"]
phi_access = true
```

Agent-visible Erdos tools: `erdos__get_schema`, `erdos__stage_query`, `erdos__stage_dashboard_config`, and `erdos__get_dashboard_config_help`. The help tool provides schema/example access through gateways that only forward tools. After staging, call the gateway's `register_dashboard`. The gateway must hide and restrict `launch_dashboard`; a direct connection to this server exposes it. Registered-path authorization is also the gateway's responsibility.

## Operator privacy settings

Configure the following in the server's launch environment, after verifying the export's schema:

```sh
ERDOS_RENYI_ENTITY_ID_COLUMN=patient_id
ERDOS_RENYI_CATEGORICAL_COLUMNS='["sex", "icd10"]'
```

The identity must be a stable patient identifier, not an encounter/row ID. Categorical approval must exclude identifying and free-text fields, including fields with arbitrary names; a name-based denylist is only an additional safeguard. These settings cannot be changed by tool arguments. Defaults disclose no vocabulary and suppress patient-dependent counts. Missing/null identities do not contribute to support. Values longer than 64 characters are withheld rather than shortened into incorrect filter literals.

Query counts require an unchanged trusted identity in a direct `SELECT ... FROM cohort`. CTEs, joins, aggregates, absent/replaced identity projections, and other unproven transformations still stage for the clinician, but return `matched_records: "not_established"`. Fewer than k distinct patients returns `"below_threshold"`. Neither means zero. An exact `matched_records` is the staged row count, not the number of distinct patients or the total match count before LIMIT.

## Agent Workflow

1. **`reyni__list_datasets`**: Obtain the `safe_path` for the tokenized twin export.
2. **`erdos__get_schema(safe_path)`**: Inspect up to 50 columns per page; pass `next_offset` as `offset`, or select `columns`. Type names omit Enum categories and nested field contents. Approved vocabulary and null/redaction counts require ≥ k distinct supporting patients (k=5 default). `profile_status: "unavailable"` means profiling failed, not that values are absent.
3. **Rewrite SQL**: Adapt the Erdos predictive query to target the local schema. The table name in Polars SQL is always **`cohort`**.
4. **`erdos__stage_query(safe_path, sql)`**: Sanitize and execute one SELECT; use `TRY_CAST` for redacted numeric text. The receipt includes column names/types. Failures return `isError: true` with safe error types and repair hints, without raw parser/engine/input dumps. `truncated` is true only when the system row cap, not your LIMIT, cut the result; it is omitted with suppressed counts.
5. **`erdos__stage_dashboard_config(session_id, config)`**: Validate and atomically replace the session's declarative config. Get an example/schema through `get_dashboard_config_help` or the resources. Invalid operands, unknown keys, unsafe templates, oversized/deep configs return bounded field errors; correct them and retry the same session. At most 20 diagnostics are returned with an omitted count. Config success confirms staging, not clinical validity.
6. **`reyni__register_dashboard(session_id)`**: Reyni launches the static dashboard internally, reads a clinician-only sidecar (`session_{id}.launch.json`), and stores the URL encrypted — the agent receives only a `dashboard_ref`.

## Security Guarantees

- **Restricted data egress**: MCP returns schema metadata, explicitly approved vocabulary supported by distinct patients, and gated counts. Vocabulary is untrusted data, never instructions. Patient rows remain local. Errors do not include raw input values or engine/parser messages.
- **SQL Sanitization**: Enforces read-only `SELECT` queries, rejects external filesystem functions (`read_csv`, `eval`), and clamps `LIMIT` to 1000 rows.
- **Localhost Enclave**: Staging files use Arrow IPC written mode-`0600` into a mode-`0700` staging directory; dashboards bind to `127.0.0.1`. Launch URLs are written to mode-`0600` sidecars, not returned over MCP. Launched dashboard sessions expire automatically; unlaunched staging files need operator cleanup.
- **CSV exports are read through a private Parquet twin**: the first tool call on a CSV converts it once (full schema inference, so a late free-text cell cannot fail a query) into `staging_dir/cache/` as a mode-`0600` file keyed by the export's path, size and mtime. Later calls are column-pruned Parquet reads. The twin is deleted when the server process exits; nothing persists across restarts.
- **Execution budget**: `ERDOS_RENYI_QUERY_TIMEOUT` (default 30 seconds) bounds the query wait, not CPU execution. A timed-out daemon worker may continue; it retains the single admission slot, and retries receive `ResourceBusy` until it exits. No session is staged on timeout. Structural guards reject cross joins, multiple joins per SELECT, and direct/subquery self-joins. Hard cancellation would require process isolation.

## Real agent dogfood

```sh
.venv/bin/python scripts/mcp_agent_e2e.py --scenario all --output-dir /private/tmp/erdos-mcp-e2e
```

Requires an authenticated Codex CLI and access to `gpt-5.6-terra`; no model substitution is made. The runner creates isolated synthetic exports, uses only this server's tools/resources, and preapproves config writes only on the synthetic server. It saves prompts, CLI JSONL, diagnostics, and per-scenario reports. Checks use actual tool events plus independently inspected Arrow/config artifacts: happy path, missing-column repair, invalid-config repair, and policy refusal. This does not validate a deployed Reyni gateway or establish statistical agent reliability.
