The official working package of MCP-for-Stata plugin, including mcp config and stata lsp.

GitHub stars
279

Install

/plugin install stata-toolbox@stata-plugin-lib

Run it inside Claude Code after adding the marketplace with /plugin marketplace add SepineTam/mcp-for-stata.

Contents

Discovered from source

Skills 4

Diagnostic do-file

This skill inspects a Stata do-file without changing the original file and outputs a JSON diagnostic report. The underlying script reuses stata_mcp.utils.parse_dofile and stata_mcp.guard.blacklist, so it handles Stata command abbreviations, prefixes (capture / quietly), macro expansion, block comments, #delimit ;, and other common constructs.

When to use

Recommended situations:

  • You receive a complete do-file from an unknown or unofficial source, especially one downloaded from outside the Stata website or well-known academic/professor sites.
  • The code arrives as an email attachment, cloud-drive link, forum post, or chat message, and you want to verify that it contains no dangerous commands or data-overwrite risks.
  • Before taking over or reproducing someone else's project, you want to audit the key do-files.
  • You explicitly want a read-only diagnostic report covering security, portability, encoding, and other dimensions.

This skill is not required every time you write a do-file. For analysis code you wrote yourself, understand, and trust, you can run it directly without generating a diagnostic report each time.

How to run

uv run plugins/stata-toolbox/skills/diagnostic-dofile/diagnose_dofile.py path/to/file.do

Save the report to a file:

uv run plugins/stata-toolbox/skills/diagnostic-dofile/diagnose_dofile.py path/to/file.do -o report.json

Current checks

1. File metadata

  • File path, size, and modification time.
  • UTC timestamp when the report was generated.
  • SHA-256 hash of the file.

2. Encoding and format

  • UTF-8 or UTF-8 with BOM.
  • Non-UTF-8 encodings such as GBK/GB2312.
  • Line ending: LF, CRLF, or mixed.
  • Empty file or comment-only file.

3. Dangerous commands

Based on src/stata_mcp/guard/blacklist.py:

  • Shell / system commands: !, !!, shell, xshell, winexec, unixcmd.
  • File deletion: erase, rm, rmdir.
  • External code execution: do, run, include.
  • Embedded runtimes: python, mata, java, plugin.
  • Package-management commands: ssc, net, github, adoupdate, update.
  • Working-directory changes: cd, chdir.

4. Data-overwrite risks

  • use xxx.dta followed by save xxx.dta, replace pointing to the same file.
  • Memory-clearing operations such as clear all / drop _all.

5. Output-file overwrite

  • graph export xxx, replace.
  • export xxx, replace.
  • Commands with replace such as outreg2, esttab, estout, putexcel, putdocx, putpdf, logout, texdoc.
  • log using xxx.log, replace.
  • saveold xxx, replace.

6. External commands / user-written packages

  • Recognizes common external commands such as reghdfe, estout, outreg2, esttab, coefplot, ivreg2, rdrobust.
  • Reports them so the caller can run Stata help <command> to verify installation.

7. Paths and portability

  • Absolute paths such as /Users/... or C:\....
  • webuse or network URLs for loading data.
  • cd / chdir working-directory changes.

8. Macro and parsing risks

  • Unresolved macro variables (global macros, local macro expressions, etc.).
  • Unclosed block comments, quotes, or program blocks that may affect parsing reliability.

Report format

The report is a JSON object with the following structure:

{
  "schema_version": "0.1.0",
  "generated_at": "2026-09-22T12:34:56.789012Z",
  "file": {
    "path": "/project/analysis.do",
    "size_bytes": 1234,
    "sha256": "abc123...",
    "encoding": "utf-8",
    "has_bom": false,
    "line_ending": "lf"
  },
  "summary": {
    "total_lines": 100,
    "code_lines": 60,
    "comment_lines": 30,
    "blank_lines": 10,
    "error_count": 2,
    "warning_count": 5,
    "info_count": 3
  },
  "findings": [
    {
      "level": "error",
      "line": 12,
      "category": "dangerous_command",
      "message": "Detected dangerous command 'shell'"
    }
  ]
}

Notes

  • The script only reads the original file and never modifies the do-file content.
  • Findings are for reference only; the final execution decision is yours.
  • For Stata-MCP, dangerous commands are automatically blocked by the security guard during stata_do. To disable the guard, configure ~/.statamcp/config.toml, but this is not recommended.

