Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions docs/en/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ This starts a FastMCP server that exposes tools for analyzing PyTorch memory sna
| `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 |
| `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
Expand Down Expand Up @@ -69,13 +69,39 @@ get_template_info("leak_detection")

# Run a query
execute_query("leak_detection", params={"min_size": 1024})
# Returns: {"total": 5, "returned": 5, "rows": [...]}
# 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`:
Expand Down
4 changes: 4 additions & 0 deletions docs/en/querying.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,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).

CLI, Python API, and MCP 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
Expand Down
29 changes: 27 additions & 2 deletions docs/zh/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pt-snap-mcp
| `set_focus` | 设置焦点到指定数据库和可选设备。运行查询前使用。 |
| `list_templates` | 列出可用的查询模板,可按类别筛选 |
| `get_template_info` | 获取模板详情,包括参数信息 |
| `execute_query` | 对焦点数据库执行查询模板 |
| `execute_query` | 对焦点数据库执行查询模板。最多返回 `max_rows` 行(默认 **100**;传 `0` 表示不限制)。见[查询结果与行数限制](#查询结果与行数限制)。 |
| `get_database_metadata` | 查看焦点或指定数据库的导入来源 metadata |

## 可用资源
Expand Down Expand Up @@ -69,13 +69,38 @@ get_template_info("leak_detection")

# 运行查询
execute_query("leak_detection", params={"min_size": 1024})
# 返回: {"total": 5, "returned": 5, "rows": [...]}
# 返回: {"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` 中声明:
Expand Down
3 changes: 3 additions & 0 deletions docs/zh/querying.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ Found 150 results, showing 2:
... and 148 more (use -n to show more)
```

即使输出被截断,"Found N" 的计数也是精确的。注意 MCP 的 `execute_query` 工具默认
最多返回 100 行,与 CLI 不同;见[MCP 服务器:查询结果与行数限制](mcp.md#查询结果与行数限制)。

CLI、Python API 和 MCP 的查询结果包含原始 SQLite 值。模板的 `output_schema`
只是 metadata,查询执行时不会自动应用。需要十六进制地址字符串等转换值时,
应显式调用 `ResultMapper`。
Expand Down
30 changes: 30 additions & 0 deletions tests/test_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,36 @@ def test_execute_query_returns_dict(self, valid_db: Path) -> None:
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
Expand Down
Loading