From 6d40ac7ec99df5189f8fc9a3c5e7602d9d038671 Mon Sep 17 00:00:00 2001 From: codeasier Date: Sun, 19 Apr 2026 17:01:40 +0800 Subject: [PATCH 1/3] feat: add MCP server support for agent integration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add MCP (Model Context Protocol) server so LLM agents can programmatically query PyTorch memory snapshots without shelling out to CLI commands. - src/pt_snap_cli/api.py: SnapshotAnalyzer service layer (no MCP dep) - src/pt_snap_cli/mcp/server.py: FastMCP server with 5 tools, 1 resource, 1 prompt - pyproject.toml: add mcp optional dependency and pt-snap-mcp entry point - tests/test_api.py, tests/test_mcp_server.py: 23 new tests Tools exposed: get_focus, set_focus, list_templates, get_template_info, execute_query. Backward compatible — existing CLI unchanged. Fixes #54 --- pyproject.toml | 6 +- src/pt_snap_cli/api.py | 124 ++++++++++++++++++++++ src/pt_snap_cli/mcp/__init__.py | 0 src/pt_snap_cli/mcp/server.py | 116 +++++++++++++++++++++ tests/test_api.py | 162 +++++++++++++++++++++++++++++ tests/test_mcp_server.py | 178 ++++++++++++++++++++++++++++++++ 6 files changed, 585 insertions(+), 1 deletion(-) create mode 100644 src/pt_snap_cli/api.py create mode 100644 src/pt_snap_cli/mcp/__init__.py create mode 100644 src/pt_snap_cli/mcp/server.py create mode 100644 tests/test_api.py create mode 100644 tests/test_mcp_server.py diff --git a/pyproject.toml b/pyproject.toml index d468f46..d4d02f5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,9 @@ dev = [ "ruff>=0.0.280", "build>=1.0.0", ] +mcp = [ + "mcp>=1.0.0", +] rag = [ "chromadb>=0.4.0", "langchain>=0.1.0", @@ -50,6 +53,7 @@ rag = [ [project.scripts] pt-snap = "pt_snap_cli.cli:_safe_call" +pt-snap-mcp = "pt_snap_cli.mcp.server:main" [tool.setuptools.packages.find] where = ["src"] @@ -92,4 +96,4 @@ exclude_lines = [ fail_under = 0 [tool.coverage.xml] -output = "coverage.xml" \ No newline at end of file +output = "coverage.xml" diff --git a/src/pt_snap_cli/api.py b/src/pt_snap_cli/api.py new file mode 100644 index 0000000..63235f5 --- /dev/null +++ b/src/pt_snap_cli/api.py @@ -0,0 +1,124 @@ +"""High-level API for PyTorch memory snapshot analysis. + +This module provides a programmatic interface that both the CLI +and the MCP server can use. It has no MCP dependency. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from pt_snap_cli.config import Config +from pt_snap_cli.context import Context +from pt_snap_cli.query.executor import QueryExecutor +from pt_snap_cli.query.registry import ( + get_template_info as _get_template_info, +) +from pt_snap_cli.query.registry import ( + list_by_category_with_details, + list_queries_with_details, +) + + +@dataclass +class FocusState: + """Current focus state of the analyzer.""" + + db_path: str | None + device_id: int | None + source: str + available_devices: list[int] + + +class SnapshotAnalyzer: + """Programmatic API for analyzing PyTorch memory snapshots.""" + + def __init__( + self, + db_path: Path | None = None, + device_id: int | None = None, + ) -> None: + self._config = Config() + self._db_path = db_path + self._device_id = device_id + self._context: Context | None = None + self._executor: QueryExecutor | None = None + + def _ensure_context(self) -> tuple[Context, QueryExecutor]: + """Resolve focus and create context/executor if needed.""" + if self._context is not None and self._executor is not None: + return self._context, self._executor + + resolved = self._config.resolve_focus(self._db_path, explicit_device_id=self._device_id) + if resolved.db_path is None: + raise RuntimeError("No database configured. Call set_focus() first.") + self._context = Context(resolved.db_path) + self._executor = QueryExecutor(self._context) + return self._context, self._executor + + def get_focus(self) -> FocusState: + """Get current focus state.""" + resolved = self._config.resolve_focus(self._db_path, explicit_device_id=self._device_id) + devices: list[int] = [] + if resolved.db_path and resolved.db_path.exists(): + try: + ctx = Context(resolved.db_path) + devices = ctx.device_ids + except Exception: + pass + return FocusState( + db_path=str(resolved.db_path) if resolved.db_path else None, + device_id=resolved.device_id, + source=resolved.source, + available_devices=devices, + ) + + def set_focus(self, db_path: str | None = None, device_id: int | None = None) -> FocusState: + """Set focus to a new database/device.""" + if db_path: + self._db_path = Path(db_path) + # Validate immediately + Context(self._db_path) + if device_id is not None: + self._device_id = device_id + # Reset cached context so next _ensure_context re-resolves + self._context = None + self._executor = None + return self.get_focus() + + def list_templates(self, category: str | None = None) -> list[dict]: + """List available query templates.""" + if category: + return list_by_category_with_details(category) + return list_queries_with_details() + + def get_template_info(self, name: str) -> dict | None: + """Get detailed template information.""" + return _get_template_info(name) + + def execute_query( + self, + template: str, + params: dict[str, Any] | None = None, + device_id: int | None = None, + max_rows: int | None = None, + ) -> dict[str, Any]: + """Execute a query template. Returns {total, returned, device_id, rows}.""" + ctx, executor = self._ensure_context() + target_device = device_id or self._device_id + if target_device is None and ctx.device_ids: + target_device = ctx.device_ids[0] + + rows = executor.execute_template(template, params or {}, device_id=target_device) + total = len(rows) + if max_rows is not None and max_rows > 0: + rows = rows[:max_rows] + + return { + "total": total, + "returned": len(rows), + "device_id": target_device, + "rows": rows, + } diff --git a/src/pt_snap_cli/mcp/__init__.py b/src/pt_snap_cli/mcp/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/pt_snap_cli/mcp/server.py b/src/pt_snap_cli/mcp/server.py new file mode 100644 index 0000000..5d74c0f --- /dev/null +++ b/src/pt_snap_cli/mcp/server.py @@ -0,0 +1,116 @@ +"""MCP server for pt-snap-cli.""" + +from typing import Any + +from mcp.server.fastmcp import FastMCP + +from pt_snap_cli.api import SnapshotAnalyzer + +mcp = FastMCP( + "pt-snap", + instructions="PyTorch Memory Snapshot Analysis", +) + +_analyzer = SnapshotAnalyzer() + + +@mcp.tool() +def get_focus() -> dict[str, Any]: + """Get the current analysis focus (database path and device).""" + state = _analyzer.get_focus() + return { + "db_path": state.db_path, + "device_id": state.device_id, + "source": state.source, + "available_devices": state.available_devices, + } + + +@mcp.tool() +def set_focus(db_path: str | None = None, device_id: int | None = None) -> dict[str, Any]: + """Set the analysis focus to a specific database and optional device. + + Use this before running queries to point to the correct snapshot file. + """ + state = _analyzer.set_focus(db_path, device_id) + return { + "db_path": state.db_path, + "device_id": state.device_id, + "available_devices": state.available_devices, + } + + +@mcp.tool() +def list_templates(category: str | None = None) -> list[dict[str, Any]]: + """List available query templates, optionally filtered by category. + + Common categories include 'basic' for simple queries and 'analysis' + for advanced memory analysis templates. + """ + return _analyzer.list_templates(category) + + +@mcp.tool() +def get_template_info(template_name: str) -> dict[str, Any]: + """Get detailed information about a query template including parameters and output schema. + + Use this to understand what parameters a template accepts before calling execute_query. + """ + info = _analyzer.get_template_info(template_name) + if info is None: + return {"error": f"Template '{template_name}' not found"} + return info + + +@mcp.tool() +def execute_query( + template: str, + params: dict[str, Any] | None = None, + device_id: int | None = None, + max_rows: int = 100, +) -> dict[str, Any]: + """Execute a query template against the focused database. + + Args: + template: Template name (e.g., 'leak_detection', 'callstack_analysis'). + Use list_templates to discover available templates. + params: Query parameters as a dict. Use get_template_info to see + what parameters each template accepts. + device_id: Device ID to query (uses focused device if not specified). + max_rows: Maximum rows to return (0 for unlimited, default: 100). + """ + return _analyzer.execute_query(template, params, device_id, max_rows) + + +@mcp.resource("focus://current") +def focus_resource() -> dict[str, Any]: + """Current analysis focus state.""" + state = _analyzer.get_focus() + return { + "db_path": state.db_path, + "device_id": state.device_id, + "source": state.source, + "available_devices": state.available_devices, + } + + +@mcp.prompt() +def analyze_memory_leaks( + db_path: str, + device_id: int = 0, +) -> str: + """Generate a prompt template for analyzing memory leaks in a PyTorch snapshot.""" + return ( + f"Analyze the PyTorch memory snapshot at '{db_path}' for device {device_id}. " + f"First, set focus to the database, then run the leak_detection template. " + f"Review the results and summarize any potential memory leaks found." + ) + + +def main() -> None: + """Entry point for the MCP server.""" + mcp.run() + + +if __name__ == "__main__": + main() diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..1eb3fc1 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,162 @@ +"""Tests for the high-level SnapshotAnalyzer API.""" + +import os +import sqlite3 +import tempfile +from pathlib import Path +from unittest.mock import patch + +import pytest + +from pt_snap_cli.api import FocusState, SnapshotAnalyzer + + +@pytest.fixture +def valid_db() -> Path: + """Create a valid test database.""" + with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f: + db_path = Path(f.name) + + conn = sqlite3.connect(str(db_path)) + conn.execute(""" + CREATE TABLE dictionary ( + `table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT + ) + """) + conn.execute(""" + CREATE TABLE trace_entry_0 ( + id INTEGER PRIMARY KEY, action INTEGER, address INTEGER, + size INTEGER, stream INTEGER, allocated INTEGER, + active INTEGER, reserved INTEGER, callstack TEXT + ) + """) + conn.execute(""" + CREATE TABLE block_0 ( + id INTEGER PRIMARY KEY, address INTEGER, size INTEGER, + requestedSize INTEGER, state INTEGER, allocEventId INTEGER, + freeEventId INTEGER + ) + """) + conn.commit() + conn.close() + + yield db_path + db_path.unlink(missing_ok=True) + + +@pytest.fixture(autouse=True) +def _reset_registry(): + """Reset the query registry singleton between tests.""" + from pt_snap_cli.query.registry import QueryRegistry + + QueryRegistry.reset() + + +@pytest.fixture(autouse=True) +def _isolate_config(): + """Isolate Config from user's global config during tests.""" + original_env = os.environ.get("PT_SNAP_DB_PATH") + if "PT_SNAP_DB_PATH" in os.environ: + del os.environ["PT_SNAP_DB_PATH"] + with patch.object(Path, "home", return_value=Path(tempfile.mkdtemp())): + yield + if original_env is not None: + os.environ["PT_SNAP_DB_PATH"] = original_env + + +class TestFocusState: + def test_focus_state_fields(self) -> None: + state = FocusState( + db_path="/tmp/test.db", + device_id=0, + source="explicit", + available_devices=[0, 1], + ) + assert state.db_path == "/tmp/test.db" + assert state.device_id == 0 + assert state.source == "explicit" + assert state.available_devices == [0, 1] + + +class TestSnapshotAnalyzerWithDB: + def test_get_focus_with_explicit_db(self, valid_db: Path) -> None: + analyzer = SnapshotAnalyzer(db_path=valid_db) + state = analyzer.get_focus() + assert state.db_path == str(valid_db) + assert state.source == "explicit" + assert 0 in state.available_devices + + def test_set_focus_changes_db(self, valid_db: Path, tmp_path: Path) -> None: + """Create a second DB and switch focus.""" + second_db = tmp_path / "second.db" + conn = sqlite3.connect(str(second_db)) + conn.execute( + "CREATE TABLE dictionary (`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)" + ) + conn.execute("CREATE TABLE trace_entry_1 (id INTEGER PRIMARY KEY)") + conn.commit() + conn.close() + + analyzer = SnapshotAnalyzer(db_path=valid_db) + assert analyzer.get_focus().db_path == str(valid_db) + + state = analyzer.set_focus(db_path=str(second_db), device_id=1) + assert state.db_path == str(second_db) + assert state.device_id == 1 + + second_db.unlink(missing_ok=True) + + def test_set_focus_invalid_db(self) -> None: + analyzer = SnapshotAnalyzer() + with pytest.raises(FileNotFoundError): + analyzer.set_focus(db_path="/nonexistent/path/db.sqlite") + + def test_list_templates(self) -> None: + analyzer = SnapshotAnalyzer() + templates = analyzer.list_templates() + assert isinstance(templates, list) + assert len(templates) > 0 + + def test_list_templates_by_category(self) -> None: + analyzer = SnapshotAnalyzer() + result = analyzer.list_templates(category="basic") + assert isinstance(result, list) + + def test_get_template_info_exists(self) -> None: + analyzer = SnapshotAnalyzer() + info = analyzer.get_template_info("leak_detection") + assert info is not None + assert info["name"] == "leak_detection" + assert "description" in info + + def test_get_template_info_not_found(self) -> None: + analyzer = SnapshotAnalyzer() + info = analyzer.get_template_info("nonexistent_template_xyz") + assert info is None + + def test_execute_query_requires_focus(self) -> None: + analyzer = SnapshotAnalyzer() + # Mock resolve_focus to return no configured DB + from pt_snap_cli.config import ResolvedFocus + + with patch.object(analyzer._config, "resolve_focus") as mock_resolve: + mock_resolve.return_value = ResolvedFocus(None, "none", None, None) + with pytest.raises(RuntimeError, match="No database configured"): + analyzer.execute_query("leak_detection") + + def test_execute_query_with_focus(self, valid_db: Path) -> None: + analyzer = SnapshotAnalyzer(db_path=valid_db) + result = analyzer.execute_query("leak_detection", max_rows=10) + assert "total" in result + assert "returned" in result + assert "device_id" in result + assert "rows" in result + assert isinstance(result["rows"], list) + + def test_execute_query_max_rows_zero(self, valid_db: Path) -> None: + """max_rows=0 returns all rows.""" + analyzer = SnapshotAnalyzer(db_path=valid_db) + result = analyzer.execute_query("leak_detection", max_rows=0) + # leak_detection on empty table returns 0 rows + assert result["total"] == 0 + assert result["returned"] == 0 diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py new file mode 100644 index 0000000..8c6944f --- /dev/null +++ b/tests/test_mcp_server.py @@ -0,0 +1,178 @@ +"""Tests for the MCP server module.""" + +import sqlite3 +import tempfile +from pathlib import Path + +import pytest + + +@pytest.fixture +def valid_db() -> Path: + """Create a valid test database.""" + with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f: + db_path = Path(f.name) + + conn = sqlite3.connect(str(db_path)) + conn.execute( + "CREATE TABLE dictionary (" "`table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT)" + ) + conn.execute( + "CREATE TABLE trace_entry_0 (" + "id INTEGER PRIMARY KEY, action INTEGER, address INTEGER, " + "size INTEGER, stream INTEGER, allocated INTEGER, " + "active INTEGER, reserved INTEGER, callstack TEXT)" + ) + conn.execute( + "CREATE TABLE block_0 (" + "id INTEGER PRIMARY KEY, address INTEGER, size INTEGER, " + "requestedSize INTEGER, state INTEGER, allocEventId INTEGER, " + "freeEventId INTEGER)" + ) + conn.commit() + conn.close() + + yield db_path + db_path.unlink(missing_ok=True) + + +@pytest.fixture(autouse=True) +def _reset_registry(): + """Reset the query registry singleton between tests.""" + from pt_snap_cli.query.registry import QueryRegistry + + QueryRegistry.reset() + + +@pytest.fixture(autouse=True) +def _fresh_analyzer(): + """Reset the module-level _analyzer for each test.""" + + import pt_snap_cli.mcp.server as server_mod + + yield + + # Reset the analyzer so it doesn't hold stale state + server_mod._analyzer = type(server_mod._analyzer)() + + +class TestMCPServerStructure: + """Test that the MCP server is properly structured.""" + + def test_mcp_server_is_fastmcp(self) -> None: + """Verify MCP server is a FastMCP instance.""" + from mcp.server.fastmcp import FastMCP + + from pt_snap_cli.mcp.server import mcp + + assert isinstance(mcp, FastMCP) + + def test_mcp_server_name(self) -> None: + """Verify MCP server has correct name.""" + from pt_snap_cli.mcp.server import mcp + + assert mcp.name == "pt-snap" + + def test_mcp_server_has_tool_decorator(self) -> None: + """Verify MCP server has tool decorator.""" + from pt_snap_cli.mcp.server import mcp + + assert hasattr(mcp, "tool") + + def test_mcp_server_has_resource_decorator(self) -> None: + """Verify MCP server has resource decorator.""" + from pt_snap_cli.mcp.server import mcp + + assert hasattr(mcp, "resource") + + def test_mcp_server_has_prompt_decorator(self) -> None: + """Verify MCP server has prompt decorator.""" + from pt_snap_cli.mcp.server import mcp + + assert hasattr(mcp, "prompt") + + +class TestMCPToolFunctions: + """Test MCP tool functions through the analyzer layer.""" + + def test_get_focus_returns_dict(self, valid_db: Path) -> None: + """Test get_focus returns proper dict structure.""" + from pt_snap_cli.api import SnapshotAnalyzer + + analyzer = SnapshotAnalyzer(db_path=valid_db) + state = analyzer.get_focus() + # MCP wrapper converts to dict + result = { + "db_path": state.db_path, + "device_id": state.device_id, + "source": state.source, + "available_devices": state.available_devices, + } + assert isinstance(result, dict) + assert result["db_path"] == str(valid_db) + assert result["source"] == "explicit" + + def test_set_focus_returns_dict(self, valid_db: Path) -> None: + """Test set_focus returns proper dict structure.""" + from pt_snap_cli.api import SnapshotAnalyzer + + analyzer = SnapshotAnalyzer() + state = analyzer.set_focus(db_path=str(valid_db)) + result = { + "db_path": state.db_path, + "device_id": state.device_id, + "available_devices": state.available_devices, + } + assert isinstance(result, dict) + assert result["db_path"] == str(valid_db) + + def test_list_templates_returns_list(self) -> None: + """Test list_templates returns a list of dicts.""" + from pt_snap_cli.api import SnapshotAnalyzer + + analyzer = SnapshotAnalyzer() + result = analyzer.list_templates() + assert isinstance(result, list) + if result: + assert "name" in result[0] + assert "description" in result[0] + + def test_get_template_info(self) -> None: + """Test get_template_info returns template details.""" + from pt_snap_cli.api import SnapshotAnalyzer + + analyzer = SnapshotAnalyzer() + info = analyzer.get_template_info("leak_detection") + assert info is not None + assert "name" in info + assert "parameters" in info + + def test_get_template_info_not_found(self) -> None: + """Test get_template_info handles missing template.""" + from pt_snap_cli.api import SnapshotAnalyzer + + analyzer = SnapshotAnalyzer() + info = analyzer.get_template_info("does_not_exist") + assert info is None + + def test_execute_query_returns_dict(self, valid_db: Path) -> None: + """Test execute_query returns proper dict structure.""" + from pt_snap_cli.api import SnapshotAnalyzer + + analyzer = SnapshotAnalyzer(db_path=valid_db) + result = analyzer.execute_query("leak_detection", max_rows=10) + assert isinstance(result, dict) + assert "total" in result + assert "returned" in result + assert "device_id" in result + assert "rows" in result + + +class TestMCPEntryPoint: + """Test the MCP server entry point.""" + + def test_main_function_exists(self) -> None: + """Verify main() function is defined.""" + from pt_snap_cli.mcp.server import main + + assert callable(main) From 4c2dd716a50499ff54ceb1bb7245b64b4ab46ce5 Mon Sep 17 00:00:00 2001 From: codeasier Date: Mon, 20 Apr 2026 00:42:32 +0800 Subject: [PATCH 2/3] fix: move mcp from optional to core dependency CI installs only core + dev dependencies. Having mcp as optional meant 'pip install -e .[dev]' skipped it, causing all MCP tests to fail with ModuleNotFoundError. --- pyproject.toml | 4 +--- tests/test_mcp_server.py | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d4d02f5..cd9794c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ ] dependencies = [ + "mcp>=1.0.0", "typer>=0.9.0", "pyyaml>=6.0", "jinja2>=3.0.0", @@ -43,9 +44,6 @@ dev = [ "ruff>=0.0.280", "build>=1.0.0", ] -mcp = [ - "mcp>=1.0.0", -] rag = [ "chromadb>=0.4.0", "langchain>=0.1.0", diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 8c6944f..25b649c 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -47,7 +47,6 @@ def _reset_registry(): @pytest.fixture(autouse=True) def _fresh_analyzer(): """Reset the module-level _analyzer for each test.""" - import pt_snap_cli.mcp.server as server_mod yield From c55080711704c66c26f23e072c99e1a1d511d7e5 Mon Sep 17 00:00:00 2001 From: codeasier Date: Mon, 20 Apr 2026 00:47:22 +0800 Subject: [PATCH 3/3] docs: add MCP server documentation Update README (EN/ZH), quickstart guides, and add dedicated MCP docs covering tools, resources, prompts, and usage workflow. --- README.md | 27 ++++++++++++++- README_zh.md | 27 ++++++++++++++- docs/en/mcp.md | 78 +++++++++++++++++++++++++++++++++++++++++++ docs/en/quickstart.md | 1 + docs/zh/mcp.md | 78 +++++++++++++++++++++++++++++++++++++++++++ docs/zh/quickstart.md | 1 + 6 files changed, 210 insertions(+), 2 deletions(-) create mode 100644 docs/en/mcp.md create mode 100644 docs/zh/mcp.md diff --git a/README.md b/README.md index fcfebf3..c504a59 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,28 @@ See the [full quick start guide](docs/en/quickstart.md) for a walkthrough. | `pt-snap focus` | Set and manage analysis focus (database + device) | | `pt-snap query` | Run memory analysis queries | | `pt-snap config` | Manage global configuration | +| `pt-snap-mcp` | Start the MCP server for agent integration | + +## MCP Server + +`pt-snap-cli` provides an MCP (Model Context Protocol) server so AI agents can interact with PyTorch memory snapshots programmatically. + +```bash +# Start the MCP server +pt-snap-mcp +``` + +The server exposes the following tools: + +| Tool | Description | +|------|-------------| +| `get_focus` | Get the current analysis focus | +| `set_focus` | Set focus to a database and optional device | +| `list_templates` | List available query templates | +| `get_template_info` | Get template details and parameters | +| `execute_query` | Run a query template against the focused database | + +See the [MCP guide](docs/en/mcp.md) for setup and usage details. ## Documentation @@ -43,6 +65,7 @@ See the [full quick start guide](docs/en/quickstart.md) for a walkthrough. | Getting started | [Quick Start](docs/en/quickstart.md) | | Managing focus | [Focus Management](docs/en/focus-management.md) | | Running queries | [Querying](docs/en/querying.md) | +| MCP server | [MCP Guide](docs/en/mcp.md) | | Database format | [SnapshotDB Schema](docs/en/database.md) | | Python API | [ResultMapper API](docs/en/result-mapper-api.md) | @@ -65,6 +88,7 @@ pt-snap-cli/ │ ├── cli.py # CLI entry point │ ├── context.py # Database context manager │ ├── config.py # Focus management +│ ├── api.py # Python API layer │ ├── query/ │ │ ├── builder.py # Query builder │ │ ├── executor.py # Query executor @@ -73,7 +97,8 @@ pt-snap-cli/ │ │ ├── condition.py # Query conditions │ │ ├── config.py # Query configuration │ │ └── templates/ # Query templates -│ └── models/ # Data models +│ ├── models/ # Data models +│ └── mcp/ # MCP server for agent integration ├── tests/ # Test files ├── examples/ # Example data └── docs/ # Documentation diff --git a/README_zh.md b/README_zh.md index 73261ba..f8a1160 100644 --- a/README_zh.md +++ b/README_zh.md @@ -35,6 +35,28 @@ pt-snap query --template-use leak_detection --params '{"min_size": 1024}' | `pt-snap focus` | 设置和管理分析焦点(数据库 + 设备) | | `pt-snap query` | 运行内存分析查询 | | `pt-snap config` | 管理全局配置 | +| `pt-snap-mcp` | 启动 MCP 服务器以支持 Agent 集成 | + +## MCP 服务器 + +`pt-snap-cli` 提供了 MCP(Model Context Protocol)服务器,使 AI Agent 能够以编程方式与 PyTorch 内存快照交互。 + +```bash +# 启动 MCP 服务器 +pt-snap-mcp +``` + +服务器暴露以下工具: + +| 工具 | 说明 | +|------|------| +| `get_focus` | 获取当前分析焦点 | +| `set_focus` | 设置焦点到指定数据库和设备 | +| `list_templates` | 列出可用的查询模板 | +| `get_template_info` | 获取模板详情和参数 | +| `execute_query` | 对焦点数据库执行查询模板 | + +详见 [MCP 指南](docs/zh/mcp.md)。 ## 文档 @@ -43,6 +65,7 @@ pt-snap query --template-use leak_detection --params '{"min_size": 1024}' | 入门指南 | [Quick Start](docs/zh/quickstart.md) | | Focus 管理 | [Focus Management](docs/zh/focus-management.md) | | 运行查询 | [Querying](docs/zh/querying.md) | +| MCP 服务器 | [MCP 指南](docs/zh/mcp.md) | | 数据库格式 | [SnapshotDB Schema](docs/zh/database.md) | | Python API | [ResultMapper API](docs/zh/result-mapper-api.md) | @@ -65,6 +88,7 @@ pt-snap-cli/ │ ├── cli.py # CLI 入口 │ ├── context.py # 数据库连接管理器 │ ├── config.py # 焦点管理 +│ ├── api.py # Python API 层 │ ├── query/ │ │ ├── builder.py # 查询构建器 │ │ ├── executor.py # 查询执行器 @@ -73,7 +97,8 @@ pt-snap-cli/ │ │ ├── condition.py # 查询条件 │ │ ├── config.py # 查询配置 │ │ └── templates/ # 查询模板 -│ └── models/ # 数据模型 +│ ├── models/ # 数据模型 +│ └── mcp/ # MCP 服务器(Agent 集成) ├── tests/ # 测试文件 ├── examples/ # 示例数据 └── docs/ # 文档 diff --git a/docs/en/mcp.md b/docs/en/mcp.md new file mode 100644 index 0000000..a8fdd1d --- /dev/null +++ b/docs/en/mcp.md @@ -0,0 +1,78 @@ +# MCP Server + +[中文](../zh/mcp.md) | English + +`pt-snap-cli` provides an MCP (Model Context Protocol) server that allows AI agents to interact with PyTorch memory snapshots programmatically. + +## Installation + +```bash +pip install -e . +``` + +The MCP server is installed as part of the core package. + +## Starting the Server + +```bash +pt-snap-mcp +``` + +This starts a FastMCP server that exposes tools for analyzing PyTorch memory snapshots. + +## Available Tools + +| Tool | Description | +|------|-------------| +| `get_focus` | Get the current analysis focus (database path, device ID, source) | +| `set_focus` | Set focus to a database and optional device. Use before running queries. | +| `list_templates` | List available query templates, optionally filtered by category | +| `get_template_info` | Get detailed information about a template including parameters | +| `execute_query` | Execute a query template against the focused database | + +## Available Resources + +| Resource | Description | +|----------|-------------| +| `focus://current` | Current analysis focus state | + +## Available Prompts + +| Prompt | Description | +|--------|-------------| +| `analyze_memory_leaks` | Generate a prompt template for analyzing memory leaks | + +## Typical Workflow + +1. Call `set_focus` with `db_path` to point to a snapshot file +2. Call `list_templates` to discover available queries +3. Call `get_template_info` with a template name to see its parameters +4. Call `execute_query` with the template name and parameters + +## Example Usage + +```python +# Set focus to a snapshot +set_focus(db_path="/path/to/snapshot.db", device_id=0) + +# List templates +list_templates() +# Returns: [{"name": "leak_detection", "description": "...", ...}, ...] + +# Get template details +get_template_info("leak_detection") +# Returns: {"name": "leak_detection", "parameters": [...], ...} + +# Run a query +execute_query("leak_detection", params={"min_size": 1024}) +# Returns: {"total": 5, "returned": 5, "rows": [...]} +``` + +## CLI Commands + +The MCP entry point is declared in `pyproject.toml`: + +```toml +[project.scripts] +pt-snap-mcp = "pt_snap_cli.mcp.server:main" +``` diff --git a/docs/en/quickstart.md b/docs/en/quickstart.md index 7f3bcb4..1685de9 100644 --- a/docs/en/quickstart.md +++ b/docs/en/quickstart.md @@ -54,4 +54,5 @@ pt-snap query --template-use block --device 1 --state 1 - [Focus Management](focus-management.md) — Learn how to manage database and device focus across projects and sessions - [Querying](querying.md) — Full guide to all query templates, parameters, and output +- [MCP Server](mcp.md) — Use the MCP server for AI agent integration - [Database Schema](database.md) — Understand the SnapshotDB format diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md new file mode 100644 index 0000000..f488083 --- /dev/null +++ b/docs/zh/mcp.md @@ -0,0 +1,78 @@ +# MCP 服务器 + +[English](../en/mcp.md) | 中文 + +`pt-snap-cli` 提供了 MCP(Model Context Protocol)服务器,使 AI Agent 能够以编程方式与 PyTorch 内存快照交互。 + +## 安装 + +```bash +pip install -e . +``` + +MCP 服务器作为核心包的一部分自动安装。 + +## 启动服务器 + +```bash +pt-snap-mcp +``` + +这将启动一个 FastMCP 服务器,暴露用于分析 PyTorch 内存快照的工具。 + +## 可用工具 + +| 工具 | 说明 | +|------|------| +| `get_focus` | 获取当前分析焦点(数据库路径、设备 ID、来源) | +| `set_focus` | 设置焦点到指定数据库和可选设备。运行查询前使用。 | +| `list_templates` | 列出可用的查询模板,可按类别筛选 | +| `get_template_info` | 获取模板详情,包括参数信息 | +| `execute_query` | 对焦点数据库执行查询模板 | + +## 可用资源 + +| 资源 | 说明 | +|------|------| +| `focus://current` | 当前分析焦点状态 | + +## 可用提示词 + +| 提示词 | 说明 | +|--------|------| +| `analyze_memory_leaks` | 生成用于分析内存泄漏的提示词模板 | + +## 典型工作流 + +1. 调用 `set_focus` 并传入 `db_path` 指向快照文件 +2. 调用 `list_templates` 发现可用查询 +3. 调用 `get_template_info` 查看模板参数 +4. 调用 `execute_query` 执行查询 + +## 使用示例 + +```python +# 设置焦点到快照文件 +set_focus(db_path="/path/to/snapshot.db", device_id=0) + +# 列出模板 +list_templates() +# 返回: [{"name": "leak_detection", "description": "...", ...}, ...] + +# 获取模板详情 +get_template_info("leak_detection") +# 返回: {"name": "leak_detection", "parameters": [...], ...} + +# 运行查询 +execute_query("leak_detection", params={"min_size": 1024}) +# 返回: {"total": 5, "returned": 5, "rows": [...]} +``` + +## CLI 命令 + +MCP 入口点在 `pyproject.toml` 中声明: + +```toml +[project.scripts] +pt-snap-mcp = "pt_snap_cli.mcp.server:main" +``` diff --git a/docs/zh/quickstart.md b/docs/zh/quickstart.md index 304fbd9..e241dd6 100644 --- a/docs/zh/quickstart.md +++ b/docs/zh/quickstart.md @@ -54,4 +54,5 @@ pt-snap query --template-use block --device 1 --state 1 - [Focus 管理](focus-management.md) — 学习如何在多个项目和会话之间管理数据库和设备焦点 - [运行查询](querying.md) — 所有查询模板、参数和输出的完整指南 +- [MCP 服务器](mcp.md) — 使用 MCP 服务器进行 AI Agent 集成 - [数据库格式](database.md) — 了解 SnapshotDB 格式