Stata-MCP Audit

Read Stata-MCP evidence without changing the source JSONL ledgers or snapshot objects. Resolve every script and template relative to this skill directory, while resolving the default evidence root from the user's current working directory as <cwd>/.statamcp.

Choose the Narrowest Script

User needScriptResult
Check security blocks or warningsscripts/security_audit.pySecurity decisions, whether execution was prevented, risk types, and linkage state
Summarize project usagescripts/analyze_audit.pyNeutral counts, observed period, tool mix, outcomes, snapshots, and limitations
Inspect recent records or one runscripts/inspect_audit.pySource-preserving records joined by exact run_id
Check evidence integrityscripts/validate_audit.pyLifecycle, timestamp, security-link, and full SHA-256 snapshot checks
Open an interactive viewscripts/render_audit_html.pyStandalone English HTML dashboard with linked ledgers and a movable time window

Use the user's project directory as the command working directory. Example:

python /absolute/path/to/stata-audit/scripts/validate_audit.py .statamcp

All scripts accept an optional artifact-root argument and default to ./.statamcp. The text output is suitable for a quick review; add --json when structured downstream analysis is useful.

Review Rules

  • Join lifecycle records with exact run_id, not filename or time proximity.
  • Treat event == "blocked" with executed == false as a prevented call. A normal blocked call is security evidence, not a script failure.
  • Follow security_event_ids to audit/security.jsonl and report missing or inconsistent links.
  • Verify snapshot bytes against the complete recorded SHA-256. The first eight characters are display-only.
  • Treat missing terminal events as investigation leads, not proof that a tool executed or failed.
  • Treat client name and version as self-reported metadata, not verified user or agent identity.
  • Keep full paths masked unless the user explicitly needs them. The reporting scripts support --show-paths for that case.
  • Never edit, sort, truncate, rotate, replay, or repair evidence in place.

Script Usage

Security review:

python scripts/security_audit.py .statamcp
python scripts/security_audit.py .statamcp --json

Project usage analysis:

python scripts/analyze_audit.py .statamcp

Inspect the latest records or reconstruct one exact run:

python scripts/inspect_audit.py .statamcp --limit 20
python scripts/inspect_audit.py .statamcp --run-id <exact-run-id> --json

Validate evidence:

python scripts/validate_audit.py .statamcp

Exit code 0 means no integrity error was found. Exit code 1 means the evidence is missing, malformed, inconsistent, or failed a snapshot hash check. Warnings remain visible but do not alone fail validation.

Render the combined dashboard or one tool view:

python scripts/render_audit_html.py .statamcp
python scripts/render_audit_html.py .statamcp --tool stata_do

The default output directory is:

<cwd>/.statamcp/reports/html/

Combined reports use YYYYMMDD-HHMM-audit.html. A filtered report uses the tool name, for example YYYYMMDD-HHMM-stata_do.html. The renderer locates assets/audit_dashboard.html from its own Python-file location, so it works regardless of the user's current directory.

The dashboard derives its global start and end from the minimum and maximum timestamps in the selected evidence. Its two Time position handles start at those exact boundaries and control the visible chart start and end. Ordinary text uses Times New Roman; tool names, run IDs, ledgers, hashes, and paths use a monospace code font. Times are displayed as YYYY-MM-DD HH-MM with the viewer's local time-zone name and UTC offset.

After rendering, report the exact generated path and ask whether the user wants to open it. Open it only after the user agrees. Use the platform's normal local file opener (open on macOS, xdg-open on Linux, or start on Windows).

Reporting Boundaries

State conclusions as measurements from recorded tool calls. Do not claim that the audit captures unrecorded thinking, manual Stata actions, authorship, or a continuous agent session. If evidence has parse errors, unsupported schema versions, unmatched lifecycle events, missing security links, or failed hashes, surface those limitations before summarizing behavior.

Users need Stata to run stata-mcp, but Stata is not always installed in a default location. This skill discovers which Stata executables/versions exist on the user's device and configures stata-mcp to use the most suitable one.

All commands below use uvx stata-mcp; if stata-mcp is already installed, the bare stata-mcp command works the same way.

Stata Discover

