Skip to main content
Glama
UCSFOMOPAgent

UCSFOMOPAgent

by BaranziniLab
README.md
# UCSFOMOPAgent

Current version: **0.4.1**. Small queries stay on MCP; long queries and full
exports run as monitored local jobs without tying up an MCP request.

## Install in BioRouter

1. Download **[ucsfomopagent.brxt](https://github.com/BaranziniLab/UCSFOMOPAgent/releases/latest/download/ucsfomopagent.brxt)**
   from [Releases](https://github.com/BaranziniLab/UCSFOMOPAgent/releases/latest).
   The same current bundle is committed under [extensions/](extensions/).
2. In BioRouter, open **Extensions → Add extension**, select the BRXT and install.
   BioRouter creates the Python environment; `uv` and Python 3.11+ are required.
3. Enter credentials in BioRouter's own configuration dialog, never in chat.
4. Enable the extension in your chat. Verify a small query before a larger export.

Terminal installation uses the same installer:

```bash
biorouter extension install ./extensions/ucsfomopagent.brxt
biorouter extension configure ucsfomopagent
```

Configure `CLINICAL_RECORDS_USERNAME` and `CLINICAL_RECORDS_PASSWORD`. Host defaults to the UCSF SQL Server; database defaults to `OMOP_DEID`. Optional `CLINICAL_RECORDS_SERVER` / `CLINICAL_RECORDS_DATABASE` overrides are declared in the manifest. UCSF network/VPN access and database read permission are required.

The Desktop installer discovers bundled `skills/*/SKILL.md`. If using a BioRouter
CLI version that does not copy bundled skills, the MCP server still provides the
job-routing instructions; the skill folders can also be installed separately.

## Long queries, CLI and progress

Use `omop-submit_query_job` for an export or a query that could exceed the
interactive timeout. Call `omop-query_job_capacity` first; submission returns a
job ID immediately and atomically checks the two-job limit. Use
`omop-wait_for_query_job` for native waits of up to 30 seconds, or
`omop-query_job_status` for an immediate snapshot. Use `omop-cancel_query_job`
to stop. Only `completed` means the file is complete. Read bounded UTF-8 chunks
with `omop-read_query_job_result` using the job ID and `next_offset`; do not pass
`result_path` to generic filesystem tools. The secure reader requires POSIX;
unsupported platforms retain the local CLI file. See [job boundaries and the
credential-free app fixture](docs/QUERY_JOBS.md#mcp-waiting-capacity-and-result-handoff).
Status includes rows, bytes, elapsed time, phase and an advisory ETA when known.
Set `mode="explain"` to obtain a plan without running the query.

From a source checkout, or BioRouter's installed extension directory:

```bash
uv sync --locked
# Standalone CLI only: configure its OS-keyring profile interactively once.
# BioRouter MCP jobs already receive credentials and do not need this command.
uv run ucsfomopagent auth
uv run ucsfomopagent submit --query-file query.sql --format jsonl --timeout-seconds 3600
uv run ucsfomopagent watch JOB_ID
```

No-argument `uv run ucsfomopagent` continues to start the MCP server. `status`, `watch`,
`list`, `cancel` and `purge` need no database credentials. Results remain in the
local private job directory. The bounded result reader can return requested chunks
to chat; keep controlled data local and share only appropriate summaries. Database/server limits can
still fail a query; jobs report those failures instead of silently truncating.

### Large fact-table studies

Background jobs avoid MCP request timeouts, but expensive database plans can
still take too long. For large OMOP studies, freeze a minimal seed cohort or
candidate superset, then extract required facts in bounded, parameterized batches.
Replace repeated eligibility CTEs across large fact tables with staged extraction
that preserves the complete clinical definition.

Keep identifiers, parameter files, outputs and the batch manifest private and
local. Pilot batches, monitor at most two concurrent jobs, and reconcile all
required outputs before applying final eligibility rules or reporting completion.
A heartbeat is not query progress; zero streamed rows is not an empty cohort.
ETA is provisional, and separate connections do not provide a shared database
snapshot. The bundled phenotype and query-job skills describe the full workflow.

See [architecture, storage, security and release details](docs/QUERY_JOBS.md).
To rebuild the tracked bundle: `uv run python scripts/build_brxt.py`.


An MCP (Model Context Protocol) server for querying the **UCSF OMOP** de-identified
electronic health records database (OMOP CDM v5.4 on Microsoft SQL Server) for
fast, robust clinical data retrieval.

> **v0.2.0** is a major upgrade focused on getting the LLM to the *right* data
> *faster* and *more reliably*, while staying robust to database changes. See
> [`benchmark/CHANGELOG.md`](benchmark/CHANGELOG.md) for the full engineering log
> and [`benchmark/`](benchmark/) for the reproducible evaluation harness.


## Database-specific behavior

The server supplies T-SQL and OMOP conventions, cached live schema discovery,
concept resolution and a lab/vital finder. `find_measurement` now examines bounded
numeric samples per candidate and unit. These are nonrandom samples, not complete
coverage counts or population estimates. It returns a full profiling query for a
monitored job when exact statistics are needed. Never mix units without an
explicit conversion plan. Live schema takes precedence over historical counts.

Interactive queries use a serialized reusable connection, autocommit, a short
preview timeout, valid CSV quoting and result caps. Full exports use independent
job connections and do not inherit preview caps. Failed connections are discarded.

## Features

- **Query UCSF OMOP**: read-only T-SQL on the de-identified OMOP CDM.
- **Concept & lab resolution**: built-in vocabulary search and a lab finder so
  the model stops guessing concept_ids.
- **Schema introspection**: live, drift-resistant.
- **Pre-configured**: server/database baked in — just provide credentials.

## Installation

### From GitHub (using uvx)

```bash
uvx --from git+https://github.com/BaranziniLab/UCSFOMOPAgent ucsfomopagent
```


## Evaluation

`benchmark/` contains the reproducible evaluation used to drive these
improvements: a harness that drives the **real** MCP server (over stdio) with a
fixed neutral system prompt, a 100-question bench across four difficulty tiers,
and an LLM-judge grader. Absolute patient counts are redacted (this repo is
public); the methodology, relative improvements, and efficiency metrics
(iterations / tool calls / tokens / latency) are included. See
[`benchmark/README.md`](benchmark/README.md).

## Security

User SQL must parse as one read-only SELECT/WITH query, and unsafe operations
are rejected. Use a database account restricted to SELECT; validation supplements
server permissions. Credentials are provided via environment variables (stored in the OS
keyring by BioRouter) and are never logged or committed.

## Provenance and credits

Made by the Baranzini Lab (Wanjun Gu, UCSF).

Original work of the Baranzini Lab.

### Sources

| Source | Version or commit | Licence | Credit and people | Use and what |
| --- | --- | --- | --- | --- |
| [keyring](https://github.com/jaraco/keyring) | version 25.7.0 | MIT | Kang Zhang and Jason R. Coombs | installed as a dependency: Python dependency: the operating system keyring the standalone command line keeps its credential profile in |
| [FastMCP](https://github.com/PrefectHQ/fastmcp) | version 4.0.10 | Apache-2.0 | Prefect | installed as a dependency: Python dependency: the MCP server framework the extension runs on |
| [Pydantic](https://github.com/pydantic/pydantic) | version 2.13.5 | MIT | Pydantic Services Inc. and individual contributors | installed as a dependency: Python dependency: the schemas of the tools' arguments |
| [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) | version 2.2.0 | MIT | Anthropic, PBC | installed as a dependency: Python dependency: the MCP types (mcp.types) the tools return and annotate; FastMCP installs it |
| [pymssql](https://github.com/pymssql/pymssql) | version 2.4.2 | LGPL-2.1-or-later | Joon-cheol Park, Damien Churchill and Mikhail Terekhov | installed as a dependency: Python dependency: the Microsoft SQL Server client the queries run through |
| [filelock](https://github.com/tox-dev/py-filelock) | version 3.32.7 | MIT | Bernát Gábor and contributors | installed as a dependency: Python dependency: the file locks of the query jobs |
| [sqlglot](https://github.com/tobymao/sqlglot) | version 28.10.1 | MIT | Toby Mao | installed as a dependency: Python dependency: the SQL parser the read-only query check uses |

### Data and services

| Data or service | Kind | Provider | Terms | How it is used | Citation |
| --- | --- | --- | --- | --- | --- |
| [UCSF OMOP_DEID (OMOP CDM v5.4 on Microsoft SQL Server, schema omop)](https://data.ucsf.edu/research/ucsf-data) | dataset | University of California, San Francisco (UCSF DEID OMOP) | Access is subject to UCSF Information Commons terms and authorization for the specific data and use (UCSF Clinical Data page, reviewed 2026-11-27) | read at run time |  |
| [OMOP standard vocabularies (the concept tables)](https://athena.ohdsi.org) | dataset | OHDSI (Observational Health Data Sciences and Informatics) | OHDSI Standardized Vocabularies content is Apache-2.0, except a few commercial source vocabularies (for example CPT4) that need EULA documentation or proof of a licence through Athena (HL7 Terminology page for OMOP, https://terminology.hl7.org/6.5.0/CodeSystem-OMOP.html, read 2026-11-27) | read at run time |  |

### Contributors

- Wanjun Gu, Baranzini Lab, UCSF: author
- Gianmarco Bellucci, Baranzini Lab, UCSF: author

The copyright lines and licences of the components above are in `NOTICE`.

Curated and organized by Wanjun Gu, Baranzini Lab, UCSF.

## License

Apache-2.0. See `LICENSE` and `NOTICE`.