Skip to main content
Glama
smart-query
by Gahyu96
README.md
# smart-query

[中文](#中文) · [English](#english)

## 中文

给 Claude Code 用的本地 stdio MCP。一次调用可批量提交 1–8 条 `read`、`search`、`list`、`tail`、`stat` 等查询。本机生成并执行查询脚本,Claude Code 只收发结构化参数和结果。无需 Magpie 或 npm 依赖。

### 安装

需要 **Node.js 22+**、Bash 和相应的本地命令。在要查询的项目内执行,将示例路径改为当前机器的真实绝对路径(`install.mjs` 会自动探测本地 Bash、写入本机 `policy.json`、执行一次真实 stdio 自检,并通过 `claude mcp add-json` 注册带 `"alwaysLoad": true` 的 user 级配置,避免首轮被延迟加载):

```sh
node "/absolute/path/to/smart-query/install.mjs" --root .
# 如需同时开放多个目录或调整截断上限(范围 512–262144):
node "/absolute/path/to/smart-query/install.mjs" --root /path/to/repo1 --root /path/to/repo2 --max-bytes 16000 --max-chars 12000
claude mcp get smart-query
```

- **团队 `CLAUDE.md` 推荐规则(可直接粘贴 5 行)**:
  ```markdown
  - 本机只读查证(搜代码、读行段、tail 日志、列目录、stat、只读 git)优先合批调用 `mcp__smart-query__query`(按需 1–8 条,不硬塞满)。
  - 不要用零碎 `Bash`(`cat`/`sed`/`grep`/`rg`/`find`/`ls`)或连续翻页 `Read` 替代 `mcp__smart-query__query`。
  - 仅在 `Edit`/`Write` 前宿主强制读取、PDF/图片、策略外路径、远端 SSH、构建/测试/写入时走原生 `Read`/`Bash`。
  - 未返回的大段内容会给出「未读目录」,按其 `address` 和 `fingerprint` 续读即可;`mcp__smart-query__query` 拒绝的路径或命令直接报告,禁止换 `Bash` 绕过。
  - 需要更大或更小的返回窗口时,在单次调用里传可选 `max_bytes` / `max_chars`(受本机服务端上限封顶)。
  ```
- **Linux / WSL**:用该环境自己的 Node 和 Bash。默认 Bash 是 `/bin/bash`;目录搜索可使用 `rg` 或 `grep`。
- **macOS**:用原生 Node 与系统 `/bin/bash`(3.2+)或 Homebrew Bash;ZIP/JAR 优先复用系统 `bsdtar` 保留 UTF-8 文件名。如需 Homebrew 工具,可在 `policy.json` 中配置 `path`。
- **Windows**:用原生 `node.exe` 和 Git for Windows。可显式设置 `bash`,指向 `C:/Program Files/Git/bin/bash.exe` 或 `C:/Program Files/Git/usr/bin/bash.exe`;不要选 WSL Bash。用 `C:/...` 或 `/c/...` 写查询路径,安装命令中的含空格路径要加引号。
- 建议保留 Claude Code 的权限询问。使用 `--scope project` 会生成可共享的项目配置,不要提交含本机绝对路径的配置。

### 查询与预算

工具是 `mcp__smart-query__query`。例如:

```json
{"queries":[{"op":"search","path":"src","pattern":"TODO","glob":"*.js"},{"op":"read","path":"README.md","start":1,"end":30}]}
```

有结构的文件会尽量按完整片段返回结果,不把所有匹配一次塞进会话。默认总输出上限为 **9,888 UTF-8 字节** 和 **8,000 UTF-16 代码单元**(含 MCP 工作目录提示),可通过以下方式自定义(合法范围 `512`–`262144`):

- **服务端上限(ceiling)优先级**:启动入参(`--max-bytes` / `--max-chars`)> 环境变量(`SMART_QUERY_MAX_BYTES` / `SMART_QUERY_MAX_CHARS`)> `policy.json`(`maxBytes` / `maxChars`)> 默认值 `9888` / `8000`。只设其中一项时,另一项按安全比例自动推导。
- **单次调用上限**:工具参数支持可选 `max_bytes` / `max_chars`,可为本次查询收窄窗口,但严格封顶于服务端上限。

未返回的片段会在预算允许时列入「未读目录」。需要继续时,把条目的 `address`、可选 `fingerprint` 和响应提示的 `format_hint` 传给下一次 `read`;`address` 不与 `start/end` 同用。

### 策略与安全边界

`SMART_QUERY_CONFIG` / `AGY_QUERY_CONFIG` 指向本地 JSON。

- `cwd`:默认查询目录,也是允许根。省略时取 MCP 启动目录;设置后取代启动目录。
- `allowRoots`:附加允许目录的绝对路径数组。默认不开放整个家目录。
- `denyPaths`:附加拒绝路径的绝对路径数组,支持 `~/`。默认拒绝家目录下的 `.ssh`、`.aws`、`.gnupg`。
- `denyNames`:附加拒绝的名称模式数组,不区分大小写,`*` 是通配符。默认拒绝 `.env*`、`*.pem`、`id_*`。
- `bash`:可信 Bash 可执行文件的绝对路径。`path`:提供给子进程的可信可执行目录数组,不是文件读取范围。
- `allowHostTools`:默认 `false`。打开后才允许部分宿主观测命令,例如 `ps` 和受限的 `docker`、`journalctl`。`run` 始终使用命令和参数白名单。

**预检不是沙箱。** 服务器用本地用户权限执行。路径通过预检后、Bash 打开文件前,其他本地进程仍可能替换文件(TOCTOU)。拒绝名单不能识别普通文件、提交消息或已允许内容里复制的秘密。只用于可信工作区;需要强隔离时使用独立账号或操作系统沙箱。批次共用 20 秒执行截止时间。POSIX 超时尝试终止 Bash 进程组,Windows 只终止直接子进程,不保证清理后代。

### 已知限制与 Magpie 集成

- 可用格式取决于宿主命令,例如 `jq`、`sqlite3`、DuckDB、`pdftotext` 和归档工具。路径预检遇到不安全条目或递归超限时会拒绝该条,不影响同批有效条目。工作目录不会跟踪 Claude Code 内部实时 `cd`。linked worktree 中普通文件查询可用,`run git` 有意要求 `cwd` 下存在实体 `.git` 目录因而会拒绝。接入 OpenAI Responses API 适配器时,须在外层 function tool 显式设置 `strict: false`(省略时 Responses 会尝试自动严格化,可能导致模型把所有可选字段填满占位值而被按操作校验拒绝)。输出提示目前含中文。
- **工作目录与 Magpie `agy-cli` bridge 配合**:任何调用方(Claude Code 中任意模型直连,或 Magpie bridge)都可传入可选绝对 `cwd`;省略时使用默认工作目录并附提示,显式传入但不存在、不合法或超出策略范围时直接拒绝该批次(`isError: true`),不回退到其他目录。配合 Magpie `agy-cli` bridge 时,bridge 需将 `agy_query` 转发到当轮声明的 `mcp__smart-query__query`;bridge 选路与 Bash 兜底不在本仓库,不经 bridge 也能直接使用本工具。
- 验证:在仓库根目录运行 `node --test`。缺少相应格式 CLI 时,有关集成用例会跳过。当前候选版只在 Linux/WSL 运行过,macOS 与原生 Windows 尚未实测。
- 来源见 [NOTICE](NOTICE.md)。独立项目许可证尚未选定;当前本地候选版不供公开发布。

## English

A local stdio MCP server for Claude Code. Batch 1–8 structured lookups such as `read`, `search`, `list`, `tail`, and `stat`. Scripts are generated and run locally; Claude Code receives structured inputs and results, not generated shell text. No Magpie installation or npm dependencies are required.

### Install

You need **Node.js 22+**, Bash, and the local commands required by your queries. From the project you want to query, replace the example paths with absolute paths on your machine:

```sh
node "/absolute/path/to/smart-query/install.mjs" --root .
# Or allow multiple roots and raise/lower the truncation ceiling (valid range 512–262144):
node "/absolute/path/to/smart-query/install.mjs" --root /path/to/repo1 --root /path/to/repo2 --max-bytes 16000 --max-chars 12000
claude mcp get smart-query
```

`install.mjs` detects Bash, writes `policy.json`, runs a real stdio smoke check, and registers the server via `claude mcp add-json` with `"alwaysLoad": true` so Claude Code loads it on turn 1 without deferred tool lookup.

- **Linux / WSL:** Use Node and Bash from that environment. The default is `/bin/bash`; directory search uses `rg` or `grep`.
- **macOS:** Use native Node with `/bin/bash` (3.2+) or Homebrew Bash; ZIP/JAR listing and reads use system `bsdtar` to preserve UTF-8 member names. Configure `path` in `policy.json` if Homebrew utilities are needed.
- **Windows:** Use native `node.exe` and Git for Windows. Override `bash` if needed, for example to `C:/Program Files/Git/bin/bash.exe` or `C:/Program Files/Git/usr/bin/bash.exe`, not WSL Bash. Use `C:/...` or `/c/...` in queries and quote installation paths containing spaces.
- Leave Claude Code permission prompts enabled. `--scope project` creates shared project configuration; do not commit configuration containing machine-specific absolute paths.

### Queries and budgets

Call `mcp__smart-query__query` with a `queries` array. The example in the Chinese section works unchanged. The generator prefers returning complete blocks rather than stuffing every match into the conversation. By default, total output is capped at **9,888 UTF-8 bytes** and **8,000 UTF-16 code units** (including any MCP working-directory notice), configurable within `[512, 262144]`:

- **Server ceiling precedence:** CLI flags (`--max-bytes` / `--max-chars`) > env vars (`SMART_QUERY_MAX_BYTES` / `SMART_QUERY_MAX_CHARS`) > `policy.json` (`maxBytes` / `maxChars`) > defaults `9888` / `8000`. Setting one side derives the other safely.
- **Per-call cap:** pass optional `max_bytes` / `max_chars` in tool arguments to shrink the response window for that call (strictly clamped to the server ceiling).

When space permits, omitted blocks appear in an unread index. Pass a block’s `address`, optional `fingerprint`, and suggested `format_hint` to a follow-up `read`. Do not combine `address` with `start/end`.

### Policy and security boundaries

`SMART_QUERY_CONFIG` / `AGY_QUERY_CONFIG` points to a local JSON file. 

- `cwd`: The default query directory and an allowed root. When specified, it replaces the MCP launch directory.
- `allowRoots`: Additional allowed absolute directories. HOME is not allowed as a whole by default.
- `denyPaths`: Additional absolute paths to block, with `~/` support. Defaults include `.ssh`, `.aws`, and `.gnupg` under HOME.
- `denyNames`: Additional case-insensitive basename patterns. `*` is a wildcard. Defaults include `.env*`, `*.pem`, and `id_*`.
- `bash`: Absolute path to a trusted Bash executable. `path`: Trusted executable directories for the subprocess, not directory read permissions.
- `allowHostTools`: Defaults to `false`. Enables a restricted set of host-observation commands, such as `ps` and selected Docker or journal commands. `run` always restricts commands and arguments.

**Preflight checks are not a sandbox.** The server runs with the local user’s permissions. Another local process can replace a file between preflight and use (TOCTOU). Deny rules do not detect secrets copied into ordinary files or commit messages. Use a trusted workspace and use an OS sandbox or separate account if you need stronger isolation. Each batch has one 20-second execution deadline. On POSIX a timeout attempts to kill the Bash process group; on Windows it kills the direct child only, not necessarily its descendants.

### Known limitations and Magpie integration

- Format support depends on host utilities such as `jq`, `sqlite3`, DuckDB, `pdftotext`, and archive tools. Unsafe or oversized recursive targets are rejected per item. The MCP working directory does not follow Claude Code’s live `cd`. In a linked Git worktree, ordinary file lookups work while `run git` intentionally requires a real `.git` directory in `cwd` and is rejected. When adapting this MCP tool to OpenAI Responses API function tools, explicitly set `strict: false` on the outer function tool definition (omitting `strict` lets Responses attempt auto-strictification, which can force models to fill all optional fields with placeholders that fail per-op validation). Some result messages are in Chinese.
- **Working directory and Magpie `agy-cli` bridge:** any caller (any LLM directly in Claude Code, or the Magpie bridge) may pass an optional absolute `cwd`. Omitting `cwd` uses the configured MCP default with a notice; passing an explicit invalid, missing, or disallowed `cwd` fails closed (`isError: true`) instead of querying another directory. With the Magpie `agy-cli` bridge, the bridge must route `agy_query` to `mcp__smart-query__query` declared in the current request. Bridge routing and its Bash fallback are not in this repository; direct Claude Code use does not require the bridge.
- Run `node --test` from the repository root. Integration cases for absent format utilities are skipped. This candidate has been tested on Linux/WSL, not on macOS or native Windows.
- See [NOTICE](NOTICE.md) for provenance. A license for the standalone project has not been selected; this local candidate is not ready for public distribution.