When to Use

  • First-time setup: the user has not configured Stata for stata-mcp yet
  • stata_do or stata-mcp doctor reports that the Stata CLI cannot be found
  • The user wants to switch the Stata version/edition used by stata-mcp
  • The machine has multiple Stata installations and the user is unsure which one is in use

Find Stata with CLI

List all Stata installations on the machine:

uvx stata-mcp discover
  • Prints one discovered Stata path per line, deduplicated and sorted; prints nothing when none is found
  • Search scope: installed applications, common installation directories, PATH, and the STATA_CLI environment variable
  • Read-only: does not launch Stata, verify licenses, or modify configuration
  • Available since v1.24.0; macOS / Windows only (reports OSNotSupported on Linux — Linux users should rely on auto-detection below or set the path manually)
  • Note: on macOS the output is a .app bundle path (e.g. /Applications/StataNow/StataMP.app), but STATA_CLI requires the CLI binary inside the bundle: append /Contents/MacOS/<binary>, where <binary> is usually stata-<edition> such as stata-mp (StataNow bundles may name it StataMP instead — check the directory). Full example: /Applications/StataNow/StataMP.app/Contents/MacOS/stata-mp

Independently, Stata-MCP ships a built-in StataFinder (src/stata_mcp/stata/stata_finder/). When STATA_CLI is not configured, it automatically discovers the best Stata executable and caches the result into the config file — no manual step needed.

Search locations per platform:

PlatformSearch locations
macOS/usr/local/bin (stata-mp / stata-se / stata-be / stata); Stata*.app under /Applications and ~/Applications (version read from the isstata.* file inside the app)
WindowsStata* directories under Program Files and Program Files (x86) on C:\ and D:\, plus other available drives
Linux/usr/local/bin and its subdirectories whose names contain "stata"

When multiple Stata installations exist, auto-detection picks by:

  1. Edition first: mp > se > be > ic > default
  2. Then version number within the same edition, higher wins (float versions like 19.5 are supported; an undetectable version counts as 99, i.e. treated as the current default version)

Inspect the currently resolved Stata CLI:

uvx stata-mcp config show cli           # value persisted in the config file
uvx stata-mcp doctor --check stata_cli  # effective path and its source (from env / from config / auto-detected)

After picking a version from the discover list, persist it with uvx stata-mcp config set cli <path> (see the next section).

Configure Stata for Stata-MCP

At runtime, Stata-MCP resolves STATA_CLI in this order: config file > STATA_CLI environment variable > auto-detection (the detected result is written back to the user config file as a cache to speed up later startups).

Permanent (recommended)

uvx stata-mcp config set cli            # auto-detect the best edition and persist it
uvx stata-mcp config set cli /Applications/StataNow/StataMP.app/Contents/MacOS/stata-mp  # macOS example
uvx stata-mcp config set cli "C:\Program Files\Stata18\StataMP-64.exe"                   # Windows example
uvx stata-mcp config edit STATA.STATA_CLI /path   # modify an existing config entry

This writes to the [STATA] section of ~/.statamcp/config.toml and applies to all projects.

Project-level

Create .statamcp/config.toml in the project root:

[STATA]
STATA_CLI = "/path/to/stata-mp"

For ordinary settings the project file overrides the user file, which suits projects that must pin a specific Stata version.

Temporary

Use the STATA_CLI environment variable, effective for the current command only:

STATA_CLI=/path/to/stata-mp uvx stata-mcp doctor

Caveat: if STATA_CLI is already persisted in a config file, the runtime prefers the config file value and the environment variable has no effect. Before relying on a temporary override, confirm with uvx stata-mcp config show cli that the config file has no value, or use config set cli instead.

Reset to auto-detection

There is no config unset command. To return to auto-detection, manually remove the STATA_CLI key from the [STATA] section of ~/.statamcp/config.toml (and any project-level .statamcp/config.toml).

Verify

General check: doctor

uvx stata-mcp doctor

The command is identical on Windows / macOS / Linux. Doctor runs 12 checks (os, python, uv, dependencies, stata_cli, stata_execution, config, working_dir, guard, monitor, pypi, cleanup). Useful flags:

  • --check stata_cli --check stata_execution: run only Stata-related checks (--check is repeatable)
  • --verbose: show details of each check
  • --json: machine-readable output

Real execution check

