1. Conduid
  2. Blockchain
  3. Stata Code
MCP server · Blockchain

Stata Code

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 跨栈交叉验证。

69Good

Scored 22 hours ago · breakdown

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
uvx stata-code
pip
pip install stata-code
From source
git clone https://github.com/brycewang-stanford/stata-code

Tools (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}.
ParameterTypeDescription
session_idstring
get_graphFetch graph bytes behind a graph:// ref. Returns an ImageContent (base64 bytes + mimeType) suitable for direct display by vision-capable clients.
ParameterTypeDescription
formatstring
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.
ParameterTypeDescription
max_linesintegerReturn at most this many lines.
ref *string
start_lineintegerFirst 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}.
ParameterTypeDescription
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.
ParameterTypeDescription
detailbooleanFalse (default) runs `codebook, compact` (one row per variable). True runs the full `codebook`.
session_idstringSession to inspect. Defaults to 'main'.
varliststringOptional 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).
ParameterTypeDescription
name *stringPackage name, e.g. 'reghdfe'. For ssc this is the SSC package id; for net it is the package name within the `from()` repository.
replacebooleanPass the `replace` option so an existing install is overwritten (keeps the call idempotent).
session_idstringSession to install into. Defaults to 'main'.
sourcestring'ssc' installs from the Boston College SSC archive. 'net' installs from an explicit `url` (required for net).
urlstringRepository 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.
ParameterTypeDescription
codestringInline Stata source to lint. Provide this or `path`.
pathstringPath 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.
ParameterTypeDescription
cell_idstringFilter by origin_cell_id recorded on the run.
limitinteger
log_dirstringExplicit log-files directory to scan.
offsetinteger
okboolean
origin_pathstringSource path (.do or .ipynb). Used both to locate <dirname>/log-files (when log_dir is absent) and as a filter on source_path.
session_idstring
sincestringISO 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.
ParameterTypeDescription
cell_id *string
expected_sourcestring
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.
ParameterTypeDescription
cell_id *stringCell 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_sourcestringOptional concurrency guard. When provided, the current on-disk source must match exactly.
new_source *stringReplacement 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.
ParameterTypeDescription
cell_idstringStable nbformat 4.5+ cell id, or a synthesized id from a prior notebook_outline call.
cell_indexinteger0-based array index. Use only when the notebook lacks cell ids; cell_id is more stable.
path *stringAbsolute 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'.
ParameterTypeDescription
after_cell_idstring
at_endboolean
at_startboolean
before_cell_idstring
cell_typestring
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.
ParameterTypeDescription
cell_typestringOptional filter by cell type.
error_textstringPasted error/traceback text. The longest code-like line is treated as a fingerprint and located in the notebook.
limitintegerMaximum number of candidates to return.
path *stringAbsolute or workspace path to the .ipynb file.
regexstringPython regex applied to the cell source (multiline mode).
snippetstringLiteral 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.
ParameterTypeDescription
path *stringAbsolute or workspace path to the .ipynb file.
preview_linesintegerNumber 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.
ParameterTypeDescription
session_idstring
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.
ParameterTypeDescription
contextintegerLines of context to include on each side of a match (capped at 10).
ignore_casebooleanCase-insensitive match (default true).
is_regexbooleantrue: Python regular expression. false: literal substring. Omitted: substring, then regex if the substring matches nothing.
max_matchesintegerStop after this many matches.
pattern *stringSubstring or regex to search for.
ref *stringA '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`.
ParameterTypeDescription
attachobjectVariable name → value-label name to attach; an empty string detaches.
data_labelstringNew dataset label; an empty string removes it.
dry_runbooleanValidate and report the changes without writing.
path *stringPath to the .dta file to read or edit.
value_labelsobjectValue-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.
ParameterTypeDescription
dry_runbooleanValidate and report the changes without writing.
labelsobjectVariable name → new label. An empty string removes the label. Omit to read the current labels.
path *stringPath 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).
ParameterTypeDescription
auto_close_logsbooleanOn 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 *stringStata code to execute. Multi-line OK.
expectobjectAcceptance 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_formatstring
include_dataset_variablesboolean
include_estimationstringHow 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_logboolean
include_graphsstring
include_resultsstringHow 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_headinteger
log_lines_tailinteger
max_coefficientsintegerCap on coefficient rows in results.estimation. estimation.n_coefficients always reports the true count and coefficients_truncated flags the cut.
origin_cell_idstringStable 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_kindstringWhich editor surface produced the submitted code.
origin_labelstringHuman-readable source label, for example demo/test1.do:1.
origin_pathstringAbsolute path of the source .do file. Used for the default Stata working directory, run-bundle placement, and metadata.
persist_generated_filesbooleanWhen 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_filesbooleanWhen true and origin_path is provided, write immutable .log/.smcl artifacts under <origin dir>/log-files/<run>/.
run_in_backgroundbooleanReturn 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_idstringSession 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_msanyHard 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_filesbooleanReport 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_workdirbooleanWhen 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_dirstringOptional 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.
ParameterTypeDescription
job_id *stringjob_id returned by stata_run(run_in_background=true).
log_lines_tailintegerLines of the running job's transcript to return as log_tail. 0 omits it.
wait_msintegerBlock up to this many milliseconds for the job to

Security checks

6 checks have not been run yet.

Questions

About Stata Code

How do I install Stata Code?

Run uvx stata-code, then add the server to your MCP client's configuration.

Is Stata Code safe to use with an AI agent?

Its trust score is 69 out of 100 (good). Conduid hasn't run static security checks on this repository yet, so review the source yourself before granting it credentials. It has no ConduID identity yet, so agent calls to it are not receipted.

Is Stata Code still maintained?

Yes — the last commit was 6 days ago. The repository has 61 stars and 10 forks.

What tools does Stata Code provide?

Conduid read 23 tools from the source: cancel_session, get_graph, get_log, get_matrix, inspect_data, install_package, lint_do, list_background_runs and 15 more. 20 of them publish their parameters, listed under Tools above.