About Stata Code
Stata Code is an MCP server published by brycewang-stanford in the Blockchain category: 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 跨栈交叉验证。. Conduid read 23 tools from its source: cancel_session, get_graph, get_log, get_matrix, inspect_data, install_package and 17 more. It is published to PyPI as stata-code and runs with uvx.
The repository has 61 stars and 10 forks, and its last commit was on 25 Nov 2026. Conduid has no tagged release on record for it. Its topics include data-analysis, data-science, econometrics, jupyter, notebook and regression.
Install
uvx stata-codepip install stata-codegit clone https://github.com/brycewang-stanford/stata-codeTools (23)
cancel_sessionRequest 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}.| Parameter | Type | Description |
|---|---|---|
| session_id | string |
get_graphFetch graph bytes behind a graph:// ref. Returns an ImageContent (base64 bytes + mimeType) suitable for direct display by vision-capable clients.| Parameter | Type | Description |
|---|---|---|
| format | string | |
| ref * | string |
get_logFetch 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.| Parameter | Type | Description |
|---|---|---|
| max_lines | integer | Return at most this many lines. |
| ref * | string | |
| start_line | integer | First line to return, 1-based. Negative counts from the end: -40 is the last 40 lines. |
get_matrixFetch 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}.| Parameter | Type | Description |
|---|---|---|
| ref * | string |
inspect_dataOne-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.| Parameter | Type | Description |
|---|---|---|
| detail | boolean | False (default) runs `codebook, compact` (one row per variable). True runs the full `codebook`. |
| session_id | string | Session to inspect. Defaults to 'main'. |
| varlist | string | Optional space-separated variable list (or wildcard, e.g. 'pri*') to restrict the report. Omit to inspect all variables. |
install_packageInstall 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).| Parameter | Type | Description |
|---|---|---|
| name * | string | Package name, e.g. 'reghdfe'. For ssc this is the SSC package id; for net it is the package name within the `from()` repository. |
| replace | boolean | Pass the `replace` option so an existing install is overwritten (keeps the call idempotent). |
| session_id | string | Session to install into. Defaults to 'main'. |
| source | string | 'ssc' installs from the Boston College SSC archive. 'net' installs from an explicit `url` (required for net). |
| url | string | Repository URL for `net install <name>, from(<url>)`. Required when source='net', ignored for source='ssc'. |
lint_doStatic, 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.| Parameter | Type | Description |
|---|---|---|
| code | string | Inline Stata source to lint. Provide this or `path`. |
| path | string | Path to a .do file to read and lint. Ignored when `code` is given. |
list_background_runsList 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.list_runsQuery 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.| Parameter | Type | Description |
|---|---|---|
| cell_id | string | Filter by origin_cell_id recorded on the run. |
| limit | integer | |
| log_dir | string | Explicit log-files directory to scan. |
| offset | integer | |
| ok | boolean | |
| origin_path | string | Source path (.do or .ipynb). Used both to locate <dirname>/log-files (when log_dir is absent) and as a filter on source_path. |
| session_id | string | |
| since | string | ISO 8601 UTC string, e.g. '2026-05-08T01:00:00.000Z'. Date-only and seconds-only forms are accepted and normalized; the boundary is inclusive. |
list_sessionsEnumerate live sessions. Each entry has session_id, frame (Stata frame name), and n_obs.notebook_delete_cellRemove a cell by id. Returns the deleted cell's source so the caller can announce or undo. Optionally pass expected_source for optimistic-concurrency.| Parameter | Type | Description |
|---|---|---|
| cell_id * | string | |
| expected_source | string | |
| path * | string |
notebook_edit_cellAtomically 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.| Parameter | Type | Description |
|---|---|---|
| cell_id * | string | Cell to edit. If addressing a pre-4.5 cell by synthesised id, the cell is upgraded with a fresh nbformat 4.5+ UUID before saving. |
| expected_source | string | Optional concurrency guard. When provided, the current on-disk source must match exactly. |
| new_source * | string | Replacement source text. |
| path * | string |
notebook_get_cellRead 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.| Parameter | Type | Description |
|---|---|---|
| cell_id | string | Stable nbformat 4.5+ cell id, or a synthesized id from a prior notebook_outline call. |
| cell_index | integer | 0-based array index. Use only when the notebook lacks cell ids; cell_id is more stable. |
| path * | string | Absolute or workspace path to the .ipynb file. |
notebook_insert_cellInsert 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'.| Parameter | Type | Description |
|---|---|---|
| after_cell_id | string | |
| at_end | boolean | |
| at_start | boolean | |
| before_cell_id | string | |
| cell_type | string | |
| path * | string | |
| source * | string |
notebook_locateFind 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.| Parameter | Type | Description |
|---|---|---|
| cell_type | string | Optional filter by cell type. |
| error_text | string | Pasted error/traceback text. The longest code-like line is treated as a fingerprint and located in the notebook. |
| limit | integer | Maximum number of candidates to return. |
| path * | string | Absolute or workspace path to the .ipynb file. |
| regex | string | Python regex applied to the cell source (multiline mode). |
| snippet | string | Literal substring to match. Whitespace is normalised line-by-line as a fallback if the exact substring is not found. |
notebook_outlineRead 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.| Parameter | Type | Description |
|---|---|---|
| path * | string | Absolute or workspace path to the .ipynb file. |
| preview_lines | integer | Number of leading source lines to include per cell as a preview. Long lines are truncated. |
reset_sessionDrop a session's data. session_id='main' performs `clear all` in place (default frame cannot be dropped); other names drop the corresponding Stata frame.| Parameter | Type | Description |
|---|---|---|
| session_id | string |
search_logGrep 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.| Parameter | Type | Description |
|---|---|---|
| context | integer | Lines of context to include on each side of a match (capped at 10). |
| ignore_case | boolean | Case-insensitive match (default true). |
| is_regex | boolean | true: Python regular expression. false: literal substring. Omitted: substring, then regex if the substring matches nothing. |
| max_matches | integer | Stop after this many matches. |
| pattern * | string | Substring or regex to search for. |
| ref * | string | A 'log://<request_id>' ref from log.ref. |
set_value_labelsStata-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`.| Parameter | Type | Description |
|---|---|---|
| attach | object | Variable name → value-label name to attach; an empty string detaches. |
| data_label | string | New dataset label; an empty string removes it. |
| dry_run | boolean | Validate and report the changes without writing. |
| path * | string | Path to the .dta file to read or edit. |
| value_labels | object | Value-label name → {code: text} to define or replace that set, or null to drop it. |
set_variable_labelsStata-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.| Parameter | Type | Description |
|---|---|---|
| dry_run | boolean | Validate and report the changes without writing. |
| labels | object | Variable name → new label. An empty string removes the label. Omit to read the current labels. |
| path * | string | Path to the .dta file to edit. |
stata_infoReport installed Stata edition, version, backend, and whether the runtime is initialized.stata_runExecute 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).| Parameter | Type | Description |
|---|---|---|
| auto_close_logs | boolean | On a failed run, close log handles that this run opened, so a script that aborts between `log using` and `log close` does not fail every subsequent run with r(604). Handles opened by earlier runs are left alone. |
| code * | string | Stata code to execute. Multi-line OK. |
| expect | object | Acceptance checks graded after Stata succeeds. Any failure turns the result into ok=false, rc=-6, error.kind='expectation_failed'; every graded check is listed under result.checks. Use it to pin the specification you intend, so a changed sample, a moved coefficient or a missing table cannot pass as success. |
| graph_format | string | |
| include_dataset_variables | boolean | |
| include_estimation | string | How much of results.estimation to return. 'summary' keeps command/N/model_stats/diagnostics but drops per-term coefficient rows — useful for specifications dominated by i.year i.firm-style nuisance terms. |
| include_full_log | boolean | |
| include_graphs | string | |
| include_results | string | How much of results.r / results.e to inline. 'scalars' (default) keeps scalars and macros and turns every matrix into a matrix:// stub with its shape — an estimation is otherwise encoded four times over (e(b), e(V), e(beta), r(table)) when results.estimation already has the typed table. 'full' inlines matrix values up to ~10,000 cells; 'none' drops r()/e() entirely. Stubbed values stay retrievable with get_matrix(ref). |
| log_lines_head | integer | |
| log_lines_tail | integer | |
| max_coefficients | integer | Cap on coefficient rows in results.estimation. estimation.n_coefficients always reports the true count and coefficients_truncated flags the cut. |
| origin_cell_id | string | Stable nbformat 4.5+ cell id when the submitted code is one cell of a Jupyter notebook. The runner does not interpret this value — it is echoed in result.origin and recorded in the run-bundle manifest so notebook-aware agents can correlate runs with cells. |
| origin_kind | string | Which editor surface produced the submitted code. |
| origin_label | string | Human-readable source label, for example demo/test1.do:1. |
| origin_path | string | Absolute path of the source .do file. Used for the default Stata working directory, run-bundle placement, and metadata. |
| persist_generated_files | boolean | When log files are persisted, also copy newly created or modified output files from the run working directory into the run bundle's outputs/ folder, and save captured graphs into graphs/. |
| persist_log_files | boolean | When true and origin_path is provided, write immutable .log/.smcl artifacts under <origin dir>/log-files/<run>/. |
| run_in_background | boolean | Return immediately with a job_id instead of waiting. Poll stata_run_status(job_id) for the RunResult. Use for bootstraps, permutation tests and other multi-minute jobs. Give the job its own session_id if you want to keep running other code meanwhile — one Stata process serves one session. |
| session_id | string | Session name. 'main' is the master frame; other names create/route to a persistent session. Values must match [A-Za-z0-9_-]+; ids that are not legal Stata frame names are mapped internally (data isolation only; r()/e() remain global in the direct runner). |
| timeout_ms | any | Hard wall-clock timeout, enforced by killing the session's worker process. null disables it. The budget covers queueing too: a call waiting behind another run in the same session returns rc=-5 (error.kind='session_busy') rather than blocking indefinitely. |
| track_output_files | boolean | Report files the run created or modified in its working directory under result.outputs (esttab tables, exported graphs, saved .dta). Independent of persist_log_files. |
| use_origin_workdir | boolean | When origin_path is provided, cd Stata to the source .do file's directory before running. This makes relative table/graph exports land next to the .do file by default. |
| working_dir | string | Optional explicit Stata working directory. Overrides origin_path's directory. |
stata_run_statusPoll 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.| Parameter | Type | Description |
|---|---|---|
| job_id * | string | job_id returned by stata_run(run_in_background=true). |
| log_lines_tail | integer | Lines of the running job's transcript to return as log_tail. 0 omits it. |
| wait_ms | integer | Block up to this many milliseconds for the job to |
Security checks
6 checks have not been run yet.