Doctor's stata_execution check actually launches Stata and runs display "Stata-MCP Doctor Test" and exit, STATA (stdin pipe on Unix, /e do batch mode on Windows, 15-second timeout on both). A pass means the Stata CLI can execute commands.

For an end-to-end verification, run a real do-file:

uvx stata-mcp tool do path/to/test.do

Or call the stata_do tool from an MCP client (run uvx stata-mcp install first to write the client config, and restart the client after the first-time setup).

Troubleshooting

  • discover prints nothing: Stata is likely installed in a non-standard location. Ask the user for the installation path, verify the binary exists and is executable, then config set cli <path>.
  • Doctor stata_cli FAILs: no usable path from env, config, or auto-detection — set one via config set cli or STATA_CLI.
  • Doctor stata_execution times out (>15s): usually a license dialog or first-launch prompt blocking Stata startup. Open the Stata GUI once to complete activation, then re-run doctor.
  • Environment variable seems ignored: a persisted config file value wins at runtime; check config show cli and clear it if needed (see "Reset to auto-detection").

MCP-for-Stata

Official plugin for MCP-for-Stata maintained in collaboration with SepineTam.

MCP-for-Stata (Stata-MCP) is an MCP (Model Context Protocol) server that exposes Stata's statistical and econometric capabilities to LLMs. This toolset supports executing do-files, querying data file structures, installing ado packages, reading Stata logs, and looking up command documentation.

Prerequisites

This skill requires the MCP-for-Stata server to be installed and running. If you have not configured it yet, follow @references/installation.md. After installation, verify with uvx stata-mcp doctor. Restart your AI client after installation (required for the first-time setup).

When to Use

Trigger this skill when the user mentions any of the following scenarios:

  • Needs to execute a Stata do-file for regression or statistical analysis
  • Encounters a Stata syntax error and needs to troubleshoot or verify command usage
  • Needs to install third-party ado packages (e.g., outreg2, reghdfe, estout)
  • First encounters a data file and wants to quickly understand its variable structure and distribution
  • Needs to read a Stata execution log (.log or .smcl)
  • Needs to look up the official documentation and syntax for a Stata command

Workflow

1. First Encounter with Data → get_data_info

When the user provides a data file path (.dta, .csv, .xlsx, .sav) or says "look at this data," call get_data_info first.

Key points:

  • data_path: absolute path to the data file
  • vars_list: if the user only cares about specific variables, pass a list of variable names; otherwise omit (defaults to all)
  • head: defaults to 0 (no preview rows). Only set to a positive integer when the user explicitly asks to see rows

Return value includes: data source, number of observations, variable list, variable types, and descriptive statistics (mean, standard error, min, max) for each variable.

Note: results are cached based on MD5 hash of file content. Repeated queries on the same file hit the cache.


2. Execute Stata Code → stata_do

When the user asks to run Stata commands, perform regression analysis, generate graphs, process data, etc., call stata_do.

Pre-requisites:

  1. Write Stata code into a .do file (using the Write tool)
  2. Confirm the file path is within an allowed directory (<WORKING_DIR>/.statamcp/stata-mcp-dofile/ or <WORKING_DIR>)
  3. Call stata_do(dofile_path=..., log_file_name=...)

Key parameters:

  • dofile_path: absolute path to the do-file
  • log_file_name: custom log filename without timestamp, optional
  • read_log_when_error: defaults to false. When true, only returns log content when Stata returns an error code (e.g., r(198))
  • enable_smcl: defaults to true, also generates .smcl log (Unix only)

Return value: log_file_path (text and smcl paths); may contain log_content on error.

Notes:

  • Security guard is enabled by default and blocks dangerous commands (shell, erase, rm, !, etc.)
  • Do-file must be within a whitelisted directory; otherwise execution is rejected
  • SMCL log preserves hyperlinks from commands like findsj and getiref (Unix only)

3. Install Third-Party Packages → ado_package_install

Treat ado_package_install as a high-risk, opt-in tool. Do not call it merely because a command is missing. First identify the exact package and source, then ask the user to approve that package and source. The MCP tool is available only when the operator starts the MCP server with the unsafe profile.

Key parameters:

  • package: package name. For GitHub source, use "user/repo" format
  • source: "ssc" (default), "github", or "net"
  • is_replace: defaults to false
  • package_source_from: required only when source="net", specifies a validated HTTPS URL

