Skip to main content
Glama
README.md
# econ-r-mcp

`econ-r-mcp` is a local MCP server plus companion skill for reproducible applied econometrics and statistics workflows powered by headless R execution.

The core rule is that an LLM must not fabricate empirical output. Coefficients, standard errors, p-values, diagnostics, tables, plots, model comparisons, and report text should be grounded in executed R code and saved artifacts.

## What It Provides

- A Python FastMCP server named `econ-r-mcp`.
- Narrow, auditable MCP tools for R and Quarto workflows.
- Workspace-restricted file access with path traversal protection.
- Per-run artifact folders containing scripts, logs, session info, package versions, result JSON, tables, plots, and reports.
- Curated local econometrics guidance lookup for method tags such as `iv`, `did`, `rd`, `panel_fe`, `synthetic_control`, `time_series`, and `forecasting`.
- First-class lookup for the locally installed AER package's Applied Econometrics with R companion materials, including package vignette/errata files, chapter demo scripts, datasets, and help/index materials.
- A companion skill at `skills/econ-r/SKILL.md` that guides agents through research design, diagnostics, robustness, and artifact-backed interpretation.

## Prerequisites

- Python 3.11 or newer.
- R with `Rscript` available on `PATH`.
- Optional: Quarto for `.qmd` report rendering.
- Optional R packages, installed as needed from the allowlist:
  `fixest`, `modelsummary`, `broom`, `marginaleffects`, `did`, `rdrobust`, `Synth`, `gsynth`, `plm`, `AER`, `sandwich`, `lmtest`, `clubSandwich`, `estimatr`, `MatchIt`, `cobalt`, `WeightIt`, `vars`, `forecast`, `fable`, `tsibble`, `urca`, `tseries`, `strucchange`, `ggplot2`, `patchwork`, `gt`, `kableExtra`, `haven`, `readxl`, `arrow`, `DBI`, and `RPostgres`.

`jsonlite` is a core runtime dependency for structured result JSON.

For textbook-grounded guidance, install `AER`. The server does not bundle or scrape an external textbook; it inspects the local R package installation and returns only source paths/materials that are actually present on disk.

## Installation

From this repository:

```bash
uv sync --extra dev
uv run econ-r-mcp
```

Or install into an environment:

```bash
python -m pip install .
econ-r-mcp
```

Run a local health check through Python:

```bash
uv run python - <<'PY'
from econ_r_mcp.tools import health_check_impl
print(health_check_impl())
PY
```

## Configuration

The server scopes file operations to configured workspace roots.

Use environment variables:

```bash
export ECON_R_MCP_ALLOWED_ROOTS="/absolute/path/to/my/project"
export ECON_R_MCP_CONFIG="/absolute/path/to/econ-r-mcp/config/econ-r-mcp.toml"
```

Or edit `config/econ-r-mcp.toml`.

Important settings:

- `allowed_workspace_roots`: absolute roots the tools can read/write.
- `allowlisted_r_packages`: packages `install_r_packages` may install.
- `allowed_env_vars`: environment variables the caller may pass into R.
- `guidance_roots`: optional local curated Markdown guidance directories.
- `default_timeout_seconds` and `max_output_bytes`: execution and response caps.

## Connecting MCP Clients

### Claude Desktop-style JSON

```json
{
  "mcpServers": {
    "econ-r-mcp": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/econ-r-mcp",
        "run",
        "econ-r-mcp"
      ],
      "env": {
        "ECON_R_MCP_ALLOWED_ROOTS": "/absolute/path/to/your/econ-project"
      }
    }
  }
}
```

### Codex or Other Local MCP Clients

Use stdio transport and run:

```bash
uv --directory /absolute/path/to/econ-r-mcp run econ-r-mcp
```

Set `ECON_R_MCP_ALLOWED_ROOTS` to the empirical project directory before launching the client.

## Tool List

- `health_check`: checks R, Rscript, Quarto, and R package availability.
- `init_project`: creates `data/`, `scripts/`, `reports/`, `outputs/tables/`, `outputs/plots/`, `outputs/models/`, and `logs/`; optionally initializes `renv`.
- `install_r_packages`: installs only allowlisted R packages and returns structured results.
- `run_r_script`: runs a project `.R` script under the artifact harness.
- `render_quarto`: renders `.qmd` reports to HTML, PDF, or DOCX when Quarto supports it.
- `inspect_dataset`: inspects CSV, TSV, RDS, Parquet, or Stata files.
- `run_regression_fixest`: runs `fixest::feols` or `fixest::feglm`.
- `run_iv`: runs IV regression with fixest syntax and first-stage output.
- `run_did`: supports TWFE event studies and Callaway-Sant'Anna through `did`.
- `run_rdrobust`: runs `rdrobust`, RD plots, and density tests where available.
- `run_panel_diagnostics`: checks panel balance, duplicate keys, missing periods, and treatment timing.
- `run_time_series_diagnostics`: creates plots, ACF/PACF, unit-root checks, and structural-break checks where packages are available.
- `create_modelsummary`: creates publication-style tables from saved model objects or result JSON.
- `read_artifact`: reads saved logs, JSON, tables, Markdown, HTML, or TeX without executing code.
- `list_artifacts`: lists run outputs with pagination.
- `reproduce_run`: reruns a previous saved script and compares result JSON hashes.
- `lookup_econometrics_guidance`: returns concise, cited local guidance for econometric methods. Use `method="aer_textbook"` to inspect the locally installed AER package's Applied Econometrics with R companion materials.

## Local AER Guidance

`lookup_econometrics_guidance` prefers deterministic method files for tags such as `iv`, `did`, and `rd`. When `AER` is installed, tagged responses also include an `aer_reference` block with local AER package source paths where relevant.

