Sandbox
@ashuiGordon/stata-cli

Stata CLI for Claude Code, Codex, and Cursor

stata-cli is a terminal interface for Stata built for agent use. It uses PyStata to run code, read data, fetch econometric results as JSON, and keep Stata alive in a daemon for faster repeat runs.

56 stars3 forksPythonUpdated 27d ago
Who it's for

Builders who want their coding agent to run Stata commands, inspect datasets, and collect regression output in a structured way.

What it delivers

You can have an agent run Stata analyses and return results it can parse instead of scraping console output.

What it does

Run Stata code

Execute inline commands, multi-line blocks, or stdin input with `run`.

Run do files

Execute `.do` files with line continuation handling and auto-named graph output with `do`.

Return structured results

Read `r()`, `e()`, `s()`, and matrices like `e(b)` and `e(V)` as JSON with `return` and `matrix`.

Inspect data and metadata

View the current dataset, variable details, labels, frames, and macros from the terminal.

Persistent daemon mode

Keep PyStata running in the background for faster repeated commands and separate sessions.

Agent-friendly output

Use JSON mode, compact output, token limits, exit codes, and log files for reliable tool use.

Stata reference library

Look up built-in help topics and a 57-topic skill library for econometrics, causal inference, and packages.

How to get it

  1. 1Option 1 — From pip (recommended)
    pip install stata-cli
  2. 2Option 2 — From npm / npx (zero Python setup)
    # One-shot usage
    npx stata-cli run "display 1+1"
    
    # Global install
    npm install -g stata-cli
  3. 3Option 3 — From source
    git clone https://github.com/ashuiGordon/stata-cli.git
    cd stata-cli
    pip install -e ".[data]"
  4. 4Step 1 — Install
    pip install stata-cli
  5. 5Step 2 — Verify Stata path
    stata-cli detect
  6. 6Step 3 — Start daemon (recommended)
    stata-cli daemon start

README

stata-cli

The agent-native Stata CLI for empirical research

stata-cli: agent-native Stata CLI for AI coding agents

License: MIT Python Version npm version

中文版 | English

An agent-native command-line interface for Stata via PyStata. Let Codex, Claude Code, Cursor, and other AI coding agents run .do files, inspect datasets, retrieve econometric results as JSON, and export graphs from the terminal. A persistent daemon keeps repeated analyses fast.

Install · AI Agent · Commands · Daemon · Advanced · Contributing

Why stata-cli?

  • Agent-Native Design — Structured JSON output, exit codes, and a SKILL.md definition out of the box — AI Agents can operate Stata with zero extra setup
  • Sub-Second Execution — Daemon mode keeps PyStata alive in the background, reducing startup from ~2-3s to ~85ms (35x speedup)
  • Full Coverage — Run code, execute .do files, view data, browse help, export graphs, interrupt execution — everything you need from one binary
  • AI-Friendly & Optimized — Compact output mode, token limit management, structured JSON responses, and graph auto-naming — designed for Agent tool-use
  • Open Source, Zero Barriers — MIT license, ready to use, just pip install
  • Up and Running in Seconds — Auto-detects your Stata installation, from install to first command in 2 steps

Features

CategoryCapabilities
Run CodeExecute inline Stata code, multi-line blocks, or pipe from stdin
Do FilesRun .do files with /// line continuation support and graph auto-naming
Data ViewerView current dataset as JSON with if-condition filtering and row limits
Variable MetadataInspect variable names, types, formats, and labels via vars
Stored ResultsRetrieve r(), e(), s() results as structured JSON via return
Matrix AccessRead Stata matrices (e.g. e(b), e(V)) as JSON via matrix
Value LabelsList and inspect value labels via labels
Macro AccessGet/set Stata macros including c(), e(), r() system macros
Frame ManagementList Stata frames and current working frame via frame
Help SystemBrowse Stata help topics with SMCL-to-plain-text conversion
Graph ExportAuto-detect and export graphs as PNG/SVG/PDF to ~/.stata-cli/graphs/
Daemon ModePersistent background process for sub-second execution; parallel sessions via --session
Output ControlCompact mode, JSON output, token limit management, log file output
InterruptionSend break signal to stop long-running commands
Skill LibraryBuilt-in Stata reference with 57 topics: syntax, econometrics, causal inference, packages

Installation & Quick Start

Requirements

  • Stata 17+ installed on your machine (provides the PyStata library)
  • Python 3.9+

Quick Start (Human Users)

Install

Choose one of the following methods:

Option 1 — From pip (recommended):

pip install stata-cli

Option 2 — From npm / npx (zero Python setup):

# One-shot usage
npx stata-cli run "display 1+1"

# Global install
npm install -g stata-cli

The npm package is a thin wrapper that delegates to uvx, pipx, or python3.

Option 3 — From source:

git clone https://github.com/ashuiGordon/stata-cli.git
cd stata-cli
pip install -e ".[data]"

Use

# 1. Verify Stata is detected
stata-cli detect

# 2. Run your first command
stata-cli run "display 1+1"

# 3. Start daemon for fast execution
stata-cli daemon start
stata-cli run "sysuse auto, clear"    # ~85ms!

Quick Start (AI Agent)

The following steps are for AI Agents calling stata-cli via the Bash tool.

Step 1 — Install

pip install stata-cli

Step 2 — Verify Stata path

stata-cli detect

Step 3 — Start daemon (recommended)

stata-cli daemon start

Step 4 — Run commands

# Inline code
stata-cli run "sysuse auto, clear
regress price mpg weight
predict yhat"

# Structured JSON output
stata-cli --json run "summarize price"

# View data
stata-cli data --if "price>10000" --rows 50

# Lookup command syntax
stata-cli help regress

Commands

run — Execute Stata Code

stata-cli run "sysuse auto, clear"

# Multi-line
stata-cli run "sysuse auto, clear
summarize price mpg
regress price mpg weight"

# Pipe from stdin
echo "display 42" | stata-cli run -

do — Execute a .do File

stata-cli do analysis.do
stata-cli --compact do long_script.do

Do files are preprocessed: /// line continuations are joined, and unnamed graph commands are auto-named for reliable export.

data — View Current Dataset

stata-cli data
stata-cli data --if "price>5000" --rows 50

Returns the current dataset as JSON with columns, data, types, and row counts.

help — Browse Stata Help

stata-cli help regress
stata-cli help summarize

Displays help as plain text (SMCL markup is automatically converted).

stop — Interrupt Execution

stata-cli stop

Sends a break signal to the running Stata command (daemon mode).

detect — Find Stata Installation

stata-cli detect

Prints the auto-detected Stata installation path.

return — Retrieve Stored Results

stata-cli return r         # r() results (after summarize, etc.)
stata-cli return e         # e() results (after regress, etc.)
stata-cli return s         # s() results

Returns r(), e(), or s() stored results as structured JSON — scalars, macros, and matrix references.

vars — Variable Metadata

stata-cli vars                # all variables
stata-cli vars price mpg      # specific variables

Returns variable names, types, formats, and labels as JSON. More structured than describe.

matrix — Read Stata Matrices

stata-cli matrix e(b)         # coefficient vector
stata-cli matrix e(V)         # variance-covariance matrix

Returns matrix data, dimensions, and row/column names as JSON.

labels — Value Labels

stata-cli labels               # list all value label names
stata-cli labels origin        # show value-label mapping
stata-cli labels --var foreign # show label attached to a variable

macro — Get/Set Macros

stata-cli macro get "c(current_date)"
stata-cli macro get "e(cmd)"
stata-cli macro set myvar "hello"

Access Stata macros including system macros (c(), e(), r()).

frame — List Frames

stata-cli frame

Shows all Stata frames and the current working frame.

skill — Stata Reference Library

stata-cli skill                # overview: gotchas, patterns, topic routing table
stata-cli skill --list         # list all 57 topics with descriptions
stata-cli skill regression     # linear regression reference
stata-cli skill did            # modern DiD packages (csdid, did_multiplegt)
stata-cli skill reghdfe        # reghdfe package guide

Built-in reference library covering data management, econometrics, causal inference, graphics, Mata programming, and 20+ community packages. Aliases supported (e.g. did for difference-in-differences, panel for panel-data).

Daemon Mode

The daemon keeps PyStata alive in the background — reduces execution time from ~2-3s to ~85ms (35x speedup).

stata-cli daemon start       # Start background daemon
stata-cli run "display 1"    # Fast — auto-routes through daemon
stata-cli daemon status      # Check daemon state (PID, uptime, idle)
stata-cli daemon restart     # Clean restart (reset Stata state)
stata-cli daemon stop        # Shut down
CommandDescription
daemon startStart the background daemon process
daemon stopGraceful shutdown
daemon stop --allStop all running sessions
daemon statusShow all running sessions (PID, uptime, idle)
daemon restartStop + start (clean Stata state)

Commands auto-route through the daemon when it is running. Use --no-daemon to force direct execution.

The daemon auto-shuts down after 1 hour of inactivity (configurable with --idle-timeout).

Parallel Sessions

Run multiple independent Stata instances — like opening multiple Stata windows:

# Start named sessions
stata-cli --session proj_a daemon start
stata-cli --session proj_b daemon start

# Each session has its own data, estimates, and macros
stata-cli --session proj_a run "use project_a.dta, clear"
stata-cli --session proj_b run "use project_b.dta, clear"

# Route any command to a specific session
stata-cli --session proj_a run "regress price mpg weight"
stata-cli --session proj_b return e

Advanced Usage

Global Options

OptionDescriptionDefault
--stata-path PATHStata installation directoryauto-detected
--edition [mp|se|be]Stata editionmp
--session NAMEDaemon session name (for parallel sessions)default
--compactStrip verbose output noiseoff
--jsonStructured JSON outputoff
--timeout SECONDSExecution timeout600
--max-tokens NMax output tokens (0=unlimited)0
--no-daemonForce direct executionoff
--graphs-dir PATHGraph export directory~/.stata-cli/graphs/
--graph-format [png|svg|pdf]Graph export formatpng
--log PATHSave output to a log fileoff

JSON Output

stata-cli --json run "display 1+1"
{
  "success": true,
  "output": ". display 1+1\n2",
  "error": "",
  "execution_time": 0.04,
  "return_code": 0,
  "extra": {}
}
FieldTypeDescription
successboolWhether the command succeeded
outputstringStata output text
errorstringError message (if any)
execution_timefloatSeconds elapsed
return_codeintStata r-code (0 = ok)
extradictMay contain graphs list with exported file paths

Graph Export

When Stata code creates graphs, they are automatically detected and exported as PNG:

stata-cli run "sysuse auto, clear
scatter price mpg"
[graph] graph1: /Users/you/.stata-cli/graphs/exec-.../graph1.png

In JSON mode, graph paths appear under extra.graphs.

Token Limit Management

For long outputs, use --max-tokens to truncate and save the full output to a file:

stata-cli --max-tokens 500 run "sysuse auto, clear
describe"

When output exceeds the limit, a preview is shown with a path to the full saved output.

Environment Variables

VariableDescription
STATA_PATHOverride Stata installation path
STATA_CLI_GRAPHS_DIROverride graph export directory

Exit Codes

CodeMeaning
0Success
1Stata command error
2CLI usage error
3Stata not found / init failure

Agent Usage Pattern

# Full analysis workflow
stata-cli run "sysuse auto, clear
summarize price mpg
regress price mpg weight
predict yhat
list make price yhat in 1/5"

# Retrieve regression results as structured JSON
stata-cli return e

# Get coefficient matrix
stata-cli matrix e(b)

# Inspect variable metadata
stata-cli vars price mpg weight

# Check value labels
stata-cli labels --var foreign

# Read system macros
stata-cli macro get "c(N)"

# Check data after loading
stata-cli data --if "price>10000"

# Lookup command syntax
stata-cli help anova

# Compact mode for less noise
stata-cli --compact run "sysuse auto, clear
describe"

# JSON mode for structured parsing
stata-cli --json run "display 1+1"

# Export graph as SVG
stata-cli --graph-format svg run "scatter price mpg"

Contributing

Community contributions are welcome! If you find a bug or have feature suggestions, please submit an Issue or Pull Request.

For major changes, we recommend discussing with us first via an Issue.

License

This project is licensed under the MIT License.

Files in the repo

Repository payload10 top-level entries
  • assets
  • bin
  • docs
  • src
  • .gitignore
  • CHANGELOG.md
  • package.json
  • pyproject.toml
  • README.md
  • SKILL.md

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More tools

JuliusBrussee/
caveman

🪨 why use many token when few token do trick — Claude Code skill that cuts 65% of tokens by talking like caveman

105k
1 add
MemPalace/
mempalace

The best-benchmarked open-source AI memory system. And it's free.

59k
stablyai/
orca

Orca is the ADE for working with a fleet of parallel agents. Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

66k

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

132k

Never stop coding. Free MIT AI gateway: one endpoint, 352 providers (150+ free), 1200+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 550+ contributors

64k
headroomlabs-ai/
headroom

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

71k