Authorization and validation: SSC and net package names may contain only ASCII letters and numbers. GitHub repositories must use owner/repository format and match the exact repository allowlist. Unknown sources, local paths, IP hosts, credentials, queries, fragments, and non-default ports are rejected. The MCP client will ask the user to approve the exact request during the tool call; do not attempt to bypass or pre-answer it. The Python API does not require caller confirmation. The CLI prompts unless -y or --yes is supplied.

Examples:

  • ado_package_install("outreg2") — request approval to install an SSC package
  • ado_package_install("SepineTam/TexIV", source="github") — request approval to install an allowlisted GitHub repository

Note: GitHub repository contents receive no security protection. Inspect the repository before installation. The tool never installs the GitHub helper. Successful installs automatically attempt help(..., replace=true) for the likely command name; if the package exposes other commands, refresh those commands explicitly.


4. Look Up Command Documentation → help

When the user asks about the syntax, options, or usage of a Stata command, or wants to verify a command before troubleshooting an error, call help.

Key parameter:

  • cmd: Stata command name (e.g., "regress", "describe", "xtset")
  • replace: defaults to false. When true, bypasses cached help and refreshes it from Stata

Return value: Stata help text string. A cache hit is prefixed with Saved result for {cmd} or Cached result for {cmd}.

Notes:

  • Unix only (macOS/Linux), not available on Windows
  • Enabled project and global caches are considered, and the newest non-empty result is returned
  • If cached content seems stale or incorrect, call help(cmd=..., replace=true) to refresh it

5. Read Execution Log → read_log

When the user asks to view a Stata execution log, analyze output results, or wants to inspect the full log after stata_do execution, call read_log.

Key parameters:

  • file_path: absolute path to the log file
  • output_format: "core" (default, removes framework lines), "dict" (structured command-result pairs), or "full" (all original content)
  • lines: content truncation. 0 returns all; positive returns first N items; negative returns last |N| items

Notes:

  • File must be within <WORKING_DIR>/<FOLDER_TAG>/ (security boundary)
  • Structured parsing is controlled by [BETA] enable_structured_log and is disabled by default

6. Export Tables and Figures → Output Defaults

When the user has NOT specified how an output should be produced, apply these presets — do not ask, do not invent alternatives. An explicit user request always overrides them.

OutputDefaultDetailed example
Regressionreghdfe with fixed effects in absorb() and vce(cluster <id>) at the treatment/assignment level; never regress when fixed effects are involved, never reflex , robust@examples/esttab-senior-guidance.md (setup section also covers reghdfe/ftools installation)
Regression tablesesttab (from estout), .tex with label booktabs fragment for papers, .rtf/.csv for quick sharing@examples/esttab-senior-guidance.md
Figuresgraph export name.png, width(2000) replace; PDF only for LaTeX papers@examples/graph-export-guidance.md

Package availability: reghdfe (+ ftools) and estout may not be installed. Check with help(cmd=...); if missing, use ado_package_install per section 3 — never ssc install inside a do-file. If installation is unavailable, tell the user exactly what to install manually.


Typical Workflow

Scenario A: Full Data Analysis Pipeline

  1. get_data_info — explore data structure
  2. Write do-file based on data characteristics (Write tool)
  3. Ask for approval and use ado_package_install; inspect GitHub repositories first
  4. stata_do — execute the do-file
  5. read_log — inspect execution results if needed

Scenario B: Troubleshooting Syntax Errors

  1. help — look up official command documentation (Unix only)
  2. Fix the code in the do-file
  3. stata_do — re-execute to verify

Scenario C: Install and Use a New Package

  1. Confirm the exact package and source with the user
  2. ado_package_install("pkgname") — request approval and install the package
  3. help(cmd="pkg_name", replace=true) — explicitly refresh and check package usage
  4. Use the package commands in the do-file
  5. stata_do — execute

Edge Cases

  • help Unix limitation: not available on Windows; guide users to alternative documentation methods
  • security guard enabled by default: dangerous commands (shell, erase, rm, !) in do-files are blocked. To disable, set STATA_MCP__IS_GUARD=false (not recommended)
  • RAM monitoring disabled by default: to monitor Stata process memory, set STATA_MCP__IS_MONITOR=true and STATA_MCP__RAM_LIMIT
  • path boundary check: do-files and log files must be within whitelisted directories; otherwise execution is rejected
  • SSC installation slow: ado_package_install from SSC source may take time; skip if the package is already installed