Use this explicit lookup for AER grounding:

```json
{
  "method": "aer_textbook",
  "query": null,
  "corpus_root": null
}
```

The response distinguishes retrieved textbook/package guidance from executed empirical results. It should not be used to invent coefficients, diagnostics, plots, or sample facts.

## Artifact Layout

Each R or Quarto run writes to:

```text
outputs/models/<tool>-<timestamp>-<id>/
  input_script.R
  executed_script.R
  stdout.log
  stderr.log
  combined.log
  session_info.txt
  package_versions.csv
  result.json
  run_metadata.json
  tables/
  plots/
  reports/
```

## Security Model

- No arbitrary shell execution tool is exposed.
- R and Quarto are invoked with argv lists, not shell strings.
- File paths are resolved and checked against allowed workspace roots.
- Project paths cannot escape the project root.
- User-provided R scripts are copied before execution.
- Generated R code is saved before execution.
- Dangerous R operations such as `system()`, `system2()`, `unlink()`, `download.file()`, and common network/process packages are blocked by default.
- Environment variables supplied to R must be explicitly allowlisted.
- Tool responses summarize logs and link artifacts; full logs stay in the artifact folder.

R itself is a powerful language, so run this server only for trusted projects and review user-supplied scripts before setting `allow_dangerous_code=true`.

## Example Workflows

### Fixed Effects Regression

User request:

> Inspect this dataset, suggest an empirical strategy, run a fixed-effects model with clustered SEs, produce a modelsummary table, and render a Quarto report.

Tool sequence:

1. `init_project`
2. `inspect_dataset(data_path="data/fe_panel.csv", id_columns=["unit"], time_column="year")`
3. `run_panel_diagnostics(data_path="data/fe_panel.csv", unit="unit", time="year")`
4. `run_regression_fixest(data_path="data/fe_panel.csv", formula="y ~ x", fixed_effects=["unit", "year"], cluster_vars=["unit"])`
5. `create_modelsummary(model_paths=["outputs/models/<run>/model.rds"], notes=["SE clustered by unit", "Unit and year FE included"])`
6. `render_quarto(qmd_path="reports/example_report.qmd", output_format="html")`

### DiD Event Study

Use `run_did` with `method="twfe_event_study"` after `inspect_dataset` and `run_panel_diagnostics`.

Required interpretation items:

- ATT/event-study estimand.
- Treatment timing summary.
- Treated/control counts.
- Pre-trend plot if produced.
- Warning about staggered TWFE bias.
- Artifact paths for result JSON and event-study plot.

### IV Regression

Use `run_iv` with explicit `outcome`, `endogenous`, `instruments`, controls, fixed effects, and cluster variables.

Required interpretation items:

- First-stage table.
- Weak-instrument diagnostics where available.
- Robust or clustered SE choice.
- Exclusion restriction stated as an assumption.
- Overidentification tests where applicable.

### Regression Discontinuity

Use `run_rdrobust` with outcome, running variable, cutoff, covariates if justified, kernel, and polynomial order.

Required interpretation items:

- Cutoff, bandwidths, kernel, and order.
- Conventional and robust estimates.
- RD plot.
- Density/manipulation check if available.
- Local nature of the estimand.

### Quarto Report Generation

Place `.qmd` files in `reports/`, then call:

```json
{
  "project_root": "/absolute/path/to/project",
  "qmd_path": "reports/example_report.qmd",
  "output_format": "html"
}
```

The rendered files are saved under the run artifact `reports/` folder.

## Companion Skill

The skill lives at:

```text
skills/econ-r/SKILL.md
```

Install or reference it in clients that support local skills. It instructs the agent to behave like a careful applied econometrician and to use this MCP server for artifact-grounded empirical output.

## Tests

Run unit tests:

```bash
uv run --extra dev pytest -m "not integration"
```

Run integration tests that execute optional R packages:

```bash
uv run --extra dev pytest -m integration
```

Integration tests skip with clear messages when optional R packages are not installed.

## Limitations

- Static blocking of dangerous R code is a guardrail, not a sandbox.
- Some diagnostics depend on optional R packages.
- The server does not decide whether a design is causally credible; it forces the agent to state assumptions and verify artifacts.
- Semantic retrieval is intentionally lightweight and local-only; deterministic method tags are preferred.
- Quarto PDF rendering depends on the local Quarto and LaTeX setup.

## Publication Status

Public GitHub repository: <https://github.com/emmanueltsallis/econ-r-mcp>

Review generated artifacts and local-only files before publishing release builds.

TDQS

B3.4/5.0

Scored across 17 tools

Disambiguation5/5

Each tool targets a specific econometric method or workflow step, with no overlapping purposes. The run_* tools are clearly differentiated by method (DiD, IV, panel diagnostics, RD, fixest regression, time series diagnostics, generic R script), and all other tools serve distinct roles like project setup, data inspection, artifact management, and reporting.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern using snake_case. Verbs like create, init, inspect, install, list, lookup, read, render, reproduce, and run are appropriately paired with nouns. Even 'health_check' can be seen as a noun phrase but functions as a verb, and the pattern is uniform across the set.

Tool Count5/5

Seventeen tools is well-suited for an econometrics-focused MCP server. The count covers essential workflow stages—project setup, data inspection, package management, multiple econometric methods, diagnostics, model summary, artifact handling, reproducibility, and reporting—without being excessive or sparse.

Completeness4/5

The tool surface covers a broad range of econometric methods (DiD, IV, RD, panel diagnostics, time series diagnostics, fixest regression) and supporting tasks. Minor gaps exist, such as no dedicated tool for basic OLS regression (though fixest can handle it) or data transformation, but overall the set is comprehensive for its stated domain.

Maintenance

ActivityInactive
ResponsivenessNo issues