mcp-stata 1.20.0__cp311-abi3-macosx_11_0_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mcp-stata might be problematic. Click here for more details.

mcp_stata/server.py ADDED
@@ -0,0 +1,1148 @@
1
+ from __future__ import annotations
2
+ import anyio
3
+ import asyncio
4
+ from dataclasses import dataclass
5
+ from datetime import datetime
6
+ from importlib.metadata import PackageNotFoundError, version
7
+ from mcp.server.fastmcp import Context, FastMCP
8
+ from mcp.server.fastmcp.utilities import logging as fastmcp_logging
9
+ import mcp.types as types
10
+ from .stata_client import StataClient
11
+ from .models import (
12
+ DataResponse,
13
+ GraphListResponse,
14
+ VariablesResponse,
15
+ GraphExportResponse,
16
+ )
17
+ import logging
18
+ import sys
19
+ import json
20
+ import os
21
+ import re
22
+ import traceback
23
+ import uuid
24
+ from functools import wraps
25
+ from typing import Optional, Dict
26
+
27
+ from .ui_http import UIChannelManager
28
+
29
+
30
+ # Configure logging
31
+ logger = logging.getLogger("mcp_stata")
32
+ payload_logger = logging.getLogger("mcp_stata.payloads")
33
+ _LOGGING_CONFIGURED = False
34
+
35
+ def get_server_version() -> str:
36
+ """Determine the server version from package metadata or fallback."""
37
+ try:
38
+ return version("mcp-stata")
39
+ except PackageNotFoundError:
40
+ # If not installed, try to find version in pyproject.toml near this file
41
+ try:
42
+ # We are in src/mcp_stata/server.py, pyproject.toml is at ../../pyproject.toml
43
+ base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
44
+ pyproject_path = os.path.join(base_dir, "pyproject.toml")
45
+ if os.path.exists(pyproject_path):
46
+ with open(pyproject_path, "r") as f:
47
+ import re
48
+ content = f.read()
49
+ match = re.search(r'^version\s*=\s*["\']([^"\']+)["\']', content, re.MULTILINE)
50
+ if match:
51
+ return match.group(1)
52
+ except Exception:
53
+ pass
54
+ return "unknown"
55
+
56
+ SERVER_VERSION = get_server_version()
57
+
58
+ def setup_logging():
59
+ global _LOGGING_CONFIGURED
60
+ if _LOGGING_CONFIGURED:
61
+ return
62
+ _LOGGING_CONFIGURED = True
63
+ log_level = os.getenv("MCP_STATA_LOGLEVEL", "DEBUG").upper()
64
+ app_handler = logging.StreamHandler(sys.stderr)
65
+ app_handler.setLevel(getattr(logging, log_level, logging.DEBUG))
66
+ app_handler.setFormatter(logging.Formatter("[%(name)s] %(levelname)s: %(message)s"))
67
+
68
+ mcp_handler = logging.StreamHandler(sys.stderr)
69
+ mcp_handler.setLevel(getattr(logging, log_level, logging.DEBUG))
70
+ mcp_handler.setFormatter(logging.Formatter("[%(name)s] %(levelname)s: %(message)s"))
71
+
72
+ payload_handler = logging.StreamHandler(sys.stderr)
73
+ payload_handler.setLevel(getattr(logging, log_level, logging.DEBUG))
74
+ payload_handler.setFormatter(logging.Formatter("[%(name)s] %(levelname)s: %(message)s"))
75
+
76
+ root_logger = logging.getLogger()
77
+ root_logger.handlers = []
78
+ root_logger.setLevel(logging.WARNING)
79
+
80
+ for name, item in logging.root.manager.loggerDict.items():
81
+ if not isinstance(item, logging.Logger):
82
+ continue
83
+ item.handlers = []
84
+ item.propagate = False
85
+ if item.level == logging.NOTSET:
86
+ item.setLevel(getattr(logging, log_level, logging.DEBUG))
87
+
88
+ logger.handlers = [app_handler]
89
+ logger.propagate = False
90
+
91
+ payload_logger.handlers = [payload_handler]
92
+ payload_logger.propagate = False
93
+
94
+ mcp_logger = logging.getLogger("mcp.server")
95
+ mcp_logger.handlers = [mcp_handler]
96
+ mcp_logger.propagate = False
97
+ mcp_logger.setLevel(getattr(logging, log_level, logging.DEBUG))
98
+
99
+ mcp_lowlevel = logging.getLogger("mcp.server.lowlevel.server")
100
+ mcp_lowlevel.handlers = [mcp_handler]
101
+ mcp_lowlevel.propagate = False
102
+ mcp_lowlevel.setLevel(getattr(logging, log_level, logging.DEBUG))
103
+
104
+ mcp_root = logging.getLogger("mcp")
105
+ mcp_root.handlers = [mcp_handler]
106
+ mcp_root.propagate = False
107
+ mcp_root.setLevel(getattr(logging, log_level, logging.DEBUG))
108
+ if logger.level == logging.NOTSET:
109
+ logger.setLevel(getattr(logging, log_level, logging.DEBUG))
110
+
111
+ logger.info("=== mcp-stata server starting ===")
112
+ logger.info("mcp-stata version: %s", SERVER_VERSION)
113
+ logger.info("STATA_PATH env at startup: %s", os.getenv("STATA_PATH", "<not set>"))
114
+ logger.info("LOG_LEVEL: %s", log_level)
115
+
116
+
117
+
118
+ # Initialize FastMCP
119
+ mcp = FastMCP("mcp_stata")
120
+ # Set version on the underlying server to expose it in InitializeResult
121
+ mcp._mcp_server.version = SERVER_VERSION
122
+
123
+ client = StataClient()
124
+ ui_channel = UIChannelManager(client)
125
+
126
+
127
+ @dataclass
128
+ class BackgroundTask:
129
+ task_id: str
130
+ kind: str
131
+ task: asyncio.Task
132
+ created_at: datetime
133
+ log_path: Optional[str] = None
134
+ result: Optional[str] = None
135
+ error: Optional[str] = None
136
+ done: bool = False
137
+
138
+
139
+ _background_tasks: Dict[str, BackgroundTask] = {}
140
+ _request_log_paths: Dict[str, str] = {}
141
+ _read_log_paths: set[str] = set()
142
+ _read_log_offsets: Dict[str, int] = {}
143
+
144
+
145
+ def _register_task(task_info: BackgroundTask, max_tasks: int = 100) -> None:
146
+ _background_tasks[task_info.task_id] = task_info
147
+ if len(_background_tasks) <= max_tasks:
148
+ return
149
+ completed = [task for task in _background_tasks.values() if task.done]
150
+ completed.sort(key=lambda item: item.created_at)
151
+ for task in completed[: max(0, len(_background_tasks) - max_tasks)]:
152
+ _background_tasks.pop(task.task_id, None)
153
+
154
+
155
+ def _format_command_result(result, raw: bool, as_json: bool) -> str:
156
+ if raw:
157
+ if result.success:
158
+ return result.log_path or ""
159
+ if result.error:
160
+ msg = result.error.message
161
+ if result.error.rc is not None:
162
+ msg = f"{msg}\nrc={result.error.rc}"
163
+ return msg
164
+ return result.log_path or ""
165
+ if as_json:
166
+ return result.model_dump_json()
167
+ return result.model_dump_json()
168
+
169
+
170
+ async def _wait_for_log_path(task_info: BackgroundTask) -> None:
171
+ while task_info.log_path is None and not task_info.done:
172
+ await anyio.sleep(0.01)
173
+
174
+
175
+ async def _notify_task_done(session: object | None, task_info: BackgroundTask, request_id: object | None) -> None:
176
+ if session is None:
177
+ return
178
+ payload = {
179
+ "event": "task_done",
180
+ "task_id": task_info.task_id,
181
+ "status": "done" if task_info.done else "unknown",
182
+ "log_path": task_info.log_path,
183
+ "error": task_info.error,
184
+ }
185
+ try:
186
+ await session.send_log_message(level="info", data=json.dumps(payload), related_request_id=request_id)
187
+ except Exception:
188
+ return
189
+
190
+
191
+ def _debug_notification(kind: str, payload: object, request_id: object | None = None) -> None:
192
+ try:
193
+ serialized = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False)
194
+ except Exception:
195
+ serialized = str(payload)
196
+ payload_logger.info("MCP notify %s request_id=%s payload=%s", kind, request_id, serialized)
197
+
198
+
199
+ async def _notify_tool_error(ctx: Context | None, tool_name: str, exc: Exception) -> None:
200
+ if ctx is None:
201
+ return
202
+ session = ctx.request_context.session
203
+ if session is None:
204
+ return
205
+ task_id = None
206
+ meta = ctx.request_context.meta
207
+ if meta is not None:
208
+ task_id = getattr(meta, "task_id", None) or getattr(meta, "taskId", None)
209
+ payload = {
210
+ "event": "tool_error",
211
+ "tool": tool_name,
212
+ "error": str(exc),
213
+ "traceback": traceback.format_exc(),
214
+ }
215
+ if task_id is not None:
216
+ payload["task_id"] = task_id
217
+ try:
218
+ await session.send_log_message(
219
+ level="error",
220
+ data=json.dumps(payload),
221
+ related_request_id=ctx.request_id,
222
+ )
223
+ except Exception:
224
+ logger.exception("Failed to emit tool_error notification for %s", tool_name)
225
+
226
+
227
+ def _log_tool_call(tool_name: str, ctx: Context | None = None) -> None:
228
+ request_id = None
229
+ if ctx is not None:
230
+ request_id = getattr(ctx, "request_id", None)
231
+ logger.info("MCP tool call: %s request_id=%s", tool_name, request_id)
232
+
233
+ def _should_stream_smcl_chunk(text: str, request_id: object | None) -> bool:
234
+ if request_id is None:
235
+ return True
236
+ try:
237
+ payload = json.loads(text)
238
+ if isinstance(payload, dict) and payload.get("event"):
239
+ return True
240
+ except Exception:
241
+ pass
242
+ log_path = _request_log_paths.get(str(request_id))
243
+ if log_path and log_path in _read_log_paths:
244
+ return False
245
+ return True
246
+
247
+
248
+ def _attach_task_id(ctx: Context | None, task_id: str) -> None:
249
+ if ctx is None:
250
+ return
251
+ meta = ctx.request_context.meta
252
+ if meta is None:
253
+ meta = types.RequestParams.Meta()
254
+ ctx.request_context.meta = meta
255
+ try:
256
+ setattr(meta, "task_id", task_id)
257
+ except Exception:
258
+ logger.debug("Unable to attach task_id to request meta", exc_info=True)
259
+
260
+
261
+ def _extract_ctx(args: tuple[object, ...], kwargs: dict[str, object]) -> Context | None:
262
+ ctx = kwargs.get("ctx")
263
+ if isinstance(ctx, Context):
264
+ return ctx
265
+ for arg in args:
266
+ if isinstance(arg, Context):
267
+ return arg
268
+ return None
269
+
270
+
271
+ _mcp_tool = mcp.tool
272
+ _mcp_resource = mcp.resource
273
+
274
+
275
+ def tool(*tool_args, **tool_kwargs):
276
+ decorator = _mcp_tool(*tool_args, **tool_kwargs)
277
+
278
+ def outer(func):
279
+ if asyncio.iscoroutinefunction(func):
280
+ @wraps(func)
281
+ async def async_inner(*args, **kwargs):
282
+ ctx = _extract_ctx(args, kwargs)
283
+ _log_tool_call(func.__name__, ctx)
284
+ try:
285
+ return await func(*args, **kwargs)
286
+ except Exception as exc:
287
+ await _notify_tool_error(ctx, func.__name__, exc)
288
+ raise
289
+
290
+ return decorator(async_inner)
291
+
292
+ @wraps(func)
293
+ def sync_inner(*args, **kwargs):
294
+ ctx = _extract_ctx(args, kwargs)
295
+ _log_tool_call(func.__name__, ctx)
296
+ try:
297
+ return func(*args, **kwargs)
298
+ except Exception:
299
+ logger.exception("Tool %s failed", func.__name__)
300
+ raise
301
+
302
+ return decorator(sync_inner)
303
+
304
+ return outer
305
+
306
+
307
+ mcp.tool = tool
308
+
309
+
310
+ def resource(*resource_args, **resource_kwargs):
311
+ decorator = _mcp_resource(*resource_args, **resource_kwargs)
312
+
313
+ def outer(func):
314
+ if asyncio.iscoroutinefunction(func):
315
+ @wraps(func)
316
+ async def async_inner(*args, **kwargs):
317
+ _log_tool_call(func.__name__, _extract_ctx(args, kwargs))
318
+ return await func(*args, **kwargs)
319
+
320
+ return decorator(async_inner)
321
+
322
+ @wraps(func)
323
+ def sync_inner(*args, **kwargs):
324
+ _log_tool_call(func.__name__, _extract_ctx(args, kwargs))
325
+ return func(*args, **kwargs)
326
+
327
+ return decorator(sync_inner)
328
+
329
+ return outer
330
+
331
+
332
+ mcp.resource = resource
333
+
334
+
335
+ @mcp.tool()
336
+ async def run_do_file_background(
337
+ path: str,
338
+ ctx: Context | None = None,
339
+ echo: bool = True,
340
+ as_json: bool = True,
341
+ trace: bool = False,
342
+ raw: bool = False,
343
+ max_output_lines: int = None,
344
+ cwd: str | None = None,
345
+ ) -> str:
346
+ """Run a Stata do-file in the background and return a task id.
347
+
348
+ Notifications:
349
+ - logMessage: {"event":"log_path","path":"..."}
350
+ - logMessage: {"event":"task_done","task_id":"...","status":"done","log_path":"...","error":null}
351
+ """
352
+ session = ctx.request_context.session if ctx is not None else None
353
+ request_id = ctx.request_id if ctx is not None else None
354
+ task_id = uuid.uuid4().hex
355
+ _attach_task_id(ctx, task_id)
356
+ task_info = BackgroundTask(
357
+ task_id=task_id,
358
+ kind="do_file",
359
+ task=None,
360
+ created_at=datetime.utcnow(),
361
+ )
362
+
363
+ async def notify_log(text: str) -> None:
364
+ if session is not None:
365
+ if not _should_stream_smcl_chunk(text, ctx.request_id):
366
+ return
367
+ _debug_notification("logMessage", text, ctx.request_id)
368
+ try:
369
+ await session.send_log_message(level="info", data=text, related_request_id=ctx.request_id)
370
+ except Exception as e:
371
+ logger.warning("Failed to send logMessage notification: %s", e)
372
+ sys.stderr.write(f"[mcp_stata] ERROR: logMessage send failed: {e!r}\n")
373
+ sys.stderr.flush()
374
+ try:
375
+ payload = json.loads(text)
376
+ if isinstance(payload, dict) and payload.get("event") == "log_path":
377
+ task_info.log_path = payload.get("path")
378
+ if ctx.request_id is not None and task_info.log_path:
379
+ _request_log_paths[str(ctx.request_id)] = task_info.log_path
380
+ except Exception:
381
+ return
382
+
383
+ progress_token = None
384
+ if ctx is not None and ctx.request_context.meta is not None:
385
+ progress_token = ctx.request_context.meta.progressToken
386
+
387
+ async def notify_progress(progress: float, total: float | None, message: str | None) -> None:
388
+ if session is None or progress_token is None:
389
+ return
390
+ _debug_notification(
391
+ "progress",
392
+ {"progress": progress, "total": total, "message": message},
393
+ ctx.request_id,
394
+ )
395
+ await session.send_progress_notification(
396
+ progress_token=progress_token,
397
+ progress=progress,
398
+ total=total,
399
+ message=message,
400
+ related_request_id=ctx.request_id,
401
+ )
402
+
403
+ async def _run() -> None:
404
+ try:
405
+ result = await client.run_do_file_streaming(
406
+ path,
407
+ notify_log=notify_log,
408
+ notify_progress=notify_progress if progress_token is not None else None,
409
+ echo=echo,
410
+ trace=trace,
411
+ max_output_lines=max_output_lines,
412
+ cwd=cwd,
413
+ emit_graph_ready=True,
414
+ graph_ready_task_id=task_id,
415
+ graph_ready_format="svg",
416
+ )
417
+ # Notify task completion as soon as the core operation is finished
418
+ task_info.done = True
419
+ if result.error:
420
+ task_info.error = result.error.message
421
+ await _notify_task_done(session, task_info, request_id)
422
+
423
+ ui_channel.notify_potential_dataset_change()
424
+ task_info.result = _format_command_result(result, raw=raw, as_json=as_json)
425
+ except Exception as exc: # pragma: no cover - defensive
426
+ task_info.done = True
427
+ task_info.error = str(exc)
428
+ await _notify_task_done(session, task_info, request_id)
429
+
430
+ task_info.task = asyncio.create_task(_run())
431
+ _register_task(task_info)
432
+ await _wait_for_log_path(task_info)
433
+ return json.dumps({"task_id": task_id, "status": "started", "log_path": task_info.log_path})
434
+
435
+
436
+ @mcp.tool()
437
+ def get_task_status(task_id: str, allow_polling: bool = False) -> str:
438
+ """Return task status for background executions.
439
+
440
+ Polling is disabled by default; set allow_polling=True for legacy callers.
441
+ """
442
+ notice = "Prefer task_done logMessage notifications over polling get_task_status."
443
+ if not allow_polling:
444
+ logger.warning(
445
+ "get_task_status called without allow_polling; clients must use task_done logMessage notifications"
446
+ )
447
+ return json.dumps({
448
+ "task_id": task_id,
449
+ "status": "polling_not_allowed",
450
+ "error": "Polling is disabled; use task_done logMessage notifications.",
451
+ "notice": notice,
452
+ })
453
+ logger.warning("get_task_status called; clients should use task_done logMessage notifications instead of polling")
454
+ task_info = _background_tasks.get(task_id)
455
+ if task_info is None:
456
+ return json.dumps({"task_id": task_id, "status": "not_found", "notice": notice})
457
+ return json.dumps({
458
+ "task_id": task_id,
459
+ "status": "done" if task_info.done else "running",
460
+ "kind": task_info.kind,
461
+ "created_at": task_info.created_at.isoformat(),
462
+ "log_path": task_info.log_path,
463
+ "error": task_info.error,
464
+ "notice": notice,
465
+ })
466
+
467
+
468
+ @mcp.tool()
469
+ def get_task_result(task_id: str, allow_polling: bool = False) -> str:
470
+ """Return task result for background executions.
471
+
472
+ Polling is disabled by default; set allow_polling=True for legacy callers.
473
+ """
474
+ notice = "Prefer task_done logMessage notifications over polling get_task_result."
475
+ if not allow_polling:
476
+ logger.warning(
477
+ "get_task_result called without allow_polling; clients must use task_done logMessage notifications"
478
+ )
479
+ return json.dumps({
480
+ "task_id": task_id,
481
+ "status": "polling_not_allowed",
482
+ "error": "Polling is disabled; use task_done logMessage notifications.",
483
+ "notice": notice,
484
+ })
485
+ logger.warning("get_task_result called; clients should use task_done logMessage notifications instead of polling")
486
+ task_info = _background_tasks.get(task_id)
487
+ if task_info is None:
488
+ return json.dumps({"task_id": task_id, "status": "not_found", "notice": notice})
489
+ if not task_info.done:
490
+ return json.dumps({
491
+ "task_id": task_id,
492
+ "status": "running",
493
+ "log_path": task_info.log_path,
494
+ "notice": notice,
495
+ })
496
+ return json.dumps({
497
+ "task_id": task_id,
498
+ "status": "done",
499
+ "log_path": task_info.log_path,
500
+ "error": task_info.error,
501
+ "notice": notice,
502
+ "result": task_info.result,
503
+ })
504
+
505
+
506
+ @mcp.tool()
507
+ def cancel_task(task_id: str) -> str:
508
+ """Request cancellation of a background task."""
509
+ task_info = _background_tasks.get(task_id)
510
+ if task_info is None:
511
+ return json.dumps({"task_id": task_id, "status": "not_found"})
512
+ if task_info.task and not task_info.task.done():
513
+ task_info.task.cancel()
514
+ return json.dumps({"task_id": task_id, "status": "cancelling"})
515
+ return json.dumps({"task_id": task_id, "status": "done", "log_path": task_info.log_path})
516
+
517
+
518
+ @mcp.tool()
519
+ async def run_command_background(
520
+ code: str,
521
+ ctx: Context | None = None,
522
+ echo: bool = True,
523
+ as_json: bool = True,
524
+ trace: bool = False,
525
+ raw: bool = False,
526
+ max_output_lines: int = None,
527
+ cwd: str | None = None,
528
+ ) -> str:
529
+ """Run a Stata command in the background and return a task id.
530
+
531
+ Notifications:
532
+ - logMessage: {"event":"log_path","path":"..."}
533
+ - logMessage: {"event":"task_done","task_id":"...","status":"done","log_path":"...","error":null}
534
+ """
535
+ session = ctx.request_context.session if ctx is not None else None
536
+ request_id = ctx.request_id if ctx is not None else None
537
+ task_id = uuid.uuid4().hex
538
+ _attach_task_id(ctx, task_id)
539
+ task_info = BackgroundTask(
540
+ task_id=task_id,
541
+ kind="command",
542
+ task=None,
543
+ created_at=datetime.utcnow(),
544
+ )
545
+
546
+ async def notify_log(text: str) -> None:
547
+ if session is not None:
548
+ if not _should_stream_smcl_chunk(text, ctx.request_id):
549
+ return
550
+ _debug_notification("logMessage", text, ctx.request_id)
551
+ await session.send_log_message(level="info", data=text, related_request_id=ctx.request_id)
552
+ try:
553
+ payload = json.loads(text)
554
+ if isinstance(payload, dict) and payload.get("event") == "log_path":
555
+ task_info.log_path = payload.get("path")
556
+ if ctx.request_id is not None and task_info.log_path:
557
+ _request_log_paths[str(ctx.request_id)] = task_info.log_path
558
+ except Exception:
559
+ return
560
+
561
+ progress_token = None
562
+ if ctx is not None and ctx.request_context.meta is not None:
563
+ progress_token = ctx.request_context.meta.progressToken
564
+
565
+ async def notify_progress(progress: float, total: float | None, message: str | None) -> None:
566
+ if session is None or progress_token is None:
567
+ return
568
+ await session.send_progress_notification(
569
+ progress_token=progress_token,
570
+ progress=progress,
571
+ total=total,
572
+ message=message,
573
+ related_request_id=ctx.request_id,
574
+ )
575
+
576
+ async def _run() -> None:
577
+ try:
578
+ result = await client.run_command_streaming(
579
+ code,
580
+ notify_log=notify_log,
581
+ notify_progress=notify_progress if progress_token is not None else None,
582
+ echo=echo,
583
+ trace=trace,
584
+ max_output_lines=max_output_lines,
585
+ cwd=cwd,
586
+ emit_graph_ready=True,
587
+ graph_ready_task_id=task_id,
588
+ graph_ready_format="svg",
589
+ )
590
+ # Notify task completion as soon as the core operation is finished
591
+ task_info.done = True
592
+ if result.error:
593
+ task_info.error = result.error.message
594
+ await _notify_task_done(session, task_info, request_id)
595
+
596
+ ui_channel.notify_potential_dataset_change()
597
+ task_info.result = _format_command_result(result, raw=raw, as_json=as_json)
598
+ except Exception as exc: # pragma: no cover - defensive
599
+ task_info.done = True
600
+ task_info.error = str(exc)
601
+ await _notify_task_done(session, task_info, request_id)
602
+
603
+ task_info.task = asyncio.create_task(_run())
604
+ _register_task(task_info)
605
+ await _wait_for_log_path(task_info)
606
+ return json.dumps({"task_id": task_id, "status": "started", "log_path": task_info.log_path})
607
+
608
+ @mcp.tool()
609
+ async def run_command(
610
+ code: str,
611
+ ctx: Context | None = None,
612
+ echo: bool = True,
613
+ as_json: bool = True,
614
+ trace: bool = False,
615
+ raw: bool = False,
616
+ max_output_lines: int = None,
617
+ cwd: str | None = None,
618
+ ) -> str:
619
+ """
620
+ Executes Stata code.
621
+
622
+ This is the primary tool for interacting with Stata.
623
+
624
+ Stata output is written to a temporary log file on disk.
625
+ The server emits a single `notifications/logMessage` event containing the log file path
626
+ (JSON payload: {"event":"log_path","path":"..."}) so the client can tail it locally.
627
+ If the client supplies a progress callback/token, progress updates may also be emitted
628
+ via `notifications/progress`.
629
+
630
+ Args:
631
+ code: The Stata command(s) to execute (e.g., "sysuse auto", "regress price mpg", "summarize").
632
+ ctx: FastMCP-injected request context (used to send MCP notifications). Optional for direct Python calls.
633
+ echo: If True, the command itself is included in the output. Default is True.
634
+ as_json: If True, returns a JSON envelope with rc/stdout/stderr/error.
635
+ trace: If True, enables `set trace on` for deeper error diagnostics (automatically disabled after).
636
+ raw: If True, return raw output/error message rather than a JSON envelope.
637
+ max_output_lines: If set, truncates stdout to this many lines for token efficiency.
638
+ Useful for verbose commands (regress, codebook, etc.).
639
+ Note: This tool always uses log-file streaming semantics; there is no non-streaming mode.
640
+ """
641
+ session = ctx.request_context.session if ctx is not None else None
642
+
643
+ async def notify_log(text: str) -> None:
644
+ if session is None:
645
+ return
646
+ if not _should_stream_smcl_chunk(text, ctx.request_id):
647
+ return
648
+ _debug_notification("logMessage", text, ctx.request_id)
649
+ await session.send_log_message(level="info", data=text, related_request_id=ctx.request_id)
650
+ try:
651
+ payload = json.loads(text)
652
+ if isinstance(payload, dict) and payload.get("event") == "log_path":
653
+ if ctx.request_id is not None:
654
+ _request_log_paths[str(ctx.request_id)] = payload.get("path")
655
+ except Exception:
656
+ return
657
+
658
+ progress_token = None
659
+ if ctx is not None and ctx.request_context.meta is not None:
660
+ progress_token = ctx.request_context.meta.progressToken
661
+
662
+ async def notify_progress(progress: float, total: float | None, message: str | None) -> None:
663
+ if session is None or progress_token is None:
664
+ return
665
+ await session.send_progress_notification(
666
+ progress_token=progress_token,
667
+ progress=progress,
668
+ total=total,
669
+ message=message,
670
+ related_request_id=ctx.request_id,
671
+ )
672
+
673
+ async def _noop_log(_text: str) -> None:
674
+ return
675
+
676
+ result = await client.run_command_streaming(
677
+ code,
678
+ notify_log=notify_log if session is not None else _noop_log,
679
+ notify_progress=notify_progress if progress_token is not None else None,
680
+ echo=echo,
681
+ trace=trace,
682
+ max_output_lines=max_output_lines,
683
+ cwd=cwd,
684
+ emit_graph_ready=True,
685
+ graph_ready_task_id=ctx.request_id if ctx else None,
686
+ graph_ready_format="svg",
687
+ )
688
+
689
+ # Conservative invalidation: arbitrary Stata commands may change data.
690
+ ui_channel.notify_potential_dataset_change()
691
+ if raw:
692
+ if result.success:
693
+ return result.log_path or ""
694
+ if result.error:
695
+ msg = result.error.message
696
+ if result.error.rc is not None:
697
+ msg = f"{msg}\nrc={result.error.rc}"
698
+ return msg
699
+ return result.log_path or ""
700
+ if as_json:
701
+ return result.model_dump_json()
702
+
703
+
704
+ @mcp.tool()
705
+ def read_log(path: str, offset: int = 0, max_bytes: int = 65536) -> str:
706
+ """Read a slice of a log file.
707
+
708
+ Intended for clients that want to display a terminal-like view without pushing MBs of
709
+ output through MCP log notifications.
710
+
711
+ Args:
712
+ path: Absolute path to the log file previously provided by the server.
713
+ offset: Byte offset to start reading from.
714
+ max_bytes: Maximum bytes to read.
715
+
716
+ Returns a compact JSON string: {"path":..., "offset":..., "next_offset":..., "data":...}
717
+ """
718
+ try:
719
+ if path:
720
+ _read_log_paths.add(path)
721
+ if offset < 0:
722
+ offset = 0
723
+ if path:
724
+ last_offset = _read_log_offsets.get(path, 0)
725
+ if offset < last_offset:
726
+ offset = last_offset
727
+ with open(path, "rb") as f:
728
+ f.seek(offset)
729
+ data = f.read(max_bytes)
730
+ next_offset = f.tell()
731
+ if path:
732
+ _read_log_offsets[path] = next_offset
733
+ text = data.decode("utf-8", errors="replace")
734
+ return json.dumps({"path": path, "offset": offset, "next_offset": next_offset, "data": text})
735
+ except FileNotFoundError:
736
+ return json.dumps({"path": path, "offset": offset, "next_offset": offset, "data": ""})
737
+ except Exception as e:
738
+ return json.dumps({"path": path, "offset": offset, "next_offset": offset, "data": f"ERROR: {e}"})
739
+
740
+
741
+ @mcp.tool()
742
+ def find_in_log(
743
+ path: str,
744
+ query: str,
745
+ start_offset: int = 0,
746
+ max_bytes: int = 5_000_000,
747
+ before: int = 2,
748
+ after: int = 2,
749
+ case_sensitive: bool = False,
750
+ regex: bool = False,
751
+ max_matches: int = 50,
752
+ ) -> str:
753
+ """Find text within a log file and return context windows.
754
+
755
+ Args:
756
+ path: Absolute path to the log file previously provided by the server.
757
+ query: Text or regex pattern to search for.
758
+ start_offset: Byte offset to start searching from.
759
+ max_bytes: Maximum bytes to read from the log.
760
+ before: Number of context lines to include before each match.
761
+ after: Number of context lines to include after each match.
762
+ case_sensitive: If True, match case-sensitively.
763
+ regex: If True, treat query as a regular expression.
764
+ max_matches: Maximum number of matches to return.
765
+
766
+ Returns a JSON string with matches and offsets:
767
+ {"path":..., "query":..., "start_offset":..., "next_offset":..., "truncated":..., "matches":[...]}.
768
+ """
769
+ try:
770
+ if start_offset < 0:
771
+ start_offset = 0
772
+ if max_bytes <= 0:
773
+ return json.dumps({
774
+ "path": path,
775
+ "query": query,
776
+ "start_offset": start_offset,
777
+ "next_offset": start_offset,
778
+ "truncated": False,
779
+ "matches": [],
780
+ })
781
+ with open(path, "rb") as f:
782
+ f.seek(start_offset)
783
+ data = f.read(max_bytes)
784
+ next_offset = f.tell()
785
+
786
+ text = data.decode("utf-8", errors="replace")
787
+ lines = text.splitlines()
788
+
789
+ if regex:
790
+ flags = 0 if case_sensitive else re.IGNORECASE
791
+ pattern = re.compile(query, flags=flags)
792
+ def is_match(line: str) -> bool:
793
+ return pattern.search(line) is not None
794
+ else:
795
+ needle = query if case_sensitive else query.lower()
796
+ def is_match(line: str) -> bool:
797
+ haystack = line if case_sensitive else line.lower()
798
+ return needle in haystack
799
+
800
+ matches = []
801
+ for idx, line in enumerate(lines):
802
+ if not is_match(line):
803
+ continue
804
+ start_idx = max(0, idx - max(0, before))
805
+ end_idx = min(len(lines), idx + max(0, after) + 1)
806
+ context = lines[start_idx:end_idx]
807
+ matches.append({
808
+ "line_index": idx,
809
+ "context_start": start_idx,
810
+ "context_end": end_idx,
811
+ "context": context,
812
+ })
813
+ if len(matches) >= max_matches:
814
+ break
815
+
816
+ truncated = len(matches) >= max_matches
817
+ return json.dumps({
818
+ "path": path,
819
+ "query": query,
820
+ "start_offset": start_offset,
821
+ "next_offset": next_offset,
822
+ "truncated": truncated,
823
+ "matches": matches,
824
+ })
825
+ except FileNotFoundError:
826
+ return json.dumps({
827
+ "path": path,
828
+ "query": query,
829
+ "start_offset": start_offset,
830
+ "next_offset": start_offset,
831
+ "truncated": False,
832
+ "matches": [],
833
+ })
834
+ except Exception as e:
835
+ return json.dumps({
836
+ "path": path,
837
+ "query": query,
838
+ "start_offset": start_offset,
839
+ "next_offset": start_offset,
840
+ "truncated": False,
841
+ "matches": [],
842
+ "error": f"ERROR: {e}",
843
+ })
844
+
845
+
846
+ @mcp.tool()
847
+ def get_data(start: int = 0, count: int = 50) -> str:
848
+ """
849
+ Returns a slice of the active dataset as a JSON-formatted list of dictionaries.
850
+
851
+ Use this to inspect the actual data values in memory. Useful for checking data quality or content.
852
+
853
+ Args:
854
+ start: The zero-based index of the first observation to retrieve.
855
+ count: The number of observations to retrieve. Defaults to 50.
856
+ """
857
+ data = client.get_data(start, count)
858
+ resp = DataResponse(start=start, count=count, data=data)
859
+ return resp.model_dump_json()
860
+
861
+
862
+ @mcp.tool()
863
+ def get_ui_channel() -> str:
864
+ """Return localhost HTTP endpoint + bearer token for the extension UI data plane."""
865
+ info = ui_channel.get_channel()
866
+ payload = {
867
+ "baseUrl": info.base_url,
868
+ "token": info.token,
869
+ "expiresAt": info.expires_at,
870
+ "capabilities": ui_channel.capabilities(),
871
+ }
872
+ return json.dumps(payload)
873
+
874
+ @mcp.tool()
875
+ def describe() -> str:
876
+ """
877
+ Returns variable descriptions, storage types, and labels (equivalent to Stata's `describe` command).
878
+
879
+ Use this to understand the structure of the dataset, variable names, and their formats before running analysis.
880
+ """
881
+ result = client.run_command_structured("describe", echo=True)
882
+ if result.success:
883
+ return result.stdout
884
+ if result.error:
885
+ return result.error.message
886
+ return ""
887
+
888
+ @mcp.tool()
889
+ def list_graphs() -> str:
890
+ """
891
+ Lists the names of all graphs currently stored in Stata's memory.
892
+
893
+ Use this to see which graphs are available for export via `export_graph`. The
894
+ response marks the active graph so the agent knows which one will export by
895
+ default.
896
+ """
897
+ graphs = client.list_graphs_structured()
898
+ return graphs.model_dump_json()
899
+
900
+ @mcp.tool()
901
+ def export_graph(graph_name: str = None, format: str = "pdf") -> str:
902
+ """
903
+ Exports a stored Stata graph to a file and returns its path.
904
+
905
+ Args:
906
+ graph_name: The name of the graph to export (as seen in `list_graphs`).
907
+ If None, exports the currently active graph.
908
+ format: Output format, defaults to "pdf". Supported: "pdf", "png". Use
909
+ "png" to view the plot directly so the agent can visually check
910
+ titles, labels, legends, colors, and other user requirements.
911
+ """
912
+ try:
913
+ return client.export_graph(graph_name, format=format)
914
+ except Exception as e:
915
+ raise RuntimeError(f"Failed to export graph: {e}")
916
+
917
+ @mcp.tool()
918
+ def get_help(topic: str, plain_text: bool = False) -> str:
919
+ """
920
+ Returns the official Stata help text for a given command or topic.
921
+
922
+ Args:
923
+ topic: The command name or help topic (e.g., "regress", "graph", "options").
924
+ Returns Markdown by default, or plain text when plain_text=True.
925
+ """
926
+ return client.get_help(topic, plain_text=plain_text)
927
+
928
+ @mcp.tool()
929
+ def get_stored_results() -> str:
930
+ """
931
+ Returns the current stored results (r-class and e-class scalars/macros) as a JSON-formatted string.
932
+
933
+ Use this after running a command (like `summarize` or `regress`) to programmatically retrieve
934
+ specific values (e.g., means, coefficients, sample sizes) for validation or further calculation.
935
+ """
936
+ import json
937
+ return json.dumps(client.get_stored_results())
938
+
939
+ @mcp.tool()
940
+ def load_data(source: str, clear: bool = True, as_json: bool = True, raw: bool = False, max_output_lines: int = None) -> str:
941
+ """
942
+ Loads data using sysuse/webuse/use heuristics based on the source string.
943
+ Automatically appends , clear unless clear=False.
944
+
945
+ Args:
946
+ source: Dataset source (e.g., "auto", "auto.dta", "/path/to/file.dta").
947
+ clear: If True, clears data in memory before loading.
948
+ as_json: If True, returns JSON envelope.
949
+ raw: If True, returns raw output only.
950
+ max_output_lines: If set, truncates stdout to this many lines for token efficiency.
951
+ """
952
+ result = client.load_data(source, clear=clear, max_output_lines=max_output_lines)
953
+ ui_channel.notify_potential_dataset_change()
954
+ if raw:
955
+ return result.stdout if result.success else (result.error.message if result.error else result.stdout)
956
+ return result.model_dump_json()
957
+
958
+ @mcp.tool()
959
+ def codebook(variable: str, as_json: bool = True, trace: bool = False, raw: bool = False, max_output_lines: int = None) -> str:
960
+ """
961
+ Returns codebook/summary for a specific variable.
962
+
963
+ Args:
964
+ variable: The variable name to analyze.
965
+ as_json: If True, returns JSON envelope.
966
+ trace: If True, enables trace mode.
967
+ raw: If True, returns raw output only.
968
+ max_output_lines: If set, truncates stdout to this many lines for token efficiency.
969
+ """
970
+ result = client.codebook(variable, trace=trace, max_output_lines=max_output_lines)
971
+ if raw:
972
+ return result.stdout if result.success else (result.error.message if result.error else result.stdout)
973
+ return result.model_dump_json()
974
+
975
+ @mcp.tool()
976
+ async def run_do_file(
977
+ path: str,
978
+ ctx: Context | None = None,
979
+ echo: bool = True,
980
+ as_json: bool = True,
981
+ trace: bool = False,
982
+ raw: bool = False,
983
+ max_output_lines: int = None,
984
+ cwd: str | None = None,
985
+ ) -> str:
986
+ """
987
+ Executes a .do file.
988
+
989
+ Stata output is written to a temporary log file on disk.
990
+ The server emits a single `notifications/logMessage` event containing the log file path
991
+ (JSON payload: {"event":"log_path","path":"..."}) so the client can tail it locally.
992
+ If the client supplies a progress callback/token, progress updates are emitted via
993
+ `notifications/progress`.
994
+
995
+ Args:
996
+ path: Path to the .do file to execute.
997
+ ctx: FastMCP-injected request context (used to send MCP notifications). Optional for direct Python calls.
998
+ echo: If True, includes command in output.
999
+ as_json: If True, returns JSON envelope.
1000
+ trace: If True, enables trace mode.
1001
+ raw: If True, returns raw output only.
1002
+ max_output_lines: If set, truncates stdout to this many lines for token efficiency.
1003
+ Note: This tool always uses log-file streaming semantics; there is no non-streaming mode.
1004
+ """
1005
+ session = ctx.request_context.session if ctx is not None else None
1006
+
1007
+ async def notify_log(text: str) -> None:
1008
+ if session is None:
1009
+ return
1010
+ if not _should_stream_smcl_chunk(text, ctx.request_id):
1011
+ return
1012
+ await session.send_log_message(level="info", data=text, related_request_id=ctx.request_id)
1013
+ try:
1014
+ payload = json.loads(text)
1015
+ if isinstance(payload, dict) and payload.get("event") == "log_path":
1016
+ if ctx.request_id is not None:
1017
+ _request_log_paths[str(ctx.request_id)] = payload.get("path")
1018
+ except Exception:
1019
+ return
1020
+
1021
+ progress_token = None
1022
+ if ctx is not None and ctx.request_context.meta is not None:
1023
+ progress_token = ctx.request_context.meta.progressToken
1024
+
1025
+ async def notify_progress(progress: float, total: float | None, message: str | None) -> None:
1026
+ if session is None or progress_token is None:
1027
+ return
1028
+ await session.send_progress_notification(
1029
+ progress_token=progress_token,
1030
+ progress=progress,
1031
+ total=total,
1032
+ message=message,
1033
+ related_request_id=ctx.request_id,
1034
+ )
1035
+
1036
+ async def _noop_log(_text: str) -> None:
1037
+ return
1038
+
1039
+ result = await client.run_do_file_streaming(
1040
+ path,
1041
+ notify_log=notify_log if session is not None else _noop_log,
1042
+ notify_progress=notify_progress if progress_token is not None else None,
1043
+ echo=echo,
1044
+ trace=trace,
1045
+ max_output_lines=max_output_lines,
1046
+ cwd=cwd,
1047
+ emit_graph_ready=True,
1048
+ graph_ready_task_id=ctx.request_id if ctx else None,
1049
+ graph_ready_format="svg",
1050
+ )
1051
+
1052
+ ui_channel.notify_potential_dataset_change()
1053
+
1054
+ if raw:
1055
+ if result.success:
1056
+ return result.log_path or ""
1057
+ if result.error:
1058
+ return result.error.message
1059
+ return result.log_path or ""
1060
+ return result.model_dump_json()
1061
+
1062
+ @mcp.resource("stata://data/summary")
1063
+ def get_summary() -> str:
1064
+ """
1065
+ Returns the output of the `summarize` command for the dataset in memory.
1066
+ Provides descriptive statistics (obs, mean, std. dev, min, max) for all variables.
1067
+ """
1068
+ result = client.run_command_structured("summarize", echo=True)
1069
+ if result.success:
1070
+ return result.stdout
1071
+ if result.error:
1072
+ return result.error.message
1073
+ return ""
1074
+
1075
+ @mcp.resource("stata://data/metadata")
1076
+ def get_metadata() -> str:
1077
+ """
1078
+ Returns the output of the `describe` command.
1079
+ Provides metadata about the dataset, including variable names, storage types, display formats, and labels.
1080
+ """
1081
+ result = client.run_command_structured("describe", echo=True)
1082
+ if result.success:
1083
+ return result.stdout
1084
+ if result.error:
1085
+ return result.error.message
1086
+ return ""
1087
+
1088
+ @mcp.resource("stata://graphs/list")
1089
+ def list_graphs_resource() -> str:
1090
+ """Resource wrapper for the graph list (uses tool list_graphs)."""
1091
+ return list_graphs()
1092
+
1093
+ @mcp.tool()
1094
+ def get_variable_list() -> str:
1095
+ """Returns JSON list of all variables."""
1096
+ variables = client.list_variables_structured()
1097
+ return variables.model_dump_json()
1098
+
1099
+ @mcp.resource("stata://variables/list")
1100
+ def get_variable_list_resource() -> str:
1101
+ """Resource wrapper for the variable list."""
1102
+ return get_variable_list()
1103
+
1104
+ @mcp.resource("stata://results/stored")
1105
+ def get_stored_results_resource() -> str:
1106
+ """Returns stored r() and e() results."""
1107
+ import json
1108
+ return json.dumps(client.get_stored_results())
1109
+
1110
+ @mcp.tool()
1111
+ def export_graphs_all() -> str:
1112
+ """
1113
+ Exports all graphs in memory to file paths.
1114
+
1115
+ Returns a JSON envelope listing graph names and file paths.
1116
+ The agent can open SVG files directly to verify visuals (titles/labels/colors/legends).
1117
+ """
1118
+ exports = client.export_graphs_all()
1119
+ return exports.model_dump_json(exclude_none=False)
1120
+
1121
+ def main():
1122
+ if "--version" in sys.argv:
1123
+ print(SERVER_VERSION)
1124
+ return
1125
+
1126
+ setup_logging()
1127
+
1128
+ # Initialize Stata here on the main thread to ensure any issues are logged early.
1129
+ # On Windows, this is critical for COM registration. On other platforms, it helps
1130
+ # catch license or installation errors before the first tool call.
1131
+ try:
1132
+ client.init()
1133
+ except BaseException as e:
1134
+ # Use sys.stderr.write and flush to ensure visibility before exit
1135
+ msg = f"\n{'='*60}\n[mcp_stata] FATAL: STATA INITIALIZATION FAILED\n{'='*60}\nError: {repr(e)}\n"
1136
+ sys.stderr.write(msg)
1137
+ if isinstance(e, SystemExit):
1138
+ sys.stderr.write(f"Stata triggered a SystemExit (code: {e.code}). This is usually a license error.\n")
1139
+ sys.stderr.write(f"{'='*60}\n\n")
1140
+ sys.stderr.flush()
1141
+
1142
+ # We exit here because the user wants a clear failure when Stata cannot be loaded.
1143
+ sys.exit(1)
1144
+
1145
+ mcp.run()
1146
+
1147
+ if __name__ == "__main__":
1148
+ main()