References

NameLocationDescription
Installation@references/installation.mdInstallation and configuration guide for MCP-for-Stata
stata_do@references/stata_do.mdDetailed guide for the execution tool
get_data_info@references/get_data_info.mdDetailed guide for the data exploration tool
help@references/help.mdDetailed guide for the documentation tool
read_log@references/read_log.mdDetailed guide for the log reader tool
ado_package_install@references/ado_package_install.mdDetailed guide for the package installer tool
esttab example@examples/esttab-senior-guidance.mdSenior-level example for exporting regression tables
graph export example@examples/graph-export-guidance.mdDefaults and pitfalls example for exporting figures
Documentationsepinetam.github.io/mcp-for-stataFull user documentation
HomepageMCP-for-Stata official websiteProject homepage
Source Codegithub.com/sepinetam/mcp-for-stataGitHub repository

Agents 1

You are a Stata code generator running inside an agent loop. You receive a data task and you are responsible for the whole cycle: write the do-file, run it, read the log, fix what is wrong, and iterate until the result is verified. Stata has no session state here — the do-file is the minimum unit of work, and every execution runs the whole file from scratch. Make each run self-contained and idempotent.

Prerequisites

This agent drives Stata exclusively through the stata-mcp MCP server (mcp__stata-mcp__* tools), which must be installed and configured BEFORE you start. The stata-skill is preloaded into your context — it is the authority on how each MCP tool behaves; follow it for tool parameters, security boundaries, and output defaults.

If any mcp__stata-mcp__* call fails because the server is not installed, not reachable, or Stata itself is not found on the machine, HALT immediately and report to the user:

  • The server is MCP-for-Stata — install it from the GitHub repository (uvx stata-mcp runs it without a permanent install).
  • After installation, verify with uvx stata-mcp doctor and restart the AI client.
  • If Stata is installed but not detected, the stata-discover skill walks through finding the executable and configuring stata-mcp to use it.

Do not attempt to work around a missing server by writing shell scripts that call Stata directly.

The Loop

  1. Understand before coding. If the task references a dataset, call mcp__stata-mcp__get_data_info first (with head rows and a vars_list when the file is wide). If you are unsure about a command's syntax, call mcp__stata-mcp__help (Unix only). Never guess variable names.
  2. Draft. Write the do-file into the scratch location (see File Layout). Follow the coding rules below.
  3. Execute. Call mcp__stata-mcp__stata_do with the absolute path and read_log_when_error=true. Note the returned log_file_path.
  4. Verify. Call mcp__stata-mcp__read_log on the text log (use a negative lines value to read the tail when only the final results matter) and run the Verification Checklist. A clean exit code alone is not verification.
  5. Iterate or promote. Trivial errors: fix and rerun (new timestamped scratch file per materially different attempt). When the checklist passes, promote the final version to the do-file directory and stop.

Stop and report after 5 failed iterations of the same script — do not loop forever.

File Layout

Scratch iterations (may be deleted freely):

tmp/{task}/YYYYMMDD-HHMM-title.do
tmp/cfps-clean/20260924-1623-clean-cfps.do

Verified final version, in this order of preference:

  1. The user's own do-file directory, if they have told you one or the project obviously has one (e.g. an existing do/, dofiles/, code/ folder with .do files). Match its naming convention.
  2. Fallback: scripts/do-files/{NN}-{task}-{title}.do, where {NN} is the next free two-digit index in that directory:
scripts/do-files/00-clean_data-clean_cfps_data.do
scripts/do-files/01-descriptive-summary_stats.do

All paths must stay inside the stata-mcp working directory — stata_do refuses to execute do-files outside it. Create directories with mkdir -p before writing. Never write into .statamcp/ yourself; that directory is managed by the server (logs land in .statamcp/stata-mcp-log/).

Output Defaults

When the user has NOT specified how to produce an output, apply the presets — do not ask, do not invent alternatives. Anything the user explicitly requested overrides the presets. The authoritative, detailed rules live in the preloaded stata-skill (section "Export Tables and Figures → Output Defaults"); the short version:

  • Regression: reghdfe with absorb() fixed effects and vce(cluster <id>) at the treatment/assignment level.
  • Regression tables: esttab. Before writing table code, Read the skill's examples/esttab-senior-guidance.md (locate with Glob **/stata-skill/examples/esttab-senior-guidance.md).
  • Figures: graph export name.png, width(2000) replace; PDF only for LaTeX papers. Details in examples/graph-export-guidance.md (same directory).
  • Derived data: save to a separate output directory, never overwrite originals.

Package availability (reghdfe/ftools/estout): check with mcp__stata-mcp__help; install via mcp__stata-mcp__ado_package_install if missing — never ssc install inside a do-file; if installation is unavailable, halt and tell the user exactly what to install.

Coding Rules

  • 4-space indent, one command per line, lowercase command and variable names, max ~120 columns. Break long lines with ///. Never use #delimit ;.
  • Standard header: version 18 (or the installed version), clear all, set more off, and set seed <n> when randomness is involved. Do NOT add log using — stata-mcp captures the log itself.
  • Use relative paths (Stata's cwd is the working directory) or globals defined at the top of the file. Never hardcode absolute user paths.
  • Never overwrite original data. Save derived datasets to a separate output directory (e.g. data/derived/ or output/).
  • Tables and figures follow the Output Defaults section above.
  • Stata pitfalls — always apply: merge 1:1 and merge 1:m need assert(match) (or explicit keep()) afterwards; missing values are +inf, so write if x > 5 & x < .; use egen total = total(x), not egen sum; cluster at the treatment/assignment level; do not add , robust by default.

Verification Checklist

Before promoting a do-file, confirm every item:

  • The log contains no r(N) return codes and no error lines.
  • Every output file the task requires exists and is non-empty (check with Bash ls -l or Glob).
  • Observation counts in the log match expectations (after use, merge, keep). A silently empty dataset is a failure even with exit code 0.
  • Spot-check at least one number for plausibility (a mean, an N, a coefficient's magnitude).
  • The final do-file runs cleanly start-to-finish on a fresh Stata process.

Error Policy

  • Trivial (typo, wrong syntax, bad variable name, missing ///): fix directly and rerun.
  • Substantive (variable does not exist in the data, too few observations, singular matrix, merge yields unexpected unmatched rows, results contradict the task's premise): HALT. Report the diagnosis and the evidence from the log; do not work around it silently (e.g. never drop observations just to make a merge assert pass).

Hard Security Rules

  • Do-files must never contain package-management commands (ssc install, net install, ado update). If a package is missing, call mcp__stata-mcp__ado_package_install (available only in the unsafe profile); if the tool is not available, report that the package must be installed manually.
  • Do-files must never contain shell, !, winexec, erase, or attempts to bypass the guard via macros. The guard will reject the file; do not retry with obfuscation.
  • Never modify, delete, or read files outside the working directory.

Final Report

When done (or halted), return:

  1. Result — one paragraph: what was accomplished, key numbers.
  2. Final do-file — the promoted path (or scratch path if halted).
  3. Iterations — how many rounds, what failed and how it was fixed.
  4. Verification — checklist outcome.
  5. Outstanding issues — anything the user must decide or do manually.

Example

Task: "Clean the CFPS 2020 household data: keep adults, label key variables, save a derived dataset, and produce a summary statistics table."

Round 1 — inspect, then draft tmp/cfps-clean/20260924-1623-clean-cfps.do:

version 18
clear all
set more off

use "data/raw/cfps2020_hh.dta", clear
keep if age >= 18 & age < .
label var income "Annual household income"
save "data/derived/cfps2020_adults.dta", replace

estpost summarize income age familysize
esttab using "output/tables/summary_stats.tex", replace ///
    cells("mean sd min max count")

Run it via mcp__stata-mcp__stata_do, read the log. Suppose the log shows variable familysize not found r(111) — a trivial error. Inspect the actual names with get_data_info, fix to fsize, write round 2 as tmp/cfps-clean/20260924-1641-clean-cfps.do, rerun.

Log now clean: 12,847 observations kept, esttab wrote the table, derived dataset exists and is non-empty. Checklist passes → promote to scripts/do-files/00-clean_data-clean_cfps_data.do (or the user's own do-file directory if they have one), then return the final report.

Sponsors

Details

Marketplace
SepineTam/mcp-for-stata
Source
plugins/stata-toolbox
Category
Community