From 2ebaa2a5e41213d755b41d319bec4fcf4bdb1c79 Mon Sep 17 00:00:00 2001 From: codeasier Date: Mon, 7 Sep 2026 01:57:47 +0800 Subject: [PATCH] docs(mcp): document execute_query max_rows default and result semantics The MCP execute_query tool defaults to max_rows=100 while the CLI shows every row unless -n is given, and the MCP guides never mentioned max_rows or explained the total/returned/device_id/rows fields. An agent following the guide could read 100 rows and treat them as the complete result. Add a "Query Results and Row Limits" section to docs/en/mcp.md and docs/zh/mcp.md covering the field meanings, the deliberate CLI/MCP default difference, that total stays exact when the cap is hit, and how to lift or page past the cap; note the default in the tools table and fix the example return shape to include device_id. Cross-reference from the querying guides' output-format sections. Pin the behavior with an MCP test that inserts 150 leak candidates and checks returned == 100, total == 150, and max_rows=0 returning everything. Fixes #123 --- docs/en/mcp.md | 30 ++++++++++++++++++++++++++++-- docs/en/querying.md | 4 ++++ docs/zh/mcp.md | 29 +++++++++++++++++++++++++++-- docs/zh/querying.md | 3 +++ tests/test_mcp_server.py | 30 ++++++++++++++++++++++++++++++ 5 files changed, 92 insertions(+), 4 deletions(-) diff --git a/docs/en/mcp.md b/docs/en/mcp.md index a63388d..692b78b 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -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 @@ -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`: diff --git a/docs/en/querying.md b/docs/en/querying.md index 830a551..c1bd9b2 100644 --- a/docs/en/querying.md +++ b/docs/en/querying.md @@ -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 diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index b62666b..91c6023 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -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 | ## 可用资源 @@ -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` 中声明: diff --git a/docs/zh/querying.md b/docs/zh/querying.md index bf45551..446c654 100644 --- a/docs/zh/querying.md +++ b/docs/zh/querying.md @@ -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`。 diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index d0dfba8..0d08c8a 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -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