stata-ai-fusion
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Why Stata AI Fusion?
Stata is one of the most widely used statistical packages in economics, political science, epidemiology, and biostatistics. Yet while R and Python users have enjoyed deep AI integration for years, Stata has remained isolated from the AI-assisted coding revolution.
stata-ai-fusion bridges that gap. It gives AI assistants (Claude, Cursor, GitHub Copilot, and others) the ability to start a real Stata session, run commands, inspect data, extract estimation results, and capture graphs -- all through the open Model Context Protocol (MCP).
The project ships as three complementary components so every workflow is covered:
Component | What it does | Who it's for |
MCP Server | 11 tools that let any MCP-compatible AI execute Stata | Claude Desktop, Claude Code, Cursor users |
Skill Knowledge Base | 5,653 lines of Stata expertise the AI can consult | Claude.ai Project / Skill users |
VS Code Extension | Syntax highlighting, snippets, run-in-terminal | Anyone writing |
Related MCP server: Stata Executor MCP
Architecture
The data flow is straightforward:
AI Assistant sends a tool call (e.g.
stata_run_command) via MCP.MCP Server dispatches the request to the Session Manager, which maintains one or more persistent, interactive Stata processes.
Stata executes the command; the server captures output, strips SMCL markup, detects errors, and auto-exports any new graphs.
The cleaned result (text + optional base64 image) flows back to the AI, which interprets it and responds to the user.
Quick Start
Claude Code (recommended)
# Register the MCP server in one command
claude mcp add stata-ai-fusion -- uvx --from stata-ai-fusion stata-ai-fusion
# Verify
claude mcp listThen try:
> Load the auto dataset in Stata and regress price on mpg and weight with robust SEClaude Desktop
Edit your config file:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"stata": {
"command": "uvx",
"args": ["--from", "stata-ai-fusion", "stata-ai-fusion"]
}
}
}Restart Claude Desktop. The Stata tools will appear in the tool list.
Cursor / VS Code (MCP)
Create .cursor/mcp.json or .vscode/mcp.json in your project root:
{
"servers": {
"stata": {
"command": "uvx",
"args": ["--from", "stata-ai-fusion", "stata-ai-fusion"]
}
}
}Claude.ai (Skill Only)
This mode provides code-generation guidance only (no live Stata execution).
Download
stata-ai-fusion-skill.zipfrom the Releases page.Go to Claude.ai > Project > Project Knowledge > Upload.
Upload the zip file.
The AI will now reference the 5,653-line knowledge base when writing Stata code for you.
VS Code Extension
# Option 1: VS Code Marketplace
# Search "Stata AI Fusion" in the Extensions panel
# Option 2: From GitHub Release
code --install-extension stata-ai-fusion-0.3.0.vsix
# Option 3: Cursor
cursor --install-extension stata-ai-fusion-0.3.0.vsixFeatures
MCP Server -- 11 tools for AI-driven analysis
The server exposes 11 MCP tools. Each tool can be called by any MCP-compatible AI assistant.
Conversation Example
User: "Analyze the determinants of car prices in the auto dataset."
AI calls: stata_run_command("sysuse auto, clear")
AI calls: stata_inspect_data() -> 74 obs, 12 variables
AI calls: stata_run_command("regress price mpg weight foreign, robust")
AI calls: stata_get_results("e", "N,r2,F") -> N=74, R²=0.52, F=29.1
AI calls: stata_run_command("scatter price mpg || lfit price mpg")
AI calls: stata_export_graph(format="png") -> [base64 image]
AI: "The regression shows that each additional mile per gallon is associated
with a $49.50 decrease in price, controlling for weight and origin..."Skill Knowledge Base -- 5,653 lines of Stata expertise
The knowledge base uses a Progressive Disclosure architecture:
SKILL.md (486 lines) serves as the entry-point router.
14 reference files cover specific domains; the AI loads them on demand.
The AI never reads all 5,653 lines at once -- it fetches only what the current task requires.
VS Code Extension -- complete Stata IDE
Feature | Shortcut | Description |
Run Selection |
| Execute selected Stata code in the terminal |
Run File |
| Execute the entire |
Syntax Highlighting | -- | 25 grammar scopes covering commands, functions, macros |
Code Snippets |
| 30 snippets ( |
Graph Preview | -- | View Stata graphs inside VS Code |
Auto MCP Config | -- | Auto-generate |
MCP Tools Reference
Tool | Description | Example |
| Execute short ad-hoc Stata commands interactively |
|
| Run a |
|
| Describe the current dataset in memory | Returns obs count, variable names, types, labels |
| Generate codebook for specific variables |
|
| Extract stored results (r/e/c class) |
|
| Export current graph as PNG/SVG/PDF | Returns base64-encoded image data |
| Search through the Stata session log |
|
| Install SSC or user-written packages |
|
| Send interrupt (SIGINT) to cancel a running command |
|
| List all active Stata sessions | Returns session IDs, types, alive status |
| Close a specific Stata session |
|
Skill Knowledge Base
Reference | Lines | Coverage |
| 564 | Commands, data types, operators, macros |
| 481 | merge, reshape, append, collapse, encode |
| 412 | OLS, IV, panel data, GMM, quantile regression |
| 433 | DiD, RDD, synthetic control, IPW, event study |
| 332 | stset, stcox, streg, competing risks, KM curves |
| 497 | MIMIC-IV, ICD-9/10, KDIGO, Sepsis-3, LOS |
| 463 | twoway, graph options, schemes, export |
| 348 | esttab, putdocx, collect, LaTeX/Word output |
| 349 | Common Stata errors with causes and fixes |
| 389 | assert, capture, confirm, isid, tempfiles |
| 532 | Mata programming, matrices, optimization |
| 127 | High-dimensional fixed effects regression |
| 133 | Coefficient and event-study plots |
| 107 | Fast data operations (gcollapse, gegen) |
Total | 5,653 |
Configuration
Variable | Default | Description |
| Auto-detect | Full path to the Stata executable |
|
| Logging level ( |
| System temp | Base directory for session temporary files |
Stata Auto-Discovery
The server automatically detects your Stata installation using a three-tier strategy:
Environment variable --
STATA_PATHtakes highest priority.Standard paths --
macOS:
/Applications/Stata*/,/Applications/StataNow/Linux:
/usr/local/stata*/,/usr/local/bin/Windows:
C:\Program Files\Stata*\
System PATH --
which stata-mp,which stata-se,which stata
Supported editions: MP, SE, IC, BE (Stata 17, 18, 19 and StataNow).
If auto-detection fails, set the environment variable explicitly:
export STATA_PATH="/Applications/Stata/StataMP.app/Contents/MacOS/stata-mp"Multi-Session Support
The server supports multiple concurrent Stata sessions with complete data isolation:
Each session maintains its own dataset, variables, and estimation results.
Sessions persist between tool calls -- no need to reload data after every command.
A default session is created automatically; create named sessions for parallel workflows.
Idle sessions are automatically cleaned up after 1 hour (configurable).
All sessions are cleaned up gracefully on server shutdown.
AI calls: stata_run_command(code="sysuse auto, clear", session_id="session_A")
AI calls: stata_run_command(code="sysuse nlsw88, clear", session_id="session_B")
# session_A has 74 obs (auto), session_B has 2,246 obs (nlsw88)Troubleshooting
The server searches for Stata in three places (see Stata Auto-Discovery). If none work, you'll see:
StataNotFoundError: No Stata installation foundFix it:
Find your Stata executable manually:
# macOS find /Applications -name "stata-mp" -o -name "stata-se" -o -name "stata" 2>/dev/null # Linux which stata-mp || which stata-se || which stata # Windows (PowerShell) Get-ChildItem "C:\Program Files\Stata*" -Recurse -Filter "Stata*.exe" | Select-Object FullNameSet the path explicitly:
# macOS / Linux export STATA_PATH="/Applications/Stata/StataMP.app/Contents/MacOS/stata-mp" # Windows (PowerShell) $env:STATA_PATH = "C:\Program Files\Stata18\StataMP-64.exe"For Claude Code, add it to your MCP config:
{ "env": { "STATA_PATH": "/path/to/your/stata" } }
Common pitfalls:
On macOS, point to the binary inside the
.appbundle, not the.appitselfOn Windows, use the full path including
-64suffix for 64-bit editionsStataNow uses different binary names — check
Contents/MacOS/for the exact name
pexpect is the library that drives Stata's interactive console. Issues appear as:
ModuleNotFoundError: No module named 'pexpect'
# or
pexpect.exceptions.ExceptionPexpect: The command was not found ...Fix it:
# If using uv (recommended)
uv pip install pexpect
# If using pip
pip install pexpectWindows users: pexpect has limited Windows support. The server uses pexpect.popen_spawn on Windows, which works but has some limitations:
No pseudo-terminal (PTY), so some Stata output formatting may differ
morepagination must be disabled (the server handles this automatically)If you encounter issues, try running from WSL2 instead
Symptom: Claude Code or Cursor shows "MCP server failed to start" or the Stata tools don't appear.
Step 1 — Test the server standalone:
# Should print tool list and wait for input
uv run stata-ai-fusionIf this fails, check the error message:
StataNotFoundError→ see Stata not found aboveModuleNotFoundError→ install missing dependency:uv pip install stata-ai-fusionAddress already in use→ another instance is running; kill it first
Step 2 — Check your MCP configuration:
For Claude Code (~/.claude/settings.json or project .claude/settings.json):
{
"mcpServers": {
"stata-ai-fusion": {
"command": "uvx",
"args": ["stata-ai-fusion"]
}
}
}For Cursor (.cursor/mcp.json):
{
"mcpServers": {
"stata-ai-fusion": {
"command": "uvx",
"args": ["stata-ai-fusion"]
}
}
}Step 3 — Enable debug logging:
export MCP_STATA_LOGLEVEL=DEBUG
uv run stata-ai-fusionThis shows every Stata interaction, including discovery, session creation, and command execution.
Path separators:
Always use forward slashes or raw strings in STATA_PATH:
# PowerShell
$env:STATA_PATH = "C:/Program Files/Stata18/StataMP-64.exe"
# or
$env:STATA_PATH = "C:\Program Files\Stata18\StataMP-64.exe"Stata edition detection on Windows:
The server checks the Windows registry under HKEY_LOCAL_MACHINE\SOFTWARE\StataCorpLP and HKEY_CURRENT_USER\SOFTWARE\StataCorpLP for installed editions. If your registry entries are non-standard (e.g., portable install), set STATA_PATH manually.
Long path issues: If your project path exceeds 260 characters, enable long path support:
# Run as Administrator
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" `
-Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -ForceAntivirus interference:
Some antivirus software blocks pexpect from spawning Stata. Add your Stata directory and Python environment to the exclusion list if the server hangs on "Creating session."
Why it happens: Idle sessions are automatically cleaned up after 1 hour to free system resources. If your AI conversation pauses for a long time and then resumes, the session may have been closed.
Fix it:
Simply run another command — the server auto-creates a new default session
If you need a specific named session: pass a
session_idto any tool (sessions are created on demand)For long-running batch jobs, use
stata_run_do_file— it always runs in batch mode, designed for extended execution
Tip: You can check active sessions at any time by asking the AI to call stata_list_sessions.
By design, the server truncates very large outputs to stay within AI context window limits:
Head: first 3,000 characters
Tail: last 5,000 characters
Inline graphs: up to 5 per
stata_run_command, 3 perstata_run_do_file
For large outputs, use stata_run_do_file — it runs in batch mode, capturing all output to a log file and returning a summary instead of the full text.
For graphs, use stata_export_graph to save specific graphs to files at full resolution rather than relying on inline preview.
Development
# Clone and set up
git clone https://github.com/haoyu-haoyu/stata-ai-fusion.git
cd stata-ai-fusion
uv sync
# Run unit tests (no Stata required)
uv run pytest tests/test_discovery.py -v
# Run integration tests (requires Stata)
uv run pytest tests/test_integration.py -v
# Build Python package
uv build
# Build VS Code extension
cd vscode-extension && npm install && npm run buildTesting
Test Suite | Count | Requires Stata |
Unit tests (discovery, result/matrix parsing, injection, ReDoS, graph, …) | 118 | No |
| 52 | Yes |
Total | 170 |
The 118 unit tests run without Stata; all 170 pass on Stata MP 19 (macOS arm64).
Project Structure
stata-ai-fusion/
├── src/stata_ai_fusion/
│ ├── __main__.py # CLI entry point
│ ├── server.py # MCP server + resource registration
│ ├── stata_discovery.py # Auto-detect Stata installation
│ ├── stata_session.py # Interactive & batch session manager
│ ├── graph_cache.py # Graph capture and base64 encoding
│ ├── result_extractor.py # r()/e()/c() result extraction
│ └── tools/ # 11 MCP tool implementations
├── skill/
│ ├── SKILL.md # Main skill routing document (486 lines)
│ └── references/ # 14 reference documents (5,167 lines)
├── vscode-extension/
│ ├── src/ # TypeScript extension source (5 files)
│ ├── syntaxes/ # TextMate grammar
│ └── snippets/ # 30 code snippets
├── tests/ # 170 tests (118 unit + 52 integration)
├── assets/ # Icon, architecture diagrams
└── pyproject.tomlContributing
Contributions are welcome! Here are some ways to help:
Bug reports: Open an issue describing the problem, your Stata version, and OS.
New Skill references: Add a
.mdfile toskill/references/covering a Stata topic.New MCP tools: Implement a tool in
src/stata_ai_fusion/tools/and register it.VS Code improvements: Expand syntax grammar or add snippets.
Please run uv run pytest tests/ -v before submitting a PR.
License
MIT -- see LICENSE for details.
Acknowledgments
Stata by StataCorp
Model Context Protocol by Anthropic
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
Persistent file storage for AI agents via MCP and curl. Upload, download, and version files.
OCR, transcription, file extraction, and image generation for AI agents via MCP.
214 tools for AI agents over one MCP endpoint: image, video, audio, 3D, data, storage, mail, GPUs.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceConnects AI agents to a local Stata installation, enabling execution of Stata code, data inspection, graph generation, and result verification through natural language interactions.941 PyPI92AGPL 3.0
- FlicenseNot gradedqualityDmaintenanceEnables an agent to execute Stata do scripts or inline commands locally and retrieve structured results including status, error diagnostics, and output text for consumption by the model.1-
- AlicenseNot gradedqualityCmaintenanceMCP server that enables Claude to directly drive Stata, providing a persistent session and 75 tools for data management, estimation, post-estimation, graphs, and export. It lets users perform full Stata analyses through natural language instructions.MIT
- AlicenseAqualityBmaintenanceEnables LLM/agent applications to execute Stata code, load and inspect data, obtain structured regression results and graphs, and manage background tasks through the Model Context Protocol.10MIT