Skip to content
Back to search

mcp-stata

A lightweight Model Context Protocol (MCP) server for Stata. Execute commands, inspect data, retrieve stored results (r()/e()), and view graphs in your chat interface. Built for economists who want to integrate LLM assistance into their Stata workflow.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/tmonk--mcp-stata/badge.svg)](/listings/tmonk--mcp-stata)

HTML

<a href="/listings/tmonk--mcp-stata"><img src="/api/listings/tmonk--mcp-stata/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

1 · Install

macOS/Linux:

curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh | bash

Windows (PowerShell):

irm https://mcp-stata-install.tdmonk.com/install.ps1 | iex

Client-specific examples:

| Client | macOS/Linux | Windows (PowerShell) | |--------|-------------|----------------------| | **Claude Code** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent claude` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent claude` | | **Codex** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent codex` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent codex` | | **Gemini** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent gemini` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent gemini` | | **Cursor** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent cursor` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent cursor` | | **Windsurf** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent windsurf` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent windsurf` | | **VS Code** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent vscode` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent vscode` | | **Auto-detect / default** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh)` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex)))` |

2 · Verify

Ask your agent:

Do you have access to the Stata agentic toolkit? (mcp-stata)

It will confirm the connection and describe all available tools and skills.

3 · Try it

Load the auto dataset and run a regression of price on mpg

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 570 lines · 9 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Stata MCP Server (mcp-stata)
  2. <a href="https://cursor.com/en-US/install-mcp?name=mcp-stata&config=eyJjb21tYW5kIjogInV2eCAtLXJlZnJlc2ggLS1yZWZyZXNoLXBhY2thZ2UgbWNwLXN0YXRhIC0tZnJvbSBtY3Atc3RhdGFAbGF0ZXN0IG1jcC1zdGF0YSJ9"><img src="https://cursor.com/deeplink/mcp-install-dark.svg" alt="Install MCP Server" height="20"></a>&nbsp;
  3. <a href="https://pypi.org/project/mcp-stata/"><img src="https://img.shields.io/pypi/v/mcp-stata?style=flat&color=black" alt="PyPI - Version" height="20"></a>
  4. **mcp-stata** is an agentic toolkit for empirical researchers. It gives AI agents native control over a local Stata installation, allowing agents to run do-files, inspect data, check stored results, and export graphs. Contains a skills catalog for workflows researchers use often: auditing data, replication and robustness checks, specification comparisons, publication QA, referee responses, and modernization of legacy code. Featured in <a href="https://www.stata.com/stata-news/news41-2/community-corner-ai-tools/"><img src="https://raw.githubusercontent.com/tmonk/mcp-stata/refs/heads/main/img/stata.svg" height="10px" alt="Stata" style="vertical-align:middle; margin-top: -5px;"/> News</a>.
  5. > If you'd like a fully integrated VS Code extension to run Stata code without leaving your IDE, and also allow AI agent interaction, check out my other project: [<img src="https://raw.githubusercontent.com/tmonk/stata-workbench/refs/heads/main/img/icon.png" height="12px"> Stata Workbench](https://github.com/tmonk/stata-workbench/).
  6. Built by <a href="https://tdmonk.com">Thomas Monk</a>, London School of Economics.
  7. <!-- mcp-name: io.github.tmonk/mcp-stata -->
  8. This server enables LLMs to:
  9. - **Execute Stata code**: run any Stata command (e.g. `sysuse auto`, `regress price mpg`).
  10. - **Inspect data**: retrieve dataset summaries and variable codebooks.
  11. - **Export graphics**: generate and view Stata graphs (histograms, scatterplots).
  12. - **Streaming graph caching**: automatically cache graphs during command execution for instant exports.
  13. - **Verify results**: programmatically check stored results (`r()`, `e()`) for accurate validation.
  14. - **Drive paper workflows**: run structured research audits, estimation planning, specification comparisons, publication checks, and reproducibility diagnostics.
  15. - **Use modern MCP surfaces**: discover prompts, project/session resources, artifacts, and safety metadata through structured tool envelopes.
  16. ## Quickstart
  17. ### 1 · Install
  18. macOS/Linux:
  19. ```bash
  20. curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 28 on GitHub
  21. ```
  22. Windows (PowerShell):
  23. ```powershell
  24. irm https://mcp-stata-install.tdmonk.com/install.ps1 | iex
  25. ```
  26. Client-specific examples:
  27. | Client | macOS/Linux | Windows (PowerShell) |
  28. |--------|-------------|----------------------|
  29. | **Claude Code** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent claude` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent claude` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 40 on GitHub
  30. | **Codex** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent codex` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent codex` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 41 on GitHub
  31. | **Gemini** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent gemini` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent gemini` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 42 on GitHub
  32. | **Cursor** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent cursor` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent cursor` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 43 on GitHub
  33. | **Windsurf** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent windsurf` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent windsurf` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 44 on GitHub
  34. | **VS Code** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh) --agent vscode` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex))) --agent vscode` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 45 on GitHub
  35. | **Auto-detect / default** | `bash <(curl -LsSf https://mcp-stata-install.tdmonk.com/install.sh)` | `& ([scriptblock]::Create((irm https://mcp-stata-install.tdmonk.com/install.ps1 &#124; iex)))` |
    • Note: Runs a downloaded script through process substitution (bash <(curl …))
    • Line 46 on GitHub
  36. ### 2 · Verify
  37. Ask your agent:
  38. ```
  39. Do you have access to the Stata agentic toolkit? (mcp-stata)
  40. ```
  41. It will confirm the connection and describe all available tools and skills.
  42. ### 3 · Try it
  43. ```
  44. Load the auto dataset and run a regression of price on mpg
  45. ```
  46. ## Academic Research Workflows
  47. The toolkit is designed for empirical economics research.
  48. - Replication and robustness: rerun pipelines, compare specifications, and preserve an audit trail.
  49. - Data audit: check structure, missingness, duplicate identifiers, suspicious coding, and documentation readiness.
  50. - Publication QA: review tables and figures for paper-ready presentation.
  51. - Referee response: organize reruns and evidence for critiques or coauthor requests.
  52. - Environment diagnosis: troubleshoot Stata discovery, package availability, graph export, and managed-machine quirks.
  53. - Safety and diagnostics: diagnose the MCP server, and enforce the safety of code run through the server.
  54. ## Prerequisites
  55. - **Stata 17+** (Stata MP, SE, or BE). Must be licensed and installed locally.
  56. - **Python 3.11+**
  57. - **uv** (recommended)
  58. > **Note on `pystata`**: This server uses the proprietary `pystata` module that is included with your Stata installation. There is a third-party package named `pystata` on PyPI that is **not** the official Stata package and should not be installed. MCP-Stata handles finding and loading the official module from your Stata directory automatically.
  59. ## Run as a published tool with `uvx`
  60. ```bash
  61. uvx --refresh --refresh-package mcp-stata --from mcp-stata@latest mcp-stata
  62. ```
  63. `uvx` is an alias for `uv tool run` and runs the tool in an isolated, cached environment.
  64. ## Configuration
  65. This server attempts to automatically discover your Stata installation (supporting standard paths and StataNow).
  66. If auto-discovery fails, set the `STATA_PATH` environment variable to your Stata executable:
  67. ```bash
  68. # macOS example
  69. export STATA_PATH="/Applications/StataNow/StataMP.app/Contents/MacOS/stata-mp"
  70. # Windows example (cmd.exe)
  71. set STATA_PATH="C:\Program Files\Stata18\StataMP-64.exe"
  72. ```
  73. If you encounter write permission issues with temporary files (common on Windows), you can override the temporary directory location by setting `MCP_STATA_TEMP`:
  74. ```bash
  75. # Example
  76. export MCP_STATA_TEMP="/path/to/writable/temp"
  77. ```
  78. The server will automatically try the following locations in order of preference:
  79. 1. `MCP_STATA_TEMP` environment variable
  80. 2. System temporary directory
  81. 3. `~/.mcp-stata/temp`
  82. 4. Current working directory subdirectory (`.tmp/`)
  83. ### Startup Do Files
  84. When a session starts, MCP-Stata loads startup do files in the same order as native Stata:
  85. 1. **`MCP_STATA_STARTUP_DO_FILE`** (env var) — one or more custom do files, separated by `:` (Unix) or `;` (Windows).
  86. 2. **`sysprofile.do`** — the first one found along the Stata search path.
  87. 3. **`profile.do`** — the first one found along the Stata search path.
  88. The search path mirrors native Stata: Stata install directory, current working directory, then the ado-path (PERSONAL, SITE, PLUS, OLDPLACE, ...). Only the first `sysprofile.do` and first `profile.do` found are executed, matching native Stata behavior. All paths are deduplicated so the same file is never run twice.
  89. If a command clears programs (`clear all`, `clear programs`, or `program drop _all`), MCP-Stata automatically re-executes the startup files so that any programs they defined remain available. To disable this and let `clear all` behave exactly as in native Stata (programs are lost), set:
  90. ```
  91. MCP_STATA_NO_RELOAD_ON_CLEAR=1
  92. ```
  93. If you prefer, add these variables to your MCP config's `env` for any IDE shown below. It's optional and only needed when discovery cannot find Stata.
  94. Optional `env` example (add inside your MCP server entry):
  95. ```json
  96. "env": {
  97. "STATA_PATH": "/Applications/StataNow/StataMP.app/Contents/MacOS/stata-mp",
  98. "MCP_STATA_STARTUP_DO_FILE": "/path/to/my/startup.do",
  99. "MCP_STATA_NO_RELOAD_ON_CLEAR": "1"
  100. }
  101. ```
  102. ## IDE Setup (MCP)
  103. This MCP server uses the **stdio** transport (the IDE launches the process and communicates over stdin/stdout).
  104. ---
  105. ### Claude Desktop
  106. Open Claude Desktop → **Settings** → **Developer** → **Edit Config**.
  107. Config file locations include:
  108. * macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
  109. * Windows: `%APPDATA%\Claude\claude_desktop_config.json`
  110. #### Published tool (uvx)
  111. ```json
  112. {
  113. "mcpServers": {
  114. "mcp-stata": {
  115. "command": "uvx",
  116. "args": [
  117. "--refresh",
  118. "--refresh-package",
  119. "mcp-stata",
  120. "--from",
  121. "mcp-stata@latest",
  122. "mcp-stata"
  123. ]
  124. }
  125. }
  126. }
  127. ```
  128. After editing, fully quit and restart Claude Desktop to reload MCP servers.
  129. ---
  130. ### Cursor
  131. Cursor supports MCP config at:
  132. * Global: `~/.cursor/mcp.json`
  133. * Project: `.cursor/mcp.json`
  134. #### Published tool (uvx)
  135. ```json
  136. {
  137. "mcpServers": {
  138. "mcp-stata": {
  139. "command": "uvx",
  140. "args": [
  141. "--refresh",
  142. "--refresh-package",
  143. "mcp-stata",
  144. "--from",
  145. "mcp-stata@latest",
  146. "mcp-stata"
  147. ]
  148. }
  149. }
  150. }
  151. ```
  152. ---
  153. ### Windsurf
  154. Windsurf supports MCP plugins and also allows manual editing of `mcp_config.json`. After adding/editing a server, use the UI’s refresh so it re-reads the config.
  155. A common location is `~/.codeium/windsurf/mcp_config.json`.
  156. #### Published tool (uvx)
  157. ```json
  158. {
  159. "mcpServers": {
  160. "mcp-stata": {
  161. "command": "uvx",
  162. "args": [
  163. "--refresh",
  164. "--refresh-package",
  165. "mcp-stata",
  166. "--from",
  167. "mcp-stata@latest",
  168. "mcp-stata"
  169. ]
  170. }
  171. }
  172. }
  173. ```
  174. ---
  175. ### Google Antigravity
  176. In Antigravity, MCP servers are managed from the MCP store/menu; you can open **Manage MCP Servers** and then **View raw config** to edit `mcp_config.json`.
  177. #### Published tool (uvx)
  178. ```json
  179. {
  180. "mcpServers": {
  181. "mcp-stata": {
  182. "command": "uvx",
  183. "args": [
  184. "--refresh",
  185. "--refresh-package",
  186. "mcp-stata",
  187. "--from",
  188. "mcp-stata@latest",
  189. "mcp-stata"
  190. ]
  191. }
  192. }
  193. }
  194. ```
  195. ---
  196. ### Visual Studio Code
  197. VS Code supports MCP servers via a `.vscode/mcp.json` file. The top-level key is **`servers`** (not `mcpServers`).
  198. Create `.vscode/mcp.json`:
  199. #### Published tool (uvx)
  200. ```json
  201. {
  202. "servers": {
  203. "mcp-stata": {
  204. "type": "stdio",
  205. "command": "uvx",
  206. "args": [
  207. "--refresh",
  208. "--refresh-package",
  209. "mcp-stata",
  210. "--from",
  211. "mcp-stata@latest",
  212. "mcp-stata"
  213. ]
  214. }
  215. }
  216. }
  217. ```
  218. VS Code documents `.vscode/mcp.json` and the `servers` schema, including `type` and `command`/`args`.
  219. ---
  220. ## Skills Catalog
  221. The toolkit includes a catalog of "Skills", providing domain knowledge to AI agents.
  222. - **Base Skill**: [plugin/skills/stata-toolkit/SKILL.md](plugin/skills/stata-toolkit/SKILL.md) — Main Stata toolkit dispatcher.
  223. - **Modernize Skill**: [plugin/skills/stata-modernize/SKILL.md](plugin/skills/stata-modernize/SKILL.md) — Replaces legacy Stata patterns (i.e. prefer frames over `preserve`, `restore`.)
  224. - **Replication Skill**: [plugin/skills/stata-replication/SKILL.md](plugin/skills/stata-replication/SKILL.md) — Reproducibility and robustness workflows.
  225. - **Data Audit Skill**: [plugin/skills/stata-data-audit/SKILL.md](plugin/skills/stata-data-audit/SKILL.md) — Dataset QA and sanity checks.
  226. - **Publication QA Skill**: [plugin/skills/stata-publication-qa/SKILL.md](plugin/skills/stata-publication-qa/SKILL.md) — Tables and figures for paper readiness.
  227. - **Environment Diagnose Skill**: [plugin/skills/stata-environment-diagnose/SKILL.md](plugin/skills/stata-environment-diagnose/SKILL.md) — Setup and platform troubleshooting.
  228. - Additional plugin skills cover basic causal inference, table building, power analysis, data provenance, and referee-response work.
  229. ## Tools Available (from server.py)
  230. * `stata_run(code, is_file=False, background=False, echo=True, as_json=True, trace=False, raw=False, max_output_lines=None, cwd=None, session_id="default", strip_smcl=True, filter_pattern=None, exclude_pattern=None)`: Execute Stata commands or a `.do` file.
  231. - Set `is_file=True` to treat `code` as an absolute path to a `.do` file.
  232. - Set `background=True` to start long jobs asynchronously (returns `task_id`).
  233. - Always writes output to a temporary log file and emits `notifications/logMessage` containing `{"event":"log_path","path":"..."}`.
  234. - May emit `notifications/progress` when the client provides a progress token/callback.
  235. * `stata_task_status(task_id, wait=False, timeout=60.0, poll_interval=1.0, tail_lines=0)`: Query or wait on background task status.
  236. * `stata_control(action, id)`: Control active work.
  237. - `action="break"` with `id=<session_id>` to interrupt a running session.
  238. - `action="cancel"` with `id=<task_id>` to cancel a background task.
  239. * `stata_read_log(path, offset=0, max_bytes=262144, tail_lines=0, query=None, before=2, after=2, case_sensitive=False, regex=False, max_matches=50)`: Read, tail, or search a log file.
  240. * `stata_load_data(source, clear=True, as_json=True, raw=False, max_output_lines=None, session_id="default")`: Heuristic loader (sysuse/webuse/use/path/URL) for the specified session.
  241. * `stata_inspect_data(action, query=None, variables=None, start=0, count=50, session_id="default")`: Unified data inspector.
  242. - `action`: `describe`, `codebook`, `summary`, `search`, `list`, `get`, or **`lint`**.
  243. - `lint`: performs static analysis of `.do` and `.ado` files for modern best practices.
  244. * `stata_manage_graphs(action, graph_name=None, format="svg", session_id="default")`: Graph management (`list`, `export`, `export_all`).
  245. * `stata_get_results(session_id="default", include_formatting=False, include_matrices=True, matrix_max_rows=200, matrix_max_cols=200, include_mata=False, as_json=True)`: Unified stored-results tool for coherent structured `r()`/`e()`/`s()` payloads with optional structured Mata snapshot.
  246. * `stata_get_help(topic, plain_text=False, merge_paragraphs=True, session_id="default")`: Markdown or plain-text Stata help.
  247. * `stata_manage_session(action, session_id="default", code=None, since_command=None)`: Session lifecycle, state history, and UI channel orchestration.
  248. - `action`: `create`, `stop`, `list`, `set_profile`, `history_diff`, `history_stats`, `get_ui_channel`, or **`detect`**.
  249. - `detect`: Returns metadata about the Stata installation (version, flavor, OS) and optionally SSC packages.
  250. - `history_diff` returns tracked changes in variables/macros and dataset dimensions.
  251. - `history_stats` returns retained window metadata (`history_size`, `earliest_command`, `latest_command`, `max_history_entries`).
  252. ### Common action examples
  253. ```python
  254. # Session lifecycle
  255. stata_manage_session(action="create", session_id="analysis")
  256. stata_manage_session(action="list")
  257. stata_manage_session(action="stop", session_id="analysis")
  258. # Session history tracking
  259. stata_manage_session(action="history_stats", session_id="analysis")
  260. stata_manage_session(action="history_diff", session_id="analysis")
  261. stata_manage_session(action="history_diff", session_id="analysis", since_command=42)
  262. # Run a do-file (replacement for run_do_file)
  263. stata_run("/path/to/analysis.do", is_file=True, session_id="analysis")
  264. # Data inspection (describe, codebook, variable list)
  265. stata_inspect_data(action="describe", session_id="analysis")
  266. stata_inspect_data(action="codebook", query="price", session_id="analysis")
  267. stata_inspect_data(action="list", session_id="analysis")
  268. # Graph operations
  269. stata_manage_graphs(action="list", session_id="analysis")
  270. stata_manage_graphs(action="export", graph_name="Graph", format="png", session_id="analysis")
  271. stata_manage_graphs(action="export_all", session_id="analysis")
  272. # Help and stored results
  273. stata_get_help(topic="regress", session_id="analysis")
  274. stata_get_results(session_id="analysis", include_mata=True)
  275. # UI data browser channel
  276. stata_manage_session(action="get_ui_channel", session_id="analysis")
  277. # Interrupt / cancel / background status
  278. stata_control(action="break", id="analysis")
  279. stata_run("quietly do /path/to/long_job.do", background=True, session_id="analysis")
  280. stata_task_status(task_id="...", wait=True, timeout=30)
  281. stata_control(action="cancel", id="...")
  282. ```
  283. ### Cancellation
  284. - Clients may cancel an in-flight request by sending the MCP notification `notifications/cancelled` with `params.requestId` set to the original tool call ID.
  285. - Client guidance:
  286. 1. Pass a `_meta.progressToken` when invoking the tool if you want progress updates (optional).
  287. 2. If you need to cancel, send `notifications/cancelled` with the same requestId. You may also stop tailing the log file path once you receive cancellation confirmation (the tool call will return an error indicating cancellation).
  288. 3. Be prepared for partial output in the log file; cancellation is best-effort and depends on Stata surfacing `BreakError`.
  289. ### Output and results behavior
  290. - `stata_run` defaults to `strip_smcl=True`, so responses are plain-text oriented unless you explicitly disable stripping.
  291. - `stata_get_results` returns structured stored results and can include Mata state (`include_mata=True`) with typed object/function payloads suitable for downstream programmatic checks.
  292. Resources exposed for MCP clients:
  293. * `stata://data/summary` → `summarize`
  294. * `stata://data/metadata` → `describe`
  295. * `stata://graphs/list` → graph list (resource handler delegates to `stata_manage_graphs(action="list")`)
  296. * `stata://variables/list` → variable list (resource wrapper)
  297. * `stata://results/stored` → stored `r()`/`e()`/`s()` results
  298. ## UI-only Data Browser (Local HTTP API)
  299. This server also hosts a **localhost-only HTTP API** intended for a VS Code extension UI to browse data at high volume (paging, filtering) without sending large payloads over MCP.
  300. Important properties:
  301. - **Loopback only**: binds to `127.0.0.1`.
  302. - **Bearer auth**: every request requires an `Authorization: Bearer <token>` header.
  303. - **Short-lived tokens**: clients should call `stata_manage_session(action="get_ui_channel")` to obtain a fresh token as needed.
  304. - **Session Isolate**: caches (views, sorting) are isolated per `sessionId`.
  305. - **No Stata dataset mutation** for browsing/filtering:
  306. - No generated variables.
  307. - Paging uses `sfi.Data.get`.
  308. - Filtering is evaluated in Python over chunked reads.
  309. ### Discovery via MCP (`stata_manage_session`)
  310. Call the MCP tool `stata_manage_session(action="get_ui_channel")` and parse the JSON:
  311. ```json
  312. {
  313. "baseUrl": "http://127.0.0.1:53741",
  314. "token": "...",
  315. "expiresAt": 1730000000,
  316. "capabilities": {
  317. "dataBrowser": true,
  318. "filtering": true,
  319. "sorting": true,
  320. "arrowStream": true
  321. }
  322. }
  323. ```
  324. Server-enforced limits (current defaults):
  325. - **maxLimit**: 500
  326. - **maxVars**: 32,767
  327. - **maxChars**: 500
  328. - **maxRequestBytes**: 1,000,000
  329. - **maxArrowLimit**: 1,000,000 (specific to `/v1/arrow`)
  330. ### Endpoints
  331. All endpoints are under `baseUrl` and require the bearer token.
  332. - `GET /v1/dataset?sessionId=default`
  333. - Returns dataset identity and basic state (`id`, `frame`, `n`, `k`) for the given session.
  334. - `GET /v1/vars?sessionId=default`
  335. - Returns full variable list with labels, types, and formats.
  336. - `POST /v1/page`
  337. - Paged data retrieval. Supports `sortBy`, `filterExpr` (ephemeral), and `sessionId`.
  338. - `POST /v1/arrow`
  339. - Returns a binary Arrow IPC stream (same input as `/v1/page`).
  340. - `POST /v1/views`
  341. - Create a long-lived filtered view. Returns a `viewId`. Requires `sessionId`.
  342. - `POST /v1/views/<viewId>/page`
  343. - Paged retrieval from a previously created view. Supports `sortBy` and `sessionId`.
  344. - `POST /v1/views/:viewId/arrow`
  345. - Returns a binary Arrow IPC stream from a filtered view.
  346. - `DELETE /v1/views/:viewId`
  347. - Deletes a view handle.
  348. - `POST /v1/filters/validate`
  349. - Validates a filter expression.
  350. ### Paging request example
  351. ```bash
  352. curl -sS \
  353. -H "Authorization: Bearer $TOKEN" \
  354. -H "Content-Type: application/json" \
  355. -d '{"datasetId":"...","frame":"default","offset":0,"limit":50,"vars":["price","mpg"],"includeObsNo":true,"maxChars":200}' \
  356. "$BASE_URL/v1/page"
  357. ```
  358. #### Sorting
  359. The `/v1/page` and `/v1/views/:viewId/page` endpoints support sorting via the optional `sortBy` parameter:
  360. ```bash
  361. # Sort by price ascending
  362. curl -sS \
  363. -H "Authorization: Bearer $TOKEN" \
  364. -H "Content-Type: application/json" \
  365. -d '{"datasetId":"...","offset":0,"limit":50,"vars":["price","mpg"],"sortBy":["price"]}' \
  366. "$BASE_URL/v1/page"
  367. # Sort by price descending
  368. curl -sS \
  369. -H "Authorization: Bearer $TOKEN" \
  370. -H "Content-Type: application/json" \
  371. -d '{"datasetId":"...","offset":0,"limit":50,"vars":["price","mpg"],"sortBy":["-price"]}' \
  372. "$BASE_URL/v1/page"
  373. # Multi-variable sort: foreign ascending, then price descending
  374. curl -sS \
  375. -H "Authorization: Bearer $TOKEN" \
  376. -H "Content-Type: application/json" \
  377. -d '{"datasetId":"...","offset":0,"limit":50,"vars":["foreign","price","mpg"],"sortBy":["foreign","-price"]}' \
  378. "$BASE_URL/v1/page"
  379. ```
  380. **Sort specification format:**
  381. - `sortBy` is an array of strings (variable names with optional prefix)
  382. - No prefix or `+` prefix = ascending order (e.g., `"price"` or `"+price"`)
  383. - `-` prefix = descending order (e.g., `"-price"`)
  384. - Multiple variables are supported for multi-level sorting
  385. - Uses the native Rust sorter when available, with a Polars fallback
  386. **Sorting with filtered views:**
  387. - Sorting is fully supported with filtered views
  388. - The sort is computed in-memory over the sort columns, then filtered indices are re-applied
  389. - Example: Filter for `price < 5000`, then sort descending by price
  390. ```bash
  391. # Create a filtered view
  392. curl -sS \
  393. -H "Authorization: Bearer $TOKEN" \
  394. -H "Content-Type: application/json" \
  395. -d '{"datasetId":"...","frame":"default","filterExpr":"price < 5000"}' \
  396. "$BASE_URL/v1/views"
  397. # Returns: {"view": {"id": "view_abc123", "filteredN": 37}}
  398. # Get sorted page from filtered view
  399. curl -sS \
  400. -H "Authorization: Bearer $TOKEN" \
  401. -H "Content-Type: application/json" \
  402. -d '{"offset":0,"limit":50,"vars":["price","mpg"],"sortBy":["-price"]}' \
  403. "$BASE_URL/v1/views/view_abc123/page"
  404. ```
  405. Notes:
  406. - `datasetId` is used for cache invalidation. If the dataset changes due to running Stata commands, the server will report a new dataset id and view handles become invalid.
  407. - Filter expressions are evaluated in Python using values read from Stata via `sfi.Data.get`. Use boolean operators like `==`, `!=`, `<`, `>`, and `and`/`or` (Stata-style `&`/`|` are also accepted).
  408. - Sorting does **not** mutate the dataset order in Stata; it computes sorted indices for the response and caches them for subsequent requests.
  409. - The Rust sorter is the primary implementation; Polars is used only as a fallback when the native extension is unavailable.
  410. ## License
  411. This project is licensed under the GNU Affero General Public License v3.0 or later.
  412. See the LICENSE file for the full text.
  413. ## Error reporting
  414. - All tools that execute Stata commands support JSON envelopes (`as_json=true`) carrying:
  415. - `rc` (from r()/c(rc)), `stdout`, `stderr`, `message`, optional `line` (when Stata reports it), `command`, optional `log_path` (for log-file streaming), and a `snippet` excerpt of error output.
  416. - Stata-specific cues are preserved:
  417. - `r(XXX)` codes are parsed when present in output.
  418. - “Red text” is captured via stderr where available.
  419. - `trace=true` adds `set trace on` around the command/do-file to surface program-defined errors; the trace is turned off afterward.
  420. ## Logging
  421. Set `MCP_STATA_LOGLEVEL` (e.g., `DEBUG`, `INFO`) to control server logging. Logs include discovery details (edition/path) and command-init traces for easier troubleshooting.
  422. ## Development & Contributing
  423. For detailed information on building, testing, and contributing to this project, see [CONTRIBUTING.md](CONTRIBUTING.md).
  424. Quick setup:
  425. ```bash
  426. # Install dependencies
  427. uv sync --extra dev --no-install-project
  428. # Run tests (requires Stata)
  429. pytest
  430. # Run tests without Stata
  431. pytest -v -m "not requires_stata"
  432. # Build the package
  433. python -m build
  434. ```
  435. [![Tests](https://github.com/tmonk/mcp-stata/actions/workflows/build-test.yml/badge.svg)](https://github.com/tmonk/mcp-stata/actions/workflows/build-test.yml)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.