# stata-code [Health: Active]

**Category:** 🧮 Data Science Tools  
**Repository:** https://github.com/brycewang-stanford/stata-code  
**GitHub Stars:** 56  
**Views:** 0  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/stata-code

## Description
Agent-native Stata bridge for empirical research — run DiD/IV/RDD and publication-ready tables from Claude Code, Jupyter, or VS Code on one token-economy result schema, with StatsPAI cross-validation. | 面向实证研究的智能体 Stata 桥接器——在 Claude Code、Jupyter、VS Code 中用一套省 token 的结果格式跑 DiD/IV/RDD 与出版级表格，并支持 StatsPAI 跨栈交叉验证。

## Tools
Capabilities this server exposes over MCP:

- **stata_run** — Execute Stata code and return a v1.0 stata_code RunResult (see SCHEMA.md). The result is a JSON object with ok, rc, error (typed), log (head+tail+ref by default), results.r/e (scalars/macros/matrices, native types), dataset metadata, graphs, warnings, and capabilities. Use the structured fields rather than parsing the log. On ok=false, surface error.kind/message/line/suggestions. Use suggestions for iterative debug/fix loops only when the user asked for that or approved changes; for run/validate-only requests, report diagnostics without rewriting source code. ok=true only means Stata did not stop: check warnings for kind='suppressed_error' (a failure hidden by capture), and pass expect={...} to have the sample size, key coefficients and output files graded (a mismatch returns ok=false, error.kind='expectation_failed', with every check under result.checks).
- **stata_run_status** — Poll a background run submitted with stata_run(run_in_background=true). While it is still going the response is just the job summary; once finished it carries the full RunResult under `result` (or `error` if the job itself failed to start). Pass wait_ms to block up to that long for completion instead of returning immediately — that is cheaper than a tight poll loop. A job that is still running reports log_tail (the last lines Stata has printed), log_lines_total and current_command, so you can tell a slow bootstrap from a stuck one without waiting for it to end.
- **list_background_runs** — List background runs tracked by this server, newest first, with their status and elapsed time. Result payloads are not included — fetch one with stata_run_status.
- **stata_info** — Report installed Stata edition, version, backend, and whether the runtime is initialized.
- **get_log** — Fetch the log text behind a log:// ref returned by a prior stata_run call. Returns JSON {text, lines_total, bytes_total}. Pass start_line and/or max_lines to read part of a long log (the response then adds start_line, lines_returned and truncated); search_log finds the lines worth reading.
- **get_graph** — Fetch graph bytes behind a graph:// ref. Returns an ImageContent (base64 bytes + mimeType) suitable for direct display by vision-capable clients.
- **get_matrix** — Fetch a matrix's values, rows, and cols behind a matrix:// ref. Producers emit a ref instead of inlining values when the matrix exceeds ~10,000 cells. Returns JSON {rows, cols, values}.
- **list_sessions** — Enumerate live sessions. Each entry has session_id, frame (Stata frame name), and n_obs.
- **cancel_session** — Request cancellation for this subprocess-backed session. If a run is in flight, the worker process is terminated; otherwise the flag is consumed by the next call and returns a RunResult with ok=false, rc=-3, error.kind='cancelled'. Returns JSON {session_id, was_pending, is_pending, killed_worker}.
- **reset_session** — Drop a session's data. session_id='main' performs `clear all` in place (default frame cannot be dropped); other names drop the corresponding Stata frame.
- **notebook_outline** — Read a .ipynb file and return a compact per-cell index: cell_id (nbformat 4.5+ UUID, or a synthesized fallback for older notebooks), index, cell_type, source preview, line/char counts, execution_count, and whether outputs/error outputs are present. Read-only; does not execute or modify the notebook. Use this before notebook_get_cell to avoid pulling the full notebook into context.
- **notebook_get_cell** — Read one cell of a .ipynb by cell_id (preferred) or cell_index. Returns the cell's full source plus a token-economic outputs summary (count, types, whether an image is present, head/tail of stream/text outputs, error ename/evalue with truncated traceback). Read-only; does not execute or modify the notebook.
- **notebook_locate** — Find cells in a .ipynb by content. Pass exactly one of snippet (literal substring with whitespace-tolerant fall-back), regex (Python regex, multiline), or error_text (pasted Stata/traceback text — the longest code-like line is used as a fingerprint). Returns up to `limit` candidates ranked by match score, each with cell_id, line_in_cell, and a short preview. Read-only.
- **notebook_edit_cell** — Atomically replace one cell's source. Preserves cell.id and metadata. For code cells, clears outputs and execution_count. Optionally pass expected_source for optimistic-concurrency: the call fails with 'edit_source_drift' if the on-disk source no longer matches. Writes the whole notebook via temp file + rename. Note: if the cell was addressed by a synthesised id (pre-nbformat-4.5 notebook), the cell is upgraded to a real UUID during this call. The old synth id is no longer valid — use the cell_id returned in this result for follow-up calls.
- **notebook_insert_cell** — Insert a new cell with a fresh nbformat 4.5+ UUID. Pass exactly one anchor: after_cell_id, before_cell_id, at_start, or at_end. Default cell_type is 'code'.
- **notebook_delete_cell** — Remove a cell by id. Returns the deleted cell's source so the caller can announce or undo. Optionally pass expected_source for optimistic-concurrency.
- **list_runs** — Query the on-disk run-bundle manifests under a log-files directory. Pass either log_dir directly or origin_path (then the dir is inferred as <origin_path parent>/log-files). Filters compose with AND: cell_id, session_id, ok, since (ISO 8601 UTC, lexicographic compare on started_at), limit, and offset. Read-only; never re-runs anything. Returns compact summaries newest-first; callers fetch the full manifest from the returned manifest_path if needed.
- **install_package** — Install a community-contributed Stata package (e.g. reghdfe, coefplot, estout, ftools) without the agent having to remember `ssc install` / `net install` syntax. Runs the install in the named session, then verifies the package resolves with `which`. Returns a compact JSON summary: {name, source, command, ok, verified, rc, stata, log, error}. On failure the typed error block (kind: network / permission / file_not_found / ...) is surfaced so the agent can react. Idempotent by default (replace).
- **search_log** — Grep within a `log://` payload returned by a truncated stata_run (log.ref). Returns only the matching lines (with optional surrounding context) instead of pulling the whole log back via get_log — the token-economy way to inspect a long log. Substring match by default; set is_regex=true for a Python regular expression. When is_regex is omitted and the literal text matches nothing, a pattern written as a regex (alternation, character classes, anchors) is retried as one; the response's is_regex and note say so.
- **inspect_data** — One-call 'what is in this dataset' for the in-memory data of a session. Runs `describe` + `codebook` (compact unless detail=true) and returns the structured dataset block (frame, n_obs, n_vars, variables) plus the codebook log so the agent does not have to remember the command. Branch on the structured `dataset` field; the `log` is human-oriented detail (head + ref). Read-only: it never modifies data.
- **lint_do** — Static, Stata-free check of do-file source BEFORE spending a run to discover a structural mistake. Catches unbalanced braces, a `program` / `mata` / `python` block with no `end`, a stray `end`, and a dangling `///` continuation. Pass `code` (inline source) or `path` (a .do file to read). Returns {ok, counts:{error,warning}, findings:[{rule,severity,line,message}]}, where ok=true means no error-severity findings. Advisory and conservative — a clean result is not a guarantee the code runs, and it never executes anything.
- **set_variable_labels** — Stata-free: write variable labels straight into a .dta file on disk, the on-disk equivalent of `label variable x "..."` + `save, replace`. Pass `path` and `labels` ({variable name: label}; "" removes a label). Only the label fields are overwritten, so the data, value labels, notes, formats and characteristics are byte-for-byte unchanged and no Stata session or license is used. Omit `labels` to just read the current names and labels (e.g. to find unlabeled variables before proposing labels). All edits are validated first; if any is invalid nothing is written. Limits: 80 characters per label; files in formats older than 118 (Stata 13 or earlier) take ASCII labels only. Returns {ok, path, release, changed:[{name, before, after}], unchanged:[...]}; `before` is what to pass back to undo. Use `dry_run` to validate without writing. This edits the file, not a dataset already loaded in a session: run `use` again to see the new labels there.
- **set_value_labels** — Stata-free: read or edit the value labels, the dataset label and the value label attached to each variable of a .dta file on disk, the on-disk equivalent of `label define`, `label values`, `label drop` and `label data` + `save, replace`. Pass only `path` to read: the result lists every variable (type, label, attached value label, notes), every value-label set, the dataset label and the dataset notes. To edit, pass any of: `value_labels` ({name: {code: text}} defines that set, replacing the whole set if it exists; {name: null} drops it and detaches it from the variables that used it; a code is an integer or ".a"-".z"), `attach` ({variable: name}; "" detaches; the name must exist once this call's `value_labels` are applied; string variables are refused), `data_label` ("" removes it). The observations are never re-encoded: attachments are overwritten in place; a change to a set or to the dataset label writes a new copy of the file beside it and swaps it in atomically. All edits are validated first; if any is invalid nothing is written. Limits: 32,000 bytes per label text, 80 characters for the dataset label; files older than format 118 (Stata 13 or earlier) take ASCII only. Returns {ok, path, release, changed: {value_labels: {name: defined|modified|dropped}, attached: [{name, before, after}], data_label}, rewritten}. Use `dry_run` to validate without writing. This edits the file, not a dataset already loaded in a session: run `use` again to see the change there. For variable labels use `set_variable_labels`.

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `uvx` (confidence: high):

```json
"mcpServers": {
  "stata-code": {
    "command": "uvx",
    "args": ["--from","stata-code[mcp]","stata-code-mcp"]
  }
}
```

## Documentation

## What stata-code does

stata-code provides an agent-facing bridge to locally installed Stata. The same Python core supports an MCP server, a Jupyter kernel, a VS Code extension, and the `stata-code run` command-line interface. These entry points use a shared result format intended to reduce unnecessary output while preserving information agents need to interpret a run.

The project targets empirical economics workflows. Its included guidance and prompts cover difference-in-differences, instrumental variables and weak-instrument checks, regression discontinuity, table generation with `esttab`, and cross-package or cross-stack parity checks. StatsPAI can be used to re-estimate an ATT and compare results across implementations.

## How it works

The core can run through either of two Stata backends. Stata 17 and later can use the bundled `pystata` integration for in-memory sessions, while Stata 13 and later can use a console backend without `pystata`. Both backends return the same result schema. Stata frames support multiple sessions in the core.

For MCP use, an agent can call `stata_run` with Stata code or a do-file workflow. Failed runs return structured error information such as the error kind, source line, context, and suggested next steps. An agent may use those fields to repair and rerun a do-file only when the user explicitly requests that behavior; failure handling is diagnostic by default.

The repository also includes reusable prompts such as `did_event_study`, `iv_2sls`, `rdd`, `publication_table`, and `cross_validate_did`. These prompts draw on recipes in the packaged skill resources rather than requiring every workflow to be written from scratch.

## Setup and configuration

The package requires Python 3.10 or newer and a local Stata installation. Install the base package with:

```bash
pip install stata-code
```

Install the MCP and Jupyter extras when those frontends are needed:

```bash
pip install "stata-code[mcp,kernel]"
```

For a quick MCP setup with Claude Code, use `uvx`:

```bash
claude mcp add stata-code --scope user -- uvx --from "stata-code[mcp]" stata-code-mcp
```

The package looks for Stata's `pystata` files in standard installation locations. If Stata is installed elsewhere, add its `pystata` directory to `PYTHONPATH` before importing the package. The `stata-code doctor` command checks Python and package details, optional extras, Stata discovery, console commands, and common MCP client configuration locations. Use `--json` for machine-readable diagnostics.

To add the Jupyter frontend, install the kernel extra and register the kernel with `stata-code-kernel install --user`. The resulting Stata kernel can be selected in Jupyter Notebook, JupyterLab, and VS Code's Jupyter extension.

## Tools and capabilities

- Execute Stata code through the MCP server or CLI.
- Return compact, structured results with typed errors and native `r()` and `e()` values.
- Expose log and graph references instead of requiring agents to process all output inline.
- Run recipe-backed DiD, IV, RDD, publication-table, and cross-validation workflows.
- Use Stata 17+ with `pystata` or Stata 13+ through the console backend.
- Share the core across MCP, Jupyter, VS Code, and terminal frontends.

## Limitations and notes

Stata must be installed separately; `pystata` is distributed with Stata rather than through PyPI. The console backend is stateless, while the `pystata` backend supports in-memory sessions. Cross-validation with StatsPAI covers the Stata side of the workflow and relies on explicit handoffs to independent R, Python, or data MCP tools. Automatic repair and rerunning after an error is opt-in rather than the default behavior.

_Full upstream README: https://allmcps.com/mcp/stata-code/readme_

