mcp_quant_server
by rogerlzp
README.md
# mcp_quant_server
A **read-only MCP (Model Context Protocol) server** over a quant factor panel — letting an LLM agent query factor scores, price history, and data quality through typed tools instead of hand-written SQL.
Part of a two-repo set:
| Repo | Layer |
|---|---|
| [`panda_factor`](https://github.com/rogerlzp/panda_factor) | factor computation (pandas / NumPy) |
| [`dbt_quant_demo`](https://github.com/rogerlzp/dbt_quant_demo) | transformation layer (dbt → DuckDB) |
| **`mcp_quant_server`** | **agent access layer (MCP)** ← you are here |
The agent reads the same DuckDB file that dbt built. That is the point: **dbt owns the data contract, MCP owns the agent's access to it, and neither has to know about the other.**
---
## Why this exists
In 2026, a data engineer is increasingly asked to make data reachable by agents. Doing that by handing an LLM a database connection is a bad idea: no permission boundary, no schema contract, no way to make the model check its own inputs.
This server is the disciplined version of that idea.
---
## The five harness decisions that matter
This repo is deliberately built to demonstrate the properties that 2026 senior roles ask for by name.
### 1. Permission boundary — every tool is read-only
`DataStore` opens DuckDB with `read_only=True`. There is no write tool, no delete tool, no "run arbitrary SQL" tool. The agent's blast radius is bounded by construction, not by policy text.
### 2. Tool descriptions are the API
Each tool's docstring tells the model **when to call it** and **what it returns**:
```python
def get_data_quality(store, limit=30):
"""取每日数据质量指标(因子覆盖率、缺失行数)。
Use this BEFORE trusting any analysis: if factor_coverage_ratio is below
the configured threshold, downstream results are not trustworthy and you
must say so in your answer.
"""
```
An agent does not read your code — it reads tool descriptions. Vague descriptions produce wrong tool calls; specific ones ("call this *before* concluding") change behaviour.
### 3. Errors return guidance, not stack traces
When a filter matches nothing, the tool returns `{"rows": [], "hint": "..."}` rather than raising. The agent can self-correct in the next turn instead of collapsing.
### 4. Data quality is a first-class tool
`get_data_quality` is a tool the agent is *told* to call before drawing conclusions. It returns a `warning` field when coverage drops below threshold.
This is the difference between **generating** and **verifying**. A model that can check its own inputs is a different product from one that cannot.
### 5. Structured output only
Every tool returns a dict with stable keys. No free-text blobs, no markdown tables — the model can parse these reliably.
---
## Tools
| Tool | Purpose |
|---|---|
| `list_symbols` | Which tickers exist in the dataset? |
| `get_trading_dates` | Which dates are valid arguments? |
| `get_latest_scores` | Latest composite factor scores + components + bucket |
| `get_price_history` | One symbol's price / MA / volatility / returns history |
| `get_data_quality` | Daily coverage and missing-row metrics — **call before concluding** |
| `compare_symbols` | Side-by-side comparison of specific tickers |
---
## Install & run
```bash
pip install mcp duckdb
git clone https://github.com/rogerlzp/mcp_quant_server.git
cd mcp_quant_server
# 1) 先用 dbt 建好数据(见 dbt_quant_demo)
# dbt build → 产生 quant_demo.duckdb
# 2) 起 server(stdio transport)
python mcp_server.py --db /path/to/quant_demo.duckdb
```
### Register with an MCP client
Claude Desktop / Claude Code `claude_desktop_config.json`:
```json
{
"mcpServers": {
"quant-research": {
"command": "python",
"args": ["/path/to/mcp_quant_server/mcp_server.py", "--db", "/path/to/quant_demo.duckdb"]
}
}
}
```
Then ask things like:
> "Which stocks have the best composite factor score in the latest session? Check data quality first."
---
## Layout
```
mcp_quant_server/
├── mcp_server.py # MCP server entry: registers tools, injects the store
├── quant_tools/
│ └── tools.py # tool implementations + docstrings (the real substance)
└── tests/
├── test_tools.py # contract tests: every tool returns the documented shape
└── test_e2e_mcp.py # end-to-end: real MCP client -> real server -> DuckDB
```
---
## The store-injection detail
FastMCP builds each tool's JSON schema from the function signature. If the store were a parameter, the model would be asked to *fill in a database connection* — which it cannot, and should not.
The fix is to inject the store **before** registration:
```python
for fn in TOOLS.values():
mcp.tool()(_with_store(fn, store))
```
and to explicitly set `__signature__` so `inspect.signature` reports the post-injection signature.
Two bugs this codebase actually hit, both now covered by tests:
1. **`functools.wraps` leaves `__wrapped__`**, so `inspect.signature` still saw the original `store` parameter — the model would have been asked to fill in a database connection.
2. **The wrapper was `async` but the tools are sync.** `return await fn(store, ...)` raised `object dict can't be used in 'await' expression` at runtime. The contract test caught it; a reader of the code would not.
Registering first and wrapping afterwards is the natural-looking mistake; it silently leaks `store` into the schema.
## SDK compatibility
MCP SDK **2.x renamed `FastMCP` → `MCPServer`** and changed the tool-registration API (`add_tool` vs `tool()`). The server detects and supports both, and the e2e test reads the schema under either key (`input_schema` / `inputSchema`).
---
## License
MIT — see [LICENSE](LICENSE).
---
## Verified
```
python tests/test_tools.py <duckdb> → 12/12 pass
python tests/test_e2e_mcp.py <duckdb> → all passed
```
The e2e test starts the server over stdio, completes the MCP handshake with a
real client, and asserts that the JSON schema exposed to the model does not
leak the internal store handle.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues