diff --git a/.github/ISSUE_TEMPLATE/AGENTS.md b/.github/ISSUE_TEMPLATE/AGENTS.md index 604ab3b..bb7204a 100644 --- a/.github/ISSUE_TEMPLATE/AGENTS.md +++ b/.github/ISSUE_TEMPLATE/AGENTS.md @@ -23,7 +23,7 @@ ## For AI Agents ### Working In This Directory -- Keep issue forms scoped to this Python CLI/MCP project. +- Keep issue forms scoped to this Python CLI project. - Preserve valid GitHub issue form YAML structure. - Ordering is controlled by numbered filenames; `config.yml` has no `issue_templates` key. diff --git a/AGENTS.md b/AGENTS.md index 261db8b..46597ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,8 +6,8 @@ facts here; user-facing behavior belongs in `README.md` and `docs/`. ## Project Scope `pt-snap-cli` is a Python 3.10+ package for importing, splitting, inspecting, -and querying PyTorch memory snapshots. It exposes a Typer CLI, a Python API, -and an MCP server over shared service-layer behavior. +and querying PyTorch memory snapshots. It exposes a Typer CLI and a Python API +over shared service-layer behavior. ## Development Commands @@ -53,7 +53,6 @@ when they exist. | --- | --- | --- | | CLI | `src/pt_snap_cli/cli.py` via `pt_snap_cli.cli:_safe_call` | Typer commands for focus, import, split, metadata, query, reports, config, and skill install/list | | Python API | `src/pt_snap_cli/api.py` (`SnapshotAnalyzer`) | Programmatic focus, query, and metadata facade | -| MCP | `src/pt_snap_cli/mcp/server.py` via `pt_snap_cli.mcp.server:main` | Agent tools/resources backed by `SnapshotAnalyzer` | | Product services | `src/pt_snap_cli/core/` | Shared focus, import, split, query, report, metadata, and error semantics | | Database access | `src/pt_snap_cli/context.py` | Read-only SQLite validation, connection management, and device discovery | | Query engine | `src/pt_snap_cli/query/` | YAML loading, registry, parameter validation, SQL rendering/execution, and result mapping | @@ -66,12 +65,12 @@ templates under category subdirectories are included by ## Repository Invariants -### CLI, API, and MCP +### CLI and Python API -- Keep normalized CLI and MCP behavior in shared API/core services; adapters may - format output differently but must not redefine focus, query, metadata, or - error semantics. -- Update `tests/test_contract_cli_mcp.py` when a shared CLI/MCP capability or +- Keep normalized CLI and `SnapshotAnalyzer` behavior in shared API/core + services; adapters may format output differently but must not redefine focus, + query, metadata, or error semantics. +- Update `tests/test_contract_cli_api.py` when a shared CLI/API capability or normalized result changes. ### Focus and database selection @@ -100,7 +99,7 @@ templates under category subdirectories are included by leave `callstack_layout` unset and fail only variant templates. Do not persist layout in `focus.json` or migrate databases on open. - When template metadata or behavior changes, review the YAML, config, registry, - executor, `core/query_service.py`, CLI/MCP presentation, and focused tests + executor, `core/query_service.py`, CLI/API presentation, and focused tests together. ### Agent skills @@ -114,8 +113,7 @@ templates under category subdirectories are included by Agent Skills hosts) plus Claude's independent `~/.claude/skills` or `$CLAUDE_CONFIG_DIR/skills`. `--target cursor` and `--target codex` keep the host-native extras; `--dir` covers anything else. List reports - `installed`, `outdated`, or `missing`. Skill management is CLI-only and - is not exposed on the MCP server. + `installed`, `outdated`, or `missing`. Skill management is CLI-only. ### Snapshot import and split @@ -140,7 +138,7 @@ templates under category subdirectories are included by | Focus precedence or persistence | `src/pt_snap_cli/config.py`, `src/pt_snap_cli/core/focus_service.py`, `src/pt_snap_cli/context.py` | `tests/test_config.py`, `tests/test_context.py`, `tests/core/test_focus_service.py` | | Context/executor caching | `src/pt_snap_cli/core/context_cache.py`, `src/pt_snap_cli/api.py`, `src/pt_snap_cli/core/query_service.py` | `tests/core/test_context_cache.py`, `tests/test_snapshot_analyzer_cache.py`, `tests/test_query_cache_perf.py` | | Query schema, SQL, or categories | `src/pt_snap_cli/query/`, `src/pt_snap_cli/core/query_service.py` | `tests/query/`, `tests/core/test_query_service.py` | -| MCP or Python API behavior | `src/pt_snap_cli/api.py`, `src/pt_snap_cli/mcp/server.py` | `tests/test_api.py`, `tests/test_mcp_server.py`, `tests/test_contract_cli_mcp.py` | +| Python API behavior | `src/pt_snap_cli/api.py` | `tests/test_api.py`, `tests/test_contract_cli_api.py` | | Snapshot import or metadata | `src/pt_snap_cli/core/import_service.py`, `src/pt_snap_cli/core/import_metadata.py`, `src/pt_snap_cli/core/snapshot_import_backend.py` | `tests/core/test_import_*.py`, `tests/test_snapshot_db.py` | | Snapshot splitting or replay | `src/pt_snap_cli/core/split_service.py`, `src/pt_snap_cli/snapshot/` | `tests/core/test_split_service.py`, `tests/snapshot/` | | Reports | `src/pt_snap_cli/core/report_service.py`, report commands in `src/pt_snap_cli/cli.py` | `tests/core/test_report_service.py`, report cases in `tests/test_cli.py` | diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c9639c..c86df73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [0.4.0] - Unreleased + +本次发布将 Agent 集成入口统一到 bundled skills 与 CLI,并关闭 MCP 产品面。这是 0.x 阶段的 breaking 变更。 + +### 破坏性变更 + +- 移除 `pt-snap-mcp` 控制台入口、`src/pt_snap_cli/mcp/` 与核心依赖 `mcp`。安装 `pt-snap-cli`(无 extra)后依赖树不再包含 `mcp`、`starlette` 或 `uvicorn`。 +- Agent 集成改为 skills + `pt-snap` CLI。`SnapshotAnalyzer` Python API 保留;`execute_query()` 默认仍为 `max_rows=None`(不截断),缺模板时 `get_template_info()` 仍返回 `None`。 + +### 兼容性提示 + +- 已配置 `pt-snap-mcp` 或 MCP 客户端的调用方需改用 CLI、bundled skills 或 Python API。历史 CHANGELOG 中的 MCP 条目仅作记录,不再对应已发布入口。 + ## [0.3.0] - 2026-09-17 本次发布聚焦 Agent 诊断技能与查询/导入性能:新增内存泄漏、碎片、峰值拆解与 Ascend NPU 采集等诊断 skill、`pt-snap skill` 共享安装命令及本地 skill 评测框架;SnapshotDB 采用去重 callstack 存储,叠加查询执行层优化,使导入、拆分与查询获得数量级加速,同时只读兼容 v1/v2 两种 callstack 布局;pickle 加载收敛到内建类型白名单,进一步降低反序列化风险。 diff --git a/README.md b/README.md index d972d2e..2d93f1f 100644 --- a/README.md +++ b/README.md @@ -64,20 +64,12 @@ See the [full quick start guide](docs/en/quickstart.md) for a walkthrough. | `pt-snap report` | Generate higher-level memory analysis reports | | `pt-snap config` | Manage global configuration | | `pt-snap skill` | List and install bundled agent skills | -| `pt-snap-mcp` | Start the MCP server for agent integration | `pt-snap --help` includes an agent hint: prefer `--json` where supported, start with the `pt-snap-helper` skill, and check availability with `pt-snap skill list --json`. -## MCP Server +## Agent Skills -`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 -``` - -See the [MCP guide](docs/en/mcp.md) for setup and usage details. +Install bundled diagnostic workflows with `pt-snap skill install`. Agent integration uses skills plus the CLI; there is no MCP server. See the [Agent Skills guide](docs/en/skills.md). ## Documentation @@ -90,7 +82,6 @@ See the [documentation index](docs/README.md) for all English and Chinese guides | Running queries | [Querying](docs/en/querying.md) | | Splitting snapshots | [Splitting Snapshots](docs/en/splitting.md) | | Agent skills | [Agent Skills](docs/en/skills.md) | -| MCP server | [MCP Guide](docs/en/mcp.md) | | Database format | [SnapshotDB Schema](docs/en/database.md) | | Python API | [SnapshotAnalyzer API](docs/en/snapshot-analyzer-api.md) | | Result mapping utility | [ResultMapper API](docs/en/result-mapper-api.md) | diff --git a/README_zh.md b/README_zh.md index e1008fd..fb6fcb1 100644 --- a/README_zh.md +++ b/README_zh.md @@ -59,20 +59,12 @@ pt-snap split snapshot.pkl --slices 4 --output snapshot-slices | `pt-snap report` | 生成高层内存分析报告 | | `pt-snap config` | 管理全局配置 | | `pt-snap skill` | 列出并安装随包 agent skill | -| `pt-snap-mcp` | 启动 MCP 服务器以支持 Agent 集成 | `pt-snap --help` 含 Agent 提示:在当前已支持的命令上优先使用 `--json`,从 `pt-snap-helper` skill 开始,并用 `pt-snap skill list --json` 检查是否已安装。 -## MCP 服务器 +## Agent Skills -`pt-snap-cli` 提供了 MCP(Model Context Protocol)服务器,使 AI Agent 能够以编程方式与 PyTorch 内存快照交互。 - -```bash -# 启动 MCP 服务器 -pt-snap-mcp -``` - -详见 [MCP 指南](docs/zh/mcp.md)。 +使用 `pt-snap skill install` 安装随包诊断工作流。Agent 集成入口是 skills 与 CLI,不再提供 MCP 服务器。详见 [Agent Skills 指南](docs/zh/skills.md)。 ## 文档 @@ -85,7 +77,6 @@ pt-snap-mcp | 运行查询 | [Querying](docs/zh/querying.md) | | 拆分快照 | [拆分快照](docs/zh/splitting.md) | | Agent skill | [Agent Skills](docs/zh/skills.md) | -| MCP 服务器 | [MCP 指南](docs/zh/mcp.md) | | 数据库格式 | [SnapshotDB Schema](docs/zh/database.md) | | Python API | [SnapshotAnalyzer API](docs/zh/snapshot-analyzer-api.md) | | 结果映射工具 | [ResultMapper API](docs/zh/result-mapper-api.md) | diff --git a/docs/AGENTS.md b/docs/AGENTS.md index ab1e6d8..e374a2e 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -4,7 +4,7 @@ # docs ## Purpose -`docs` contains end-user and API documentation for the CLI, focus management, query templates, agent skills, MCP integration, snapshot database format, high-level and result mapping Python APIs, and retained legal evidence. It is split into English and Chinese language trees with a top-level README for navigation. +`docs` contains end-user and API documentation for the CLI, focus management, query templates, agent skills, snapshot database format, high-level and result mapping Python APIs, and retained legal evidence. It is split into English and Chinese language trees with a top-level README for navigation. ## Key Files | File | Description | @@ -22,7 +22,7 @@ ### Working In This Directory - Keep English and Chinese docs synchronized when changing user-visible behavior. -- Verify command names, options, template names, and MCP tool names against source code before updating docs. +- Verify command names, options, and template names against source code before updating docs. - Prefer updating existing guides over creating new documentation pages. ### Testing Requirements @@ -30,13 +30,12 @@ - If examples depend on behavior changes, run the matching CLI or service tests. ### Common Patterns -- The two language trees mirror the same topics: quick start, focus management, querying, snapshot splitting, agent skills, MCP, database schema, SnapshotAnalyzer API, and result mapper API. +- The two language trees mirror the same topics: quick start, focus management, querying, snapshot splitting, agent skills, database schema, SnapshotAnalyzer API, and result mapper API. ## Dependencies ### Internal - `src/pt_snap_cli/cli.py` defines documented CLI commands and options. -- `src/pt_snap_cli/mcp/server.py` defines documented MCP tools, resource, and prompt. - `src/pt_snap_cli/query/templates/` defines documented built-in template names and parameters. ### External diff --git a/docs/README.md b/docs/README.md index 8d30a33..619d4f1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,7 +11,6 @@ | Reports | [en/querying.md](en/querying.md) | | Splitting Snapshots | [en/splitting.md](en/splitting.md) | | Agent skills | [en/skills.md](en/skills.md) | -| MCP server | [en/mcp.md](en/mcp.md) | | Database Schema | [en/database.md](en/database.md) | | Import metadata | [en/database.md](en/database.md) | | SnapshotAnalyzer API | [en/snapshot-analyzer-api.md](en/snapshot-analyzer-api.md) | @@ -28,7 +27,6 @@ | 分析报告 | [zh/querying.md](zh/querying.md) | | 拆分快照 | [zh/splitting.md](zh/splitting.md) | | Agent skill | [zh/skills.md](zh/skills.md) | -| MCP 服务器 | [zh/mcp.md](zh/mcp.md) | | 数据库格式 | [zh/database.md](zh/database.md) | | 导入 metadata | [zh/database.md](zh/database.md) | | SnapshotAnalyzer API | [zh/snapshot-analyzer-api.md](zh/snapshot-analyzer-api.md) | diff --git a/docs/en/AGENTS.md b/docs/en/AGENTS.md index 4f3521f..ebea246 100644 --- a/docs/en/AGENTS.md +++ b/docs/en/AGENTS.md @@ -4,7 +4,7 @@ # en ## Purpose -`docs/en` contains the English documentation set for installing and using `pt-snap-cli`, managing focus, querying and splitting snapshots, installing bundled agent skills, running the MCP server, understanding the SQLite schema, and using the high-level and result mapping Python APIs. +`docs/en` contains the English documentation set for installing and using `pt-snap-cli`, managing focus, querying and splitting snapshots, installing bundled agent skills, understanding the SQLite schema, and using the high-level and result mapping Python APIs. ## Key Files | File | Description | @@ -14,7 +14,6 @@ | `querying.md` | Query listing, template info, parameter usage, result limits, and built-in templates. | | `splitting.md` | Snapshot slicing strategies, output formats, replay validation, and publication guarantees. | | `skills.md` | Bundled agent-skill listing, helper entry, install destinations, and status meanings. | -| `mcp.md` | MCP server setup, tools, resources, prompts, and agent usage. | | `database.md` | Snapshot SQLite table/schema reference. | | `snapshot-analyzer-api.md` | High-level Python API for focus, template discovery, queries, and import metadata. | | `result-mapper-api.md` | Result mapping API documentation. | @@ -41,7 +40,7 @@ ## Dependencies ### Internal -- CLI, MCP, query template, and schema details should be checked against `src/pt_snap_cli/` before editing. +- CLI, query template, and schema details should be checked against `src/pt_snap_cli/` before editing. ### External - Markdown only. diff --git a/docs/en/database.md b/docs/en/database.md index 0a1c150..f6a3e1b 100644 --- a/docs/en/database.md +++ b/docs/en/database.md @@ -339,7 +339,7 @@ on each `trace_entry_` table and have no shared `callstack` table template name, parameter set, and output schema. The query engine selects v1 or v2 SQL from the detected layout. Other templates do not depend on this split. -Detection is read-only: `focus`, `query`, reports, the Python API, and MCP all +Detection is read-only: `focus`, `query`, reports, and the Python API all open the database with SQLite `mode=ro`. Layout is not stored in `.pt-snap/focus.json`. Conflicting columns, mixed devices, a damaged `callstack` table, or metadata that disagrees with the physical schema leave diff --git a/docs/en/mcp.md b/docs/en/mcp.md deleted file mode 100644 index dd2ddb6..0000000 --- a/docs/en/mcp.md +++ /dev/null @@ -1,112 +0,0 @@ -# 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 pt-snap-cli -``` - -The MCP server is installed as part of the core package. Contributors working -from a source checkout can use `pip install -e ".[dev]"`; see -[Development](../../README.md#development) in the repository README. - -## 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. Returns at most `max_rows` rows (default **100**; pass `0` for unlimited). See [Query Results and Row Limits](#query-results-and-row-limits). | -| `get_database_metadata` | Inspect import provenance for the focused or specified 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 SnapshotDB `.db` 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 -5. Call `get_database_metadata` when import provenance or cache compatibility is needed - -## Example Usage - -```python -# Set focus to a SnapshotDB file -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": {"min_size": {...}}, ...} - -# Run a query -execute_query("leak_detection", params={"min_size": 1024}) -# Returns: {"total": 5, "returned": 5, "device_id": 0, "rows": [...]} - -# Inspect database import metadata -get_database_metadata() -# Returns: {"status": "available", "metadata": {"source_sha256": "...", ...}} -``` - -## Query Results and Row Limits - -`execute_query(template, params=None, device_id=None, max_rows=100)` returns: - -| Field | Meaning | -|-------|---------| -| `total` | Number of rows the query matches. This is exact even when the result was capped: when `max_rows` is hit, the server runs a `COUNT(*)` over the same query. | -| `returned` | Number of rows actually included in `rows`. | -| `device_id` | The device the query ran against (explicit `device_id`, else the focused device, else the first device in the database). | -| `rows` | The result rows as dictionaries of raw SQLite values. | - -**The MCP default is `max_rows=100`, which differs from the CLI.** `pt-snap query` -shows every row unless `-n` is given; the MCP tool caps output so a large result -cannot flood an agent's context. Treat `returned < total` as "more data exists": -raise `max_rows`, pass `0` for unlimited, or narrow the query parameters. Do not -sum or count over `rows` as if it were the complete result. - -```python -result = execute_query("leak_detection", params={"min_size": 1024}) -if result["returned"] < result["total"]: - result = execute_query("leak_detection", params={"min_size": 1024}, max_rows=0) -``` - -Templates that expose a `limit` parameter (for example `leak_detection`, -`allocation`, `block`, `event`) apply `min(limit, max_rows)` when both are set. - -## 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/querying.md b/docs/en/querying.md index f8b3d10..89a4d2c 100644 --- a/docs/en/querying.md +++ b/docs/en/querying.md @@ -95,8 +95,8 @@ pt-snap query --template-info allocation pt-snap query --template-use allocation --params '{"order_by": "reserved", "order_dir": "desc"}' -n 5 ``` -The same rules apply to `SnapshotAnalyzer.execute_query()` and the MCP -`execute_query` tool, which raise `TemplateRenderError` with the same message. +The same rules apply to `SnapshotAnalyzer.execute_query()`, which raises +`TemplateRenderError` with the same message. ## Peak Memory Attribution Workflow @@ -214,11 +214,10 @@ Found 150 results, showing 2: ... and 148 more (use -n to show more) ``` -The "Found N" count is exact even when output is capped. Note that the MCP -`execute_query` tool applies a default cap of 100 rows, unlike the CLI; see -[MCP Server: Query Results and Row Limits](mcp.md#query-results-and-row-limits). +The "Found N" count is exact even when output is capped. `SnapshotAnalyzer.execute_query()` +defaults to `max_rows=None` (no cap), matching the CLI unless `-n` / `max_rows` is set. -CLI, Python API, and MCP query results contain raw SQLite values. A template's +CLI and Python API query results contain raw SQLite values. A template's `output_schema` is metadata and is not applied automatically during query execution. Use `ResultMapper` explicitly when converted values such as hexadecimal address strings are required. diff --git a/docs/en/quickstart.md b/docs/en/quickstart.md index 8e440f0..ba08d6b 100644 --- a/docs/en/quickstart.md +++ b/docs/en/quickstart.md @@ -106,6 +106,5 @@ pt-snap query --template-use block --device 0 --params '{"min_size": 1048576}' - [Querying](querying.md) — Query workflows, template discovery, parameters, and output - [Splitting Snapshots](splitting.md) — Create independently replayable per-device slices - [Agent Skills](skills.md) — Install bundled agent workflows into the shared agents directory and Claude -- [MCP Server](mcp.md) — Use the MCP server for AI agent integration - [Database Schema](database.md) — Understand the SnapshotDB format - [SnapshotAnalyzer API](snapshot-analyzer-api.md) — Query SnapshotDB files from Python diff --git a/docs/en/skills.md b/docs/en/skills.md index ff4d994..20b047e 100644 --- a/docs/en/skills.md +++ b/docs/en/skills.md @@ -86,4 +86,4 @@ After an install, upgrade, or uninstall that changes skill files, restart the ag | `pt-snap-memory-peak-breakdown` | Explaining active memory at a peak event | | `pt-snap-memory-fragmentation` | Diagnosing allocator gaps and reserved-pool pressure | -Skill management is CLI-only. The MCP server does not install, upgrade, or uninstall skills. +Skill management is CLI-only. diff --git a/docs/zh/AGENTS.md b/docs/zh/AGENTS.md index 174b895..7652dda 100644 --- a/docs/zh/AGENTS.md +++ b/docs/zh/AGENTS.md @@ -4,7 +4,7 @@ # zh ## Purpose -`docs/zh` contains the Chinese documentation set for `pt-snap-cli`, covering the same user-facing areas as the English docs: quick start, focus management, querying, snapshot splitting, agent skills, MCP integration, database schema, and the high-level and result mapping Python APIs. +`docs/zh` contains the Chinese documentation set for `pt-snap-cli`, covering the same user-facing areas as the English docs: quick start, focus management, querying, snapshot splitting, agent skills, database schema, and the high-level and result mapping Python APIs. ## Key Files | File | Description | @@ -14,7 +14,6 @@ | `querying.md` | Chinese guide to query templates, parameters, and output. | | `splitting.md` | Chinese guide to snapshot slicing, formats, replay validation, and publication. | | `skills.md` | Chinese guide to bundled agent-skill listing, helper entry, and installation. | -| `mcp.md` | Chinese MCP server setup and tool reference. | | `database.md` | Chinese snapshot SQLite schema reference. | | `snapshot-analyzer-api.md` | Chinese guide to the high-level focus, query, and metadata Python API. | | `result-mapper-api.md` | Chinese result mapping API guide. | @@ -31,7 +30,7 @@ - Preserve Chinese terminology consistently across guides. ### Testing Requirements -- Verify commands, options, template names, and MCP tools against source before editing examples. +- Verify commands, options, and template names against source before editing examples. ### Common Patterns - Files mirror the English documentation topics one-for-one. diff --git a/docs/zh/database.md b/docs/zh/database.md index 9a37e6e..0c8c616 100644 --- a/docs/zh/database.md +++ b/docs/zh/database.md @@ -326,7 +326,7 @@ CREATE TABLE callstack ( 模板名、参数和输出契约。查询引擎按识别到的布局选择 v1 或 v2 SQL。其他模板不依赖 这次拆分。 -识别过程是只读的:`focus`、`query`、报告、Python API 和 MCP 都以 SQLite +识别过程是只读的:`focus`、`query`、报告和 Python API 都以 SQLite `mode=ro` 打开数据库。布局不会写入 `.pt-snap/focus.json`。列冲突、设备布局不一致、 损坏的 `callstack` 表,或 metadata 与物理结构不一致时,布局保持无法识别,并且 只有调用栈模板会报错;不会猜测布局,也不会阻止 focus、metadata 和其他查询。 diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md deleted file mode 100644 index ea607b0..0000000 --- a/docs/zh/mcp.md +++ /dev/null @@ -1,110 +0,0 @@ -# MCP 服务器 - -[English](../en/mcp.md) | 中文 - -`pt-snap-cli` 提供了 MCP(Model Context Protocol)服务器,使 AI Agent 能够以编程方式与 PyTorch 内存快照交互。 - -## 安装 - -```bash -pip install pt-snap-cli -``` - -MCP 服务器作为核心包的一部分自动安装。从源码 checkout 开发时,可使用 -`pip install -e ".[dev]"`;详见仓库 README 的[开发](../../README_zh.md#开发)一节。 - -## 启动服务器 - -```bash -pt-snap-mcp -``` - -这将启动一个 FastMCP 服务器,暴露用于分析 PyTorch 内存快照的工具。 - -## 可用工具 - -| 工具 | 说明 | -|------|------| -| `get_focus` | 获取当前分析焦点(数据库路径、设备 ID、来源) | -| `set_focus` | 设置焦点到指定数据库和可选设备。运行查询前使用。 | -| `list_templates` | 列出可用的查询模板,可按类别筛选 | -| `get_template_info` | 获取模板详情,包括参数信息 | -| `execute_query` | 对焦点数据库执行查询模板。最多返回 `max_rows` 行(默认 **100**;传 `0` 表示不限制)。见[查询结果与行数限制](#查询结果与行数限制)。 | -| `get_database_metadata` | 查看焦点或指定数据库的导入来源 metadata | - -## 可用资源 - -| 资源 | 说明 | -|------|------| -| `focus://current` | 当前分析焦点状态 | - -## 可用提示词 - -| 提示词 | 说明 | -|--------|------| -| `analyze_memory_leaks` | 生成用于分析内存泄漏的提示词模板 | - -## 典型工作流 - -1. 调用 `set_focus` 并传入 `db_path` 指向 SnapshotDB `.db` 文件 -2. 调用 `list_templates` 发现可用查询 -3. 调用 `get_template_info` 查看模板参数 -4. 调用 `execute_query` 执行查询 -5. 需要确认导入来源或缓存兼容性时调用 `get_database_metadata` - -## 使用示例 - -```python -# 设置焦点到 SnapshotDB 文件 -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": {"min_size": {...}}, ...} - -# 运行查询 -execute_query("leak_detection", params={"min_size": 1024}) -# 返回: {"total": 5, "returned": 5, "device_id": 0, "rows": [...]} - -# 查看数据库导入 metadata -get_database_metadata() -# 返回: {"status": "available", "metadata": {"source_sha256": "...", ...}} -``` - -## 查询结果与行数限制 - -`execute_query(template, params=None, device_id=None, max_rows=100)` 的返回值: - -| 字段 | 含义 | -|------|------| -| `total` | 查询匹配的总行数。即使结果被截断,这个值也是精确的:命中 `max_rows` 时服务端会对同一查询额外执行一次 `COUNT(*)`。 | -| `returned` | `rows` 中实际包含的行数。 | -| `device_id` | 查询实际使用的设备(显式 `device_id`,否则为焦点设备,否则为数据库中的第一个设备)。 | -| `rows` | 结果行,每行是原始 SQLite 值组成的字典。 | - -**MCP 的默认值是 `max_rows=100`,与 CLI 不同。** `pt-snap query` 在没有 `-n` 时 -显示全部行;MCP 工具则限制输出,避免大结果集撑爆 agent 的上下文。把 -`returned < total` 理解为"还有更多数据":提高 `max_rows`、传 `0` 取消限制,或收紧 -查询参数。不要把 `rows` 当作完整结果去求和或计数。 - -```python -result = execute_query("leak_detection", params={"min_size": 1024}) -if result["returned"] < result["total"]: - result = execute_query("leak_detection", params={"min_size": 1024}, max_rows=0) -``` - -带 `limit` 参数的模板(如 `leak_detection`、`allocation`、`block`、`event`)在两者 -都设置时取 `min(limit, max_rows)`。 - -## CLI 命令 - -MCP 入口点在 `pyproject.toml` 中声明: - -```toml -[project.scripts] -pt-snap-mcp = "pt_snap_cli.mcp.server:main" -``` diff --git a/docs/zh/querying.md b/docs/zh/querying.md index 6c85357..a8f0c68 100644 --- a/docs/zh/querying.md +++ b/docs/zh/querying.md @@ -94,8 +94,8 @@ pt-snap query --template-info allocation pt-snap query --template-use allocation --params '{"order_by": "reserved", "order_dir": "desc"}' -n 5 ``` -`SnapshotAnalyzer.execute_query()` 和 MCP 的 `execute_query` 工具遵循同样的规则, -并以相同的错误信息抛出 `TemplateRenderError`。 +`SnapshotAnalyzer.execute_query()` 遵循同样的规则,并以相同的错误信息抛出 +`TemplateRenderError`。 ## 峰值内存归因工作流 @@ -207,10 +207,10 @@ Found 150 results, showing 2: ... and 148 more (use -n to show more) ``` -即使输出被截断,"Found N" 的计数也是精确的。注意 MCP 的 `execute_query` 工具默认 -最多返回 100 行,与 CLI 不同;见[MCP 服务器:查询结果与行数限制](mcp.md#查询结果与行数限制)。 +即使输出被截断,"Found N" 的计数也是精确的。`SnapshotAnalyzer.execute_query()` +默认 `max_rows=None`(不截断),与 CLI 在未指定 `-n` / `max_rows` 时一致。 -CLI、Python API 和 MCP 的查询结果包含原始 SQLite 值。模板的 `output_schema` +CLI 和 Python API 的查询结果包含原始 SQLite 值。模板的 `output_schema` 只是 metadata,查询执行时不会自动应用。需要十六进制地址字符串等转换值时, 应显式调用 `ResultMapper`。 diff --git a/docs/zh/quickstart.md b/docs/zh/quickstart.md index 5023590..9a82241 100644 --- a/docs/zh/quickstart.md +++ b/docs/zh/quickstart.md @@ -99,6 +99,5 @@ pt-snap query --template-use block --device 0 --params '{"min_size": 1048576}' - [运行查询](querying.md) — 查询流程、模板发现、参数和输出说明 - [拆分快照](splitting.md) — 创建可独立回放的逐设备切片 - [Agent Skills](skills.md) — 将随包 agent 工作流安装到共享 agents 目录和 Claude -- [MCP 服务器](mcp.md) — 使用 MCP 服务器进行 AI Agent 集成 - [数据库格式](database.md) — 了解 SnapshotDB 格式 - [SnapshotAnalyzer API](snapshot-analyzer-api.md) — 从 Python 查询 SnapshotDB 文件 diff --git a/docs/zh/skills.md b/docs/zh/skills.md index 3077bf9..1174c2b 100644 --- a/docs/zh/skills.md +++ b/docs/zh/skills.md @@ -86,4 +86,4 @@ pt-snap skill uninstall --project --target cursor | `pt-snap-memory-peak-breakdown` | 解释峰值事件上的 active 内存 | | `pt-snap-memory-fragmentation` | 诊断分配器空洞和 reserved 池压力 | -Skill 管理只通过 CLI 提供。MCP 服务器不负责安装、升级或卸载 skill。 +Skill 管理只通过 CLI 提供。 diff --git a/pyproject.toml b/pyproject.toml index 9615eed..f5798ec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,6 @@ classifiers = [ ] dependencies = [ - "mcp>=1.0.0,<2", "typer>=0.9.0", "pyyaml>=6.0", "jinja2>=3.0.0", @@ -48,7 +47,6 @@ dev = [ [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"] diff --git a/src/AGENTS.md b/src/AGENTS.md index d75e13f..675d590 100644 --- a/src/AGENTS.md +++ b/src/AGENTS.md @@ -4,7 +4,7 @@ # src ## Purpose -`src` contains the installable Python package for `pt-snap-cli`. Its only package subtree, `pt_snap_cli`, holds the CLI, MCP server, product services, query system, first-party snapshot runtime, and domain models shipped in the distribution. +`src` contains the installable Python package for `pt-snap-cli`. Its only package subtree, `pt_snap_cli`, holds the CLI, product services, query system, first-party snapshot runtime, and domain models shipped in the distribution. ## Key Files | File | Description | diff --git a/src/pt_snap_cli/AGENTS.md b/src/pt_snap_cli/AGENTS.md index 63b627a..95174ad 100644 --- a/src/pt_snap_cli/AGENTS.md +++ b/src/pt_snap_cli/AGENTS.md @@ -4,13 +4,13 @@ # pt_snap_cli ## Purpose -`pt_snap_cli` is the main Python package. It exposes the Typer CLI, programmatic `SnapshotAnalyzer` API, read-only SQLite context, focus configuration, product service layer, MCP server, domain models, YAML-driven query execution pipeline, and first-party snapshot runtime. +`pt_snap_cli` is the main Python package. It exposes the Typer CLI, programmatic `SnapshotAnalyzer` API, read-only SQLite context, focus configuration, product service layer, domain models, YAML-driven query execution pipeline, and first-party snapshot runtime. ## Key Files | File | Description | |------|-------------| | `__init__.py` | Package exports and version wiring. | -| `api.py` | High-level `SnapshotAnalyzer` API used by MCP and library callers. | +| `api.py` | High-level `SnapshotAnalyzer` API for library callers. | | `cli.py` | Typer CLI entrypoint for focus, import, split, metadata, query, report, config, and skill commands. | | `completion.py` | Shell completion helpers for templates, categories, and device IDs. | | `config.py` | Atomic focus persistence and resolution across explicit paths, environment, project focus, and legacy global config. | @@ -21,7 +21,6 @@ | Directory | Purpose | |-----------|---------| | `core/` | Shared focus, import, split, metadata, query, and report services (see `core/AGENTS.md`). | -| `mcp/` | FastMCP server entrypoint and tools (see `mcp/AGENTS.md`). | | `models/` | Domain models for snapshot blocks, events, and enums (see `models/AGENTS.md`). | | `query/` | Query builders, config loading, execution, mapping, registry, and templates (see `query/AGENTS.md`). | | `snapshot/` | Snapshot representation, replay, database adaptors, and slicing for explicitly trusted inputs (see `snapshot/AGENTS.md`). | @@ -30,8 +29,8 @@ ## For AI Agents ### Working In This Directory -- Route user-facing command logic through `core` services when practical so CLI, API, and MCP behavior remain aligned. -- Skill list/install/upgrade/uninstall is CLI-only; do not expose it on MCP. +- Route user-facing command logic through `core` services when practical so CLI and API behavior remain aligned. +- Skill list/install/upgrade/uninstall is CLI-only. - Preserve focus precedence: explicit CLI/API path, `PT_SNAP_DB_PATH`, nearest project `.pt-snap/focus.json`, then legacy global config. - Keep SQLite access read-only for analysis paths. - When adding or changing a repository skill under `skills/`, copy the same `SKILL.md` into `bundled_skills//`. @@ -43,7 +42,7 @@ ### Testing Requirements - CLI changes should update/run `tests/test_cli.py` and any affected config/focus tests. - Skill catalog or install changes should update/run `tests/core/test_skill_service.py` and `tests/test_bundled_skills.py`. -- API or MCP changes should update/run `tests/test_api.py`, `tests/test_mcp_server.py`, and `tests/test_contract_cli_mcp.py` when shared semantics change. +- API changes should update/run `tests/test_api.py` and `tests/test_contract_cli_api.py` when shared semantics change. - Context or config changes should update/run `tests/test_context.py` and `tests/test_config.py`. - Import, split, and report changes should run their focused `tests/core/` suites; add `tests/snapshot/` when import/split changes cross into the runtime. @@ -62,7 +61,6 @@ ### External - `typer` for CLI commands and output. - `sqlite3` standard library for database access. -- `mcp` for agent server integration. - `jinja2` and `pyyaml` through the query subsystem. diff --git a/src/pt_snap_cli/api.py b/src/pt_snap_cli/api.py index 683b142..3729637 100644 --- a/src/pt_snap_cli/api.py +++ b/src/pt_snap_cli/api.py @@ -46,7 +46,7 @@ def __init__( self._device_id = device_id self._focus_service = FocusService(self._config) # Share one context cache across the analyzer so that long-lived - # analyzers (e.g. the MCP server singleton) reuse a single + # SnapshotAnalyzer instances reuse a single # SQLite connection and skip schema validation on every query. # Explicit ``is not None`` because an empty cache is falsy via # ``__len__`` and would be silently replaced otherwise. diff --git a/src/pt_snap_cli/context.py b/src/pt_snap_cli/context.py index 5e334b5..f15118d 100644 --- a/src/pt_snap_cli/context.py +++ b/src/pt_snap_cli/context.py @@ -33,7 +33,7 @@ class Context: By default the underlying SQLite connection is opened and closed for every ``connect()`` context. Pass ``persistent=True`` to keep the connection alive across calls so that long-lived owners (e.g. a ``ContextCache`` - shared by an MCP server) can avoid the per-query open/close cost. + shared by a long-lived SnapshotAnalyzer) can avoid the per-query open/close cost. Persistent contexts still close their connection when ``close()`` is invoked explicitly. """ diff --git a/src/pt_snap_cli/core/AGENTS.md b/src/pt_snap_cli/core/AGENTS.md index 4f8e384..30256f6 100644 --- a/src/pt_snap_cli/core/AGENTS.md +++ b/src/pt_snap_cli/core/AGENTS.md @@ -4,7 +4,7 @@ # core ## Purpose -`core` contains the product service layer shared by CLI, Python API, and MCP adapters. It owns focus, import publication and metadata, snapshot splitting, query orchestration, reports, CLI-only agent-skill install/list, stable result models, and domain-specific errors over lower-level config, context, query, and snapshot modules. +`core` contains the product service layer shared by CLI and Python API adapters. It owns focus, import publication and metadata, snapshot splitting, query orchestration, reports, CLI-only agent-skill install/list, stable result models, and domain-specific errors over lower-level config, context, query, and snapshot modules. ## Key Files | File | Description | @@ -32,7 +32,7 @@ ### Working In This Directory - Translate low-level exceptions into `core.errors` so CLI and API callers receive consistent failures. - Preserve explicit device precedence over focused device, and validate devices against `Context.device_ids`. -- Keep service models stable when changing CLI/API/MCP output shapes. +- Keep service models stable when changing CLI/API output shapes. - Preserve existing import destinations when publication or the requested focus update fails, and never replace an existing split destination. ### Testing Requirements diff --git a/src/pt_snap_cli/core/context_cache.py b/src/pt_snap_cli/core/context_cache.py index 176ed38..296c6e0 100644 --- a/src/pt_snap_cli/core/context_cache.py +++ b/src/pt_snap_cli/core/context_cache.py @@ -1,7 +1,7 @@ """LRU cache for read-only SQLite ``Context`` instances. -The cache exists so that long-lived owners (e.g. the MCP server, which keeps -a single :class:`SnapshotAnalyzer` alive across many tool calls) can reuse a +The cache exists so that long-lived owners (e.g. a long-lived +:class:`~pt_snap_cli.api.SnapshotAnalyzer`) can reuse a single :class:`pt_snap_cli.context.Context` -- and its persistent read-only SQLite connection -- instead of paying the cost of ``dictionary`` schema validation, device discovery, and a fresh ``sqlite3.connect`` URI handshake on diff --git a/src/pt_snap_cli/core/query_service.py b/src/pt_snap_cli/core/query_service.py index 71a293d..6e69f26 100644 --- a/src/pt_snap_cli/core/query_service.py +++ b/src/pt_snap_cli/core/query_service.py @@ -38,8 +38,8 @@ def __init__( context_cache: ContextCache | None = None, ) -> None: self._focus_service = focus_service or FocusService() - # Cache Context instances across calls so long-lived owners (MCP - # server, SnapshotAnalyzer) skip the per-call schema validation and + # Cache Context instances across calls so long-lived SnapshotAnalyzer + # owners skip the per-call schema validation and # SQLite connect/close handshake. See ContextCache for the LRU and # mtime invalidation semantics. self._context_cache = context_cache if context_cache is not None else ContextCache() diff --git a/src/pt_snap_cli/mcp/AGENTS.md b/src/pt_snap_cli/mcp/AGENTS.md deleted file mode 100644 index 6edfcaf..0000000 --- a/src/pt_snap_cli/mcp/AGENTS.md +++ /dev/null @@ -1,46 +0,0 @@ - - - -# mcp - -## Purpose -`mcp` exposes `pt-snap-cli` functionality as a FastMCP server so agents and MCP clients can inspect or set focus, list templates, fetch template metadata, execute queries, inspect database import metadata, and use a memory-leak analysis prompt. Skill install/list/upgrade/uninstall stay on the CLI. - -## Key Files -| File | Description | -|------|-------------| -| `__init__.py` | MCP package marker. | -| `server.py` | FastMCP app, tools, resource, prompt, and `pt-snap-mcp` entrypoint. | - -## Subdirectories -| Directory | Purpose | -|-----------|---------| -| None | MCP implementation is contained in `server.py`. | - -## For AI Agents - -### Working In This Directory -- Keep MCP tool behavior aligned with `SnapshotAnalyzer` rather than duplicating CLI-specific logic. -- Use JSON-serializable return values for tools and resources. -- Update docs in `docs/*/mcp.md` and tests when adding or changing MCP tools. -- Do not add skill-management tools; `pt-snap skill` is CLI-only. - -### Testing Requirements -- Run `pytest tests/test_mcp_server.py` for wrapper behavior and FastMCP tool/resource/prompt registration. -- Run API tests if MCP changes require `SnapshotAnalyzer` changes. -- Run `pytest tests/test_contract_cli_mcp.py` when normalized shared behavior or errors change. - -### Common Patterns -- A module-level `SnapshotAnalyzer` backs all MCP tools. -- `focus://current` mirrors the current focus tool response. -- `set_focus` delegates immediate database/device validation to `SnapshotAnalyzer`; do not accept values that the CLI focus service rejects. - -## Dependencies - -### Internal -- `pt_snap_cli.api.SnapshotAnalyzer` provides the server-facing API. - -### External -- `mcp.server.fastmcp.FastMCP` provides tool/resource/prompt registration and server execution. - - diff --git a/src/pt_snap_cli/mcp/__init__.py b/src/pt_snap_cli/mcp/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/pt_snap_cli/mcp/server.py b/src/pt_snap_cli/mcp/server.py deleted file mode 100644 index 380b935..0000000 --- a/src/pt_snap_cli/mcp/server.py +++ /dev/null @@ -1,100 +0,0 @@ -"""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]: - state = _analyzer.get_focus() - return { - "db_path": state.db_path, - "device_id": state.device_id, - "source": state.source, - "available_devices": state.available_devices, - "callstack_layout": state.callstack_layout, - "callstack_layout_error": state.callstack_layout_error, - } - - -@mcp.tool() -def set_focus(db_path: str | None = None, device_id: int | None = None) -> dict[str, Any]: - state = _analyzer.set_focus(db_path, device_id) - return { - "db_path": state.db_path, - "device_id": state.device_id, - "available_devices": state.available_devices, - "callstack_layout": state.callstack_layout, - "callstack_layout_error": state.callstack_layout_error, - } - - -@mcp.tool() -def list_templates(category: str | None = None) -> list[dict[str, Any]]: - return _analyzer.list_templates(category) - - -@mcp.tool() -def get_template_info(template_name: str) -> dict[str, Any]: - 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]: - return _analyzer.execute_query(template, params, device_id, max_rows) - - -@mcp.tool() -def get_database_metadata(db_path: str | None = None) -> dict[str, Any]: - return _analyzer.get_database_metadata(db_path) - - -@mcp.resource("focus://current") -def focus_resource() -> dict[str, Any]: - state = _analyzer.get_focus() - return { - "db_path": state.db_path, - "device_id": state.device_id, - "source": state.source, - "available_devices": state.available_devices, - "callstack_layout": state.callstack_layout, - "callstack_layout_error": state.callstack_layout_error, - } - - -@mcp.prompt() -def analyze_memory_leaks( - db_path: str, - device_id: int = 0, -) -> str: - 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: - mcp.run() - - -if __name__ == "__main__": - main() diff --git a/src/pt_snap_cli/query/executor.py b/src/pt_snap_cli/query/executor.py index 513fa49..22e48f7 100644 --- a/src/pt_snap_cli/query/executor.py +++ b/src/pt_snap_cli/query/executor.py @@ -56,7 +56,7 @@ def __init__(self, context: Context): autoescape=False, ) # Cache of compiled Jinja templates keyed by template name so that - # long-lived executors (e.g. the MCP server) avoid re-parsing + # long-lived executors (e.g. a long-lived SnapshotAnalyzer) avoid re-parsing # identical template bodies on every query. self._compiled_cache: dict[tuple[str, str], Template] = {} diff --git a/src/pt_snap_cli/query/templates/AGENTS.md b/src/pt_snap_cli/query/templates/AGENTS.md index a9be153..06ed493 100644 --- a/src/pt_snap_cli/query/templates/AGENTS.md +++ b/src/pt_snap_cli/query/templates/AGENTS.md @@ -4,7 +4,7 @@ # templates ## Purpose -`templates` contains the packaged YAML query templates used by the registry and CLI/API/MCP query execution. Templates are grouped by category and define metadata, parameters, SQL, and output schemas. +`templates` contains the packaged YAML query templates used by the registry and CLI/API query execution. Templates are grouped by category and define metadata, parameters, SQL, and output schemas. ## Key Files | File | Description | diff --git a/tests/AGENTS.md b/tests/AGENTS.md index a842087..bc79f73 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -4,7 +4,7 @@ # tests ## Purpose -`tests` contains the pytest suite for CLI/API/MCP contracts, configuration, services, query behavior, packaging/governance, and the first-party snapshot runtime. Most tests use temporary data; snapshot and import suites may use only checksum-verified executable fixtures under `tests/fixtures/snapshots/`. +`tests` contains the pytest suite for CLI/API contracts, configuration, services, query behavior, packaging/governance, and the first-party snapshot runtime. Most tests use temporary data; snapshot and import suites may use only checksum-verified executable fixtures under `tests/fixtures/snapshots/`. ## Key Files | File | Description | @@ -16,11 +16,10 @@ | `test_bundled_skills.py` | Packaged `bundled_skills/` copies must match repository `skills/*/SKILL.md`. | | `test_completion.py` | Shell completion helper tests. | | `test_config.py` | Configuration and focus precedence tests. | -| `test_contract_cli_mcp.py` | Normalized behavior contract between CLI and MCP adapters. | +| `test_contract_cli_api.py` | Normalized behavior contract between CLI and `SnapshotAnalyzer`. | | `test_context.py` | SQLite context, schema validation, and device discovery tests. | | `test_fixture_provenance.py` | Non-deserializing coverage, SHA-256, size, and Git LFS pointer validation for executable fixtures. | | `test_governance.py` | Snapshot provenance and repository governance contracts. | -| `test_mcp_server.py` | MCP server tool/resource/prompt behavior tests. | | `test_models.py` | Package-level model behavior tests. | | `test_package.py` | Package metadata/import/version tests. | | `test_release_workflow.py` | Release workflow and package publication contract tests. | diff --git a/tests/core/AGENTS.md b/tests/core/AGENTS.md index 7267180..6f022b2 100644 --- a/tests/core/AGENTS.md +++ b/tests/core/AGENTS.md @@ -4,7 +4,7 @@ # core tests ## Purpose -`tests/core` verifies focus, import, split, metadata, query, report, and skill services between CLI/API/MCP callers and lower-level config, context, query, and snapshot modules. +`tests/core` verifies focus, import, split, metadata, query, report, and skill services between CLI/API callers and lower-level config, context, query, and snapshot modules. ## Key Files | File | Description | diff --git a/tests/query/test_executor.py b/tests/query/test_executor.py index 50d220c..02e3e8b 100644 --- a/tests/query/test_executor.py +++ b/tests/query/test_executor.py @@ -264,7 +264,7 @@ def test_max_rows_tightens_non_limit_template_cap(self) -> None: assert sql.endswith("LIMIT 5"), sql def test_jinja_template_compiled_once_per_template(self) -> None: - """Long-lived executors (MCP server) must avoid re-parsing the + """Long-lived executors (a long-lived SnapshotAnalyzer) must avoid re-parsing the same template body on every render call.""" template = QueryTemplate( name="cached", diff --git a/tests/query/test_memory_peak_cte.py b/tests/query/test_memory_peak_cte.py index ba1edef..78a8b53 100644 --- a/tests/query/test_memory_peak_cte.py +++ b/tests/query/test_memory_peak_cte.py @@ -198,8 +198,8 @@ def test_memory_peak_null_start_and_end_runs_via_query_service( memory_peak_db: Path, ) -> None: """End-to-end smoke test: the rewritten template is reachable through - the QueryService -> QueryExecutor pipeline used by the CLI, MCP server - and SnapshotAnalyzer.""" + the QueryService -> QueryExecutor pipeline used by the CLI and + SnapshotAnalyzer.""" from pt_snap_cli.config import Config from pt_snap_cli.core.query_service import QueryService diff --git a/tests/skills/README.md b/tests/skills/README.md index b5c9cb6..bbf9c31 100644 --- a/tests/skills/README.md +++ b/tests/skills/README.md @@ -46,7 +46,7 @@ an isolated `HOME`, no network, a read-only project, read-only fixture mounts, and cleared focus environment variables. The gateway operation names are transport-independent. An adapter may implement -them with a CLI wrapper, MCP server, or another local agent tool, but raw command +them with a CLI wrapper or another local agent tool, but raw command spelling is not part of the grading contract. ## Run Record diff --git a/tests/test_contract_cli_mcp.py b/tests/test_contract_cli_api.py similarity index 74% rename from tests/test_contract_cli_mcp.py rename to tests/test_contract_cli_api.py index bb524b4..3a9b8e0 100644 --- a/tests/test_contract_cli_mcp.py +++ b/tests/test_contract_cli_api.py @@ -1,23 +1,25 @@ -"""CLI/MCP semantic contract tests. +"""CLI/SnapshotAnalyzer semantic contract tests. -These tests intentionally compare normalized semantics rather than raw CLI text and MCP -JSON formatting. They guard the shared API/core contract from adapter drift. +These tests compare normalized CLI semantics with SnapshotAnalyzer rather than +raw CLI text. They guard the shared API/core contract from adapter drift. + +API-specific shapes are asserted as-is: ``get_template_info()`` returns ``None`` +for a missing template, and ``execute_query()`` defaults to ``max_rows=None``. """ from __future__ import annotations import ast +import inspect import json import sqlite3 -from collections.abc import Iterator from pathlib import Path -from types import ModuleType from unittest.mock import patch import pytest from typer.testing import CliRunner -from pt_snap_cli.api import SnapshotAnalyzer +from pt_snap_cli.api import FocusState, SnapshotAnalyzer from pt_snap_cli.cli import app from pt_snap_cli.core import InvalidDeviceError, TemplateRenderError from pt_snap_cli.query.config import QueryParameter, QueryTemplate @@ -27,7 +29,7 @@ def create_contract_db(db_path: Path) -> Path: - """Create a tiny snapshot database shared by CLI and MCP contract paths.""" + """Create a tiny snapshot database shared by CLI and API contract paths.""" conn = sqlite3.connect(str(db_path)) conn.execute(""" CREATE TABLE dictionary ( @@ -86,20 +88,22 @@ def contract_db(tmp_path: Path) -> Path: @pytest.fixture -def mcp_server() -> Iterator[ModuleType]: - import pt_snap_cli.mcp.server as server +def analyzer() -> SnapshotAnalyzer: + return SnapshotAnalyzer() - original_analyzer = server._analyzer - server._analyzer = SnapshotAnalyzer() - try: - yield server - finally: - server._analyzer = original_analyzer + +def _focused_analyzer(db_path: Path, device_id: int | None = None) -> SnapshotAnalyzer: + return SnapshotAnalyzer(db_path=db_path, device_id=device_id) -def _set_mcp_focus(server: ModuleType, db_path: Path, device_id: int | None = None) -> ModuleType: - server._analyzer = SnapshotAnalyzer(db_path=db_path, device_id=device_id) - return server +def _focus_payload(state: FocusState) -> dict[str, object]: + return { + "db_path": state.db_path, + "device_id": state.device_id, + "available_devices": state.available_devices, + "callstack_layout": state.callstack_layout, + "callstack_layout_error": state.callstack_layout_error, + } def _coerce_cli_default(default_text: str) -> object: @@ -220,62 +224,50 @@ def _normalize_cli_query_result(output: str, device_id: int) -> dict[str, object return {"total": total, "returned": returned, "device_id": device_id, "rows": rows} -def _normalize_cli_missing_template(output: str) -> dict[str, str]: - return {"error": output.strip().removeprefix("Error: ")} - - def _normalize_cli_missing_focus(output: str) -> dict[str, str]: return {"kind": "focus_not_configured"} -def test_focus_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType +def test_execute_query_default_max_rows_is_unlimited() -> None: + """API default remains max_rows=None. Do not restore the removed MCP cap of 100.""" + default = inspect.signature(SnapshotAnalyzer.execute_query).parameters["max_rows"].default + assert default is None + + +def test_focus_contract_matches_cli_and_api_semantics( + contract_db: Path, analyzer: SnapshotAnalyzer ) -> None: cli_result = runner.invoke(app, ["focus", str(contract_db), "--device", "1"]) assert cli_result.exit_code == 0 cli_focus = _normalize_cli_focus(cli_result.stdout) - mcp_focus = mcp_server.set_focus(str(contract_db), device_id=1) - - assert cli_focus == { - "db_path": mcp_focus["db_path"], - "device_id": mcp_focus["device_id"], - "available_devices": mcp_focus["available_devices"], - "callstack_layout": mcp_focus["callstack_layout"], - "callstack_layout_error": mcp_focus["callstack_layout_error"], - } + api_focus = _focus_payload(analyzer.set_focus(str(contract_db), device_id=1)) + + assert cli_focus == api_focus assert cli_focus["callstack_layout"] == "v1" assert cli_focus["callstack_layout_error"] is None -def test_invalid_focus_device_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType +def test_invalid_focus_device_contract_matches_cli_and_api_semantics( + contract_db: Path, analyzer: SnapshotAnalyzer ) -> None: cli_result = runner.invoke(app, ["focus", str(contract_db), "--device", "99"]) assert cli_result.exit_code == 1 with pytest.raises(InvalidDeviceError) as exc_info: - mcp_server.set_focus(str(contract_db), device_id=99) + analyzer.set_focus(str(contract_db), device_id=99) assert str(exc_info.value) in cli_result.stdout -def test_template_list_contract_matches_cli_and_mcp_semantics(mcp_server: ModuleType) -> None: +def test_template_list_contract_matches_cli_and_api_semantics(analyzer: SnapshotAnalyzer) -> None: cli_result = runner.invoke(app, ["query", "--category", "basic"]) assert cli_result.exit_code == 0 - cli_templates = _normalize_cli_template_list(cli_result.stdout) - mcp_templates = [ - {"name": item["name"], "description": item["description"], "category": item["category"]} - for item in mcp_server.list_templates("basic") - ] - - assert cli_templates == mcp_templates + assert _normalize_cli_template_list(cli_result.stdout) == analyzer.list_templates("basic") -def test_template_info_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_template_info_contract_matches_cli_and_api_semantics(contract_db: Path) -> None: cli_result = runner.invoke( app, ["query", str(contract_db), "--template-info", "allocation"], @@ -284,11 +276,10 @@ def test_template_info_contract_matches_cli_and_mcp_semantics( assert "Category: basic" in cli_result.stdout assert "Devices: all" in cli_result.stdout - server = _set_mcp_focus(mcp_server, contract_db) cli_info = _normalize_cli_template_info(cli_result.stdout) - mcp_info = server.get_template_info("allocation") + api_info = _focused_analyzer(contract_db).get_template_info("allocation") - assert cli_info == mcp_info + assert cli_info == api_info assert cli_info["parameters"]["order_by"]["choices"] == [ "id", "allocated", @@ -298,9 +289,7 @@ def test_template_info_contract_matches_cli_and_mcp_semantics( assert cli_info["parameters"]["order_dir"]["choices"] == ["ASC", "DESC"] -def test_leak_detection_template_does_not_advertise_device_id( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_leak_detection_template_does_not_advertise_device_id(contract_db: Path) -> None: """Regression for issue #90: ``device_id`` is resolved from focus / --device, not from template parameters, so the template metadata must not expose it. """ @@ -310,11 +299,10 @@ def test_leak_detection_template_does_not_advertise_device_id( ) assert cli_result.exit_code == 0 - server = _set_mcp_focus(mcp_server, contract_db) cli_info = _normalize_cli_template_info(cli_result.stdout) - mcp_info = server.get_template_info("leak_detection") + api_info = _focused_analyzer(contract_db).get_template_info("leak_detection") - for info in (cli_info, mcp_info): + for info in (cli_info, api_info): assert info is not None assert "parameters" in info assert "device_id" not in info["parameters"], ( @@ -324,9 +312,7 @@ def test_leak_detection_template_does_not_advertise_device_id( assert "min_size" in info["parameters"] -def test_query_execution_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_query_execution_contract_matches_cli_and_api_semantics(contract_db: Path) -> None: params = {"min_size": 1024} device_id = 1 cli_result = runner.invoke( @@ -346,18 +332,15 @@ def test_query_execution_contract_matches_cli_and_mcp_semantics( ) assert cli_result.exit_code == 0 - server = _set_mcp_focus(mcp_server, contract_db) cli_query = _normalize_cli_query_result(cli_result.stdout, device_id=device_id) - mcp_query = server.execute_query( + api_query = _focused_analyzer(contract_db).execute_query( "leak_detection", params=params, device_id=device_id, max_rows=0 ) - assert cli_query == mcp_query + assert cli_query == api_query -def test_event_query_contract_reads_v1_inline_callstack( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_event_query_contract_reads_v1_inline_callstack(contract_db: Path) -> None: conn = sqlite3.connect(str(contract_db)) conn.execute( """ @@ -387,17 +370,16 @@ def test_event_query_contract_reads_v1_inline_callstack( ) assert cli_result.exit_code == 0 - server = _set_mcp_focus(mcp_server, contract_db) cli_query = _normalize_cli_query_result(cli_result.stdout, device_id=1) - mcp_query = server.execute_query("event", params={"id": 1}, device_id=1, max_rows=0) + api_query = _focused_analyzer(contract_db).execute_query( + "event", params={"id": 1}, device_id=1, max_rows=0 + ) - assert cli_query == mcp_query - assert mcp_query["rows"][0]["callstack"] == "train.py:10" + assert cli_query == api_query + assert api_query["rows"][0]["callstack"] == "train.py:10" -def test_query_parameter_error_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_query_parameter_error_contract_matches_cli_and_api_semantics(contract_db: Path) -> None: register_query( QueryTemplate( name="required_query", @@ -412,30 +394,28 @@ def test_query_parameter_error_contract_matches_cli_and_mcp_semantics( ["query", str(contract_db), "--template-use", "required_query"], ) assert cli_result.exit_code == 1 - server = _set_mcp_focus(mcp_server, contract_db) + analyzer = _focused_analyzer(contract_db) with pytest.raises(TemplateRenderError) as exc_info: - server.execute_query("required_query") + analyzer.execute_query("required_query") assert str(exc_info.value) in cli_result.stdout -def test_missing_focus_error_contract_matches_cli_and_mcp_semantics( - mcp_server: ModuleType, +def test_missing_focus_error_contract_matches_cli_and_api_semantics( + analyzer: SnapshotAnalyzer, ) -> None: cli_result = runner.invoke(app, ["query", "--template-use", "leak_detection"]) assert cli_result.exit_code == 1 with pytest.raises(RuntimeError) as exc_info: - mcp_server.execute_query("leak_detection") + analyzer.execute_query("leak_detection") assert _normalize_cli_missing_focus(cli_result.stdout) == {"kind": "focus_not_configured"} assert str(exc_info.value) == "No database configured. Call set_focus() first." -def test_unknown_parameter_error_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_unknown_parameter_error_contract_matches_cli_and_api_semantics(contract_db: Path) -> None: """Regression for issue #120: both surfaces reject undeclared parameters identically.""" cli_result = runner.invoke( app, @@ -450,17 +430,15 @@ def test_unknown_parameter_error_contract_matches_cli_and_mcp_semantics( ) assert cli_result.exit_code == 1 - server = _set_mcp_focus(mcp_server, contract_db) + analyzer = _focused_analyzer(contract_db) with pytest.raises(TemplateRenderError) as exc_info: - server.execute_query("leak_detection", params={"min_sze": 1024}) + analyzer.execute_query("leak_detection", params={"min_sze": 1024}) assert "Unknown parameter(s) for template 'leak_detection': min_sze" in str(exc_info.value) assert str(exc_info.value) in cli_result.stdout -def test_choices_error_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_choices_error_contract_matches_cli_and_api_semantics(contract_db: Path) -> None: """Regression for issue #120: SQL fragment parameters are bounded on both surfaces.""" params = {"order_by": "(SELECT 1)", "order_dir": "ASC"} cli_result = runner.invoke( @@ -469,9 +447,9 @@ def test_choices_error_contract_matches_cli_and_mcp_semantics( ) assert cli_result.exit_code == 1 - server = _set_mcp_focus(mcp_server, contract_db) + analyzer = _focused_analyzer(contract_db) with pytest.raises(TemplateRenderError) as exc_info: - server.execute_query("allocation", params=params) + analyzer.execute_query("allocation", params=params) assert "Parameter 'order_by' must be one of: id, allocated, active, reserved" in str( exc_info.value @@ -479,24 +457,18 @@ def test_choices_error_contract_matches_cli_and_mcp_semantics( assert str(exc_info.value) in cli_result.stdout -def test_missing_template_error_contract_matches_cli_and_mcp_semantics( - mcp_server: ModuleType, +def test_missing_template_error_contract_matches_cli_and_api_semantics( + analyzer: SnapshotAnalyzer, ) -> None: template_name = "does_not_exist" cli_result = runner.invoke(app, ["query", "--template-info", template_name]) assert cli_result.exit_code == 1 - - assert _normalize_cli_missing_template(cli_result.stdout) == mcp_server.get_template_info( - template_name - ) + assert f"Template '{template_name}' not found" in cli_result.stdout + assert analyzer.get_template_info(template_name) is None -def test_metadata_contract_matches_cli_and_mcp_semantics( - contract_db: Path, mcp_server: ModuleType -) -> None: +def test_metadata_contract_matches_cli_and_api_semantics(contract_db: Path) -> None: cli_result = runner.invoke(app, ["metadata", str(contract_db), "--json"]) assert cli_result.exit_code == 0 - server = _set_mcp_focus(mcp_server, contract_db) - - assert json.loads(cli_result.stdout) == server.get_database_metadata() + assert json.loads(cli_result.stdout) == _focused_analyzer(contract_db).get_database_metadata() diff --git a/tests/test_governance.py b/tests/test_governance.py index ec553d6..cd7b376 100644 --- a/tests/test_governance.py +++ b/tests/test_governance.py @@ -222,8 +222,6 @@ def test_old_source_identity_is_confined_to_fixed_evidence_allowlist() -> None: Path("README_zh.md"), Path("docs/en/quickstart.md"), Path("docs/zh/quickstart.md"), - Path("docs/en/mcp.md"), - Path("docs/zh/mcp.md"), ) PYPI_INSTALL = "pip install pt-snap-cli" EDITABLE_DEV_INSTALL = 'pip install -e ".[dev]"' diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py deleted file mode 100644 index c15077a..0000000 --- a/tests/test_mcp_server.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Tests for the MCP server module.""" - -import asyncio -import json -import sqlite3 -import tempfile -from pathlib import Path -from unittest.mock import patch - -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(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - """Reset the module analyzer and isolate focus from the host machine.""" - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.api import SnapshotAnalyzer - - original_analyzer = server_mod._analyzer - monkeypatch.chdir(tmp_path) - monkeypatch.delenv("PT_SNAP_DB_PATH", raising=False) - with patch.object(Path, "home", return_value=tmp_path): - server_mod._analyzer = SnapshotAnalyzer() - try: - yield - finally: - server_mod._analyzer = original_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_registers_tools_resource_and_prompt(self) -> None: - from pt_snap_cli.mcp.server import mcp - - tools = {tool.name for tool in asyncio.run(mcp.list_tools())} - resources = {str(resource.uri) for resource in asyncio.run(mcp.list_resources())} - prompts = {prompt.name for prompt in asyncio.run(mcp.list_prompts())} - - assert tools == { - "get_focus", - "set_focus", - "list_templates", - "get_template_info", - "execute_query", - "get_database_metadata", - } - assert resources == {"focus://current"} - assert prompts == {"analyze_memory_leaks"} - - def test_mcp_resource_and_prompt_behavior(self, valid_db: Path) -> None: - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.api import SnapshotAnalyzer - - async def read_capabilities(): - resource = await server_mod.mcp.read_resource("focus://current") - prompt = await server_mod.mcp.get_prompt( - "analyze_memory_leaks", - {"db_path": str(valid_db), "device_id": "0"}, - ) - return resource, prompt - - server_mod._analyzer = SnapshotAnalyzer(db_path=valid_db, device_id=0) - resource, prompt = asyncio.run(read_capabilities()) - - assert json.loads(resource[0].content)["db_path"] == str(valid_db) - assert "run the leak_detection template" in prompt.messages[0].content.text - - -class TestMCPToolFunctions: - """Test MCP wrapper functions against the shared analyzer.""" - - def test_get_focus_returns_dict(self, valid_db: Path) -> None: - """Test get_focus returns proper dict structure.""" - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.api import SnapshotAnalyzer - - server_mod._analyzer = SnapshotAnalyzer(db_path=valid_db) - result = server_mod.get_focus() - 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.""" - import pt_snap_cli.mcp.server as server_mod - - result = server_mod.set_focus(db_path=str(valid_db), device_id=0) - assert isinstance(result, dict) - assert result["db_path"] == str(valid_db) - assert result["device_id"] == 0 - assert result["callstack_layout"] == "v1" - - def test_set_focus_rejects_invalid_device(self, valid_db: Path) -> None: - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.core import InvalidDeviceError - - with pytest.raises(InvalidDeviceError, match="Device 99 not found"): - server_mod.set_focus(db_path=str(valid_db), device_id=99) - - def test_list_templates_returns_list(self) -> None: - """Test list_templates returns a list of dicts.""" - import pt_snap_cli.mcp.server as server_mod - - result = server_mod.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.""" - import pt_snap_cli.mcp.server as server_mod - - info = server_mod.get_template_info("leak_detection") - assert "name" in info - assert "parameters" in info - - def test_get_template_info_not_found(self) -> None: - """Test get_template_info handles missing template.""" - import pt_snap_cli.mcp.server as server_mod - - info = server_mod.get_template_info("does_not_exist") - assert info == {"error": "Template 'does_not_exist' not found"} - - def test_execute_query_returns_dict(self, valid_db: Path) -> None: - """Test execute_query returns proper dict structure.""" - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.api import SnapshotAnalyzer - - server_mod._analyzer = SnapshotAnalyzer(db_path=valid_db) - result = server_mod.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 - - def test_execute_query_default_max_rows_caps_rows_but_keeps_exact_total( - self, valid_db: Path - ) -> None: - """Documented contract (#123): MCP defaults to 100 rows, unlike the CLI. - - ``total`` must stay exact when the cap is hit so agents can detect that - more data exists; ``max_rows=0`` lifts the cap. - """ - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.api import SnapshotAnalyzer - - conn = sqlite3.connect(str(valid_db)) - conn.executemany( - "INSERT INTO block_0 (address, size, requestedSize, state, allocEventId, freeEventId)" - " VALUES (?, ?, ?, 1, ?, -1)", - [(4096 * i, 1024, 1024, i) for i in range(150)], - ) - conn.commit() - conn.close() - server_mod._analyzer = SnapshotAnalyzer(db_path=valid_db) - - capped = server_mod.execute_query("leak_detection") - assert capped["returned"] == 100 - assert capped["total"] == 150 - assert len(capped["rows"]) == 100 - - unlimited = server_mod.execute_query("leak_detection", max_rows=0) - assert unlimited["returned"] == 150 - assert unlimited["total"] == 150 - - def test_get_database_metadata(self, valid_db: Path) -> None: - import pt_snap_cli.mcp.server as server_mod - from pt_snap_cli.api import SnapshotAnalyzer - - server_mod._analyzer = SnapshotAnalyzer(db_path=valid_db) - - result = server_mod.get_database_metadata() - - assert result["status"] == "unavailable" - assert result["reason"] == "metadata_missing" - - -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) diff --git a/tests/test_package.py b/tests/test_package.py index 89dbef0..86014e2 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -1,9 +1,30 @@ -"""Tests for package initialization.""" +"""Tests for package initialization and published metadata.""" -from importlib.metadata import version +from __future__ import annotations + +import importlib +from importlib.metadata import distribution, requires, version +from pathlib import Path + +import pytest from pt_snap_cli import __version__ +ROOT = Path(__file__).resolve().parents[1] + + +def _runtime_requirement_names() -> set[str]: + names: set[str] = set() + for req in requires("pt-snap-cli") or []: + name_part, _, marker = req.partition(";") + if "extra" in marker: + continue + name = name_part.split("[", 1)[0] + for sep in (">", "<", "=", "!"): + name = name.split(sep, 1)[0] + names.add(name.strip().lower()) + return names + class TestPackage: """Test package initialization.""" @@ -15,3 +36,24 @@ def test_version(self) -> None: def test_version_format(self) -> None: """Test version string is not the fallback value.""" assert __version__ != "0.0.0-dev" + + def test_console_scripts_are_cli_only(self) -> None: + names = { + ep.name + for ep in distribution("pt-snap-cli").entry_points + if ep.group == "console_scripts" + } + assert names == {"pt-snap"} + + def test_runtime_dependencies_exclude_mcp_stack(self) -> None: + names = _runtime_requirement_names() + assert names.isdisjoint({"mcp", "starlette", "uvicorn"}) + + def test_pyproject_does_not_declare_mcp(self) -> None: + text = (ROOT / "pyproject.toml").read_text() + assert "pt-snap-mcp" not in text + assert "mcp>=" not in text + + def test_mcp_package_is_removed(self) -> None: + with pytest.raises(ModuleNotFoundError): + importlib.import_module("pt_snap_cli.mcp") diff --git a/tests/test_query_cache_perf.py b/tests/test_query_cache_perf.py index 7212b01..b91ffa8 100644 --- a/tests/test_query_cache_perf.py +++ b/tests/test_query_cache_perf.py @@ -1,7 +1,7 @@ """Performance regression test for :class:`SnapshotAnalyzer` connection reuse. -The MCP server keeps one :class:`SnapshotAnalyzer` alive across many -``execute_query`` tool calls. Without caching, every call would pay for +A long-lived :class:`SnapshotAnalyzer` keeps one instance alive across many +``execute_query`` calls. Without caching, every call would pay for schema validation and a fresh ``sqlite3.connect`` URI handshake. This test exercises the caching path and asserts that ten consecutive calls against the same database are not catastrophically slower than one call -- a diff --git a/tests/test_snapshot_analyzer_cache.py b/tests/test_snapshot_analyzer_cache.py index 48f7ca3..2756362 100644 --- a/tests/test_snapshot_analyzer_cache.py +++ b/tests/test_snapshot_analyzer_cache.py @@ -1,7 +1,7 @@ """End-to-end tests for :class:`SnapshotAnalyzer` connection reuse. -These exercise the path that the MCP server takes: keep one -:class:`SnapshotAnalyzer` alive and call ``execute_query`` repeatedly +These exercise the path that a long-lived :class:`SnapshotAnalyzer` takes: +keep one analyzer alive and call ``execute_query`` repeatedly against the same database. We assert that: * the analyzer reuses a single cached :class:`Context` across calls,