Metadata-Version: 2.5
Name: grep-mcp-tools
Version: 0.1.0
Summary: Proxy-layer MCP server: downstream sees search/invoke/status, upstream tools are indexed as plain JSONL and searched on demand
Project-URL: Homepage, https://github.com/qtalen/grep-mcp-tools
Project-URL: Repository, https://github.com/qtalen/grep-mcp-tools
Project-URL: Issues, https://github.com/qtalen/grep-mcp-tools/issues
Project-URL: Changelog, https://github.com/qtalen/grep-mcp-tools/blob/main/CHANGELOG.md
Author: Peng Qian
License-Expression: MIT
License-File: LICENSE
Keywords: agent,mcp,model-context-protocol,proxy,token-saving,tool-search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: mcp==2.3.0
Description-Content-Type: text/markdown

# grep-mcp-tools

A proxy-layer MCP server: it indexes the tools of many upstream MCP servers into a local
plain-text index and exposes only **three tools** to the downstream agent — search by
keyword, invoke by target, and check upstream health.

It solves one specific problem: **token blow-up from tool definitions that sit in the
context window all the time.** With a dozen MCP servers and a few hundred tools, the tool
definitions alone can eat 20k–60k tokens. This proxy keeps about **700 tokens** resident
(three tool definitions plus the service list, excluding optional per-service
descriptions) and pulls the rest in on demand.

```text
downstream agent                 proxy                          upstream MCP servers
+-------------+   3 tools   +------------------+   handshake   +----------------+
| Claude /    | ----------> | search_mcp_tool  | ------------> | hr (stdio)     |
| Cherry /    |             | invoke_this_tool |   pass-thru   | itops (HTTP)   |
| LangChain   | <---------- | check_mcp_status | <------------ | docs (SSE)     |
+-------------+             +------------------+               +----------------+
                                   |
                                   +- tools_index/<server>.jsonl   plain-text index, one tool per line
                                   +- tools_index/_status.json     health snapshot
                                   +- call_log.jsonl               optional call log (off by default)
```

In one sentence: **on startup it connects to every upstream, writes the tool definitions
to plain-text JSONL, the agent greps that index with keywords, and once it has a
`server__tool` target the proxy passes the call through unchanged.**

## Why

- **Resident cost.** Three tool definitions instead of every upstream definition.
- **Accuracy.** The agent sees the exact target, parameter names, types and full parameter
  descriptions (including any enum or range constraints the upstream states in them), so one
  search is enough to build a valid call.
- **Freshness.** The index is rebuilt on a timer; an upstream that died is re-connected on
  a later refresh without restarting the proxy.

Measured numbers (each with its sample size; see
[`docs/design/`](https://github.com/qtalen/grep-mcp-tools/tree/main/docs/design) for the
full methodology):

- **Resident tools:** about 700 tokens, versus 20k–60k tokens for attaching the upstream
  tools directly (experience-based estimate across real deployments).
- **A/B experiment:** 30 tasks, 25 non-negative samples counted for recall, `deepseek-flash`
  with `reasoning_effort=low`: 100% tool discovery, 100% recall, 87.8% reduction in resident
  tokens. We do **not** claim a selection gap between experiment arms, nor that task quality
  is unaffected.
- **Real client, anonymized:** one deployment, 102 upstream tools, 513 calls (2026-11-06 →
  2026-11-30): about 95% fewer resident tokens (estimated from character counts, not a
  tokenizer) and 93% of searches returned at least one tool.

## How it works

1. **Startup.** The proxy reads the config, connects to every upstream, and writes
   `tools_index/<server>.jsonl` (one JSON object per tool, written atomically).
2. **Search.** `search_mcp_tool` matches keywords against whole index lines — tool name,
   title, description, parameter names and parameter descriptions.
3. **Invoke.** The agent copies the `server__tool` target from the search result and calls
   `invoke_this_tool`; the proxy forwards the call to the owning upstream unchanged. Calls
   to the same upstream are serialized; different upstreams run concurrently.
4. **Refresh.** Every `refresh_interval` seconds the proxy re-handshakes the upstreams,
   rewrites the index and heals dead services.

| Tool | Purpose |
|---|---|
| `search_mcp_tool(keywords: string[])` | Find tools by keyword. The entry point. |
| `invoke_this_tool(target: string, params: object)` | Call `server__tool` on its upstream. |
| `check_mcp_status()` | Health snapshot of every upstream service. |

Errors are distinguishable: upstream JSON-RPC errors keep their original code and data and
get an `[upstream jsonrpc error: code=..., data=...]` suffix, while proxy-level problems
(invalid target, unreachable server, unknown tool) are prefixed `Proxy error:` and usually
say what to do next. `check_mcp_status` reports the snapshot without probing or
reconnecting; use it after an error, when a response asks for it, or when the user asks
about upstream health.

## Install

Requires **Python 3.11+**. The examples use [uv](https://docs.astral.sh/uv/).

Run without installing (resolves the package from PyPI into a cached environment):

```bash
uvx grep-mcp-tools@0.1.0 --config /path/to/config.json
```

Install the command once:

```bash
uv tool install grep-mcp-tools
```

or with pip:

```bash
pip install grep-mcp-tools
```

The first run downloads the runtime dependencies (30 packages on Windows, measured; some
are platform-specific) and takes longer than later runs.

## Quick start

### 1. Write a config file

The format is the same `mcpServers` shape Claude Code uses, plus an optional `settings`
object. A complete example with one stdio upstream and one HTTP upstream:

```json
{
  "mcpServers": {
    "hr": {
      "command": "uv",
      "args": [
        "run", "--directory", "/path/to/your/hr-server",
        "python", "server.py"
      ],
      "description": "HR service: employee records, leave balances, payroll."
    },
    "itops": {
      "type": "http",
      "url": "https://mcp.example.com/mcp",
      "headers": {
        "Authorization": "Bearer <your-token>"
      },
      "description": "IT operations: asset lookup, alert handling, change tickets."
    }
  },
  "settings": {
    "threshold": 30,
    "refresh_interval": 600
  }
}
```

> **Do not use a bare `python` as `command`.** The proxy resolves `command` through
> `PATH`; under `uv tool install` a bare `python` is the system interpreter, not the tool
> environment, so it will not find the upstream server's dependencies. Use
> `uv run --directory ...` like above, or an absolute interpreter path such as
> `/path/to/venv/bin/python` (`C:/path/to/venv/Scripts/python.exe` on Windows).

`{"mcpServers": {}}` is valid: the proxy starts and reports that no upstream services are
configured. Server names may contain only letters, digits, `_` and `-`, must not contain
`__` (the target namespace separator), and are unique case-insensitively.

### 2. Mount it in your agent

The proxy itself is a **stdio** MCP server. Let the host start it:

```json
{
  "mcpServers": {
    "tool-search": {
      "command": "grep-mcp-tools",
      "args": ["--config", "/path/to/config.json"]
    }
  }
}
```

Without a global install, point at `uvx` instead:

```json
{
  "mcpServers": {
    "tool-search": {
      "command": "uvx",
      "args": ["grep-mcp-tools@0.1.0", "--config", "/path/to/config.json"]
    }
  }
}
```

Use absolute paths: the host's working directory when it spawns the child is not
necessarily your project directory. Forward slashes (`C:/Users/you/...`) work on Windows
and avoid backslash escaping in JSON.

### 3. First search

The agent calls `search_mcp_tool(["employee", "leave"])` and gets candidate targets with
their parameters:

```text
1 tool(s) matched [employee, leave]:

hr__get_leave_balance - Query the remaining annual leave balance for an employee.
  params:
  - employee_id (string) - Employee identifier, e.g. E-1
```

Copy `hr__get_leave_balance` as the target and call
`invoke_this_tool({"target": "hr__get_leave_balance", "params": {"employee_id": "E-1"}})`.
The upstream result is returned unchanged.

## Configuration reference

### Upstream entries

Each key in `mcpServers` is a server name; each value is one of:

```json
{
  "mcpServers": {
    "local-tool": {
      "command": "/path/to/venv/bin/python",
      "args": ["server.py"],
      "env": { "API_KEY": "xxx" }
    },
    "remote-http": {
      "type": "http",
      "url": "https://example.com/mcp",
      "headers": { "Authorization": "Bearer xxx" }
    },
    "remote-sse": {
      "type": "sse",
      "url": "https://example.com/sse",
      "headers": { "Authorization": "Bearer xxx" }
    }
  }
}
```

| Field | Applies to | Meaning |
|---|---|---|
| `command` | stdio | Executable to spawn. |
| `args` | stdio | Argument array. |
| `env` | stdio | Child environment variables, merged into the SDK's default environment whitelist — not the full parent environment. |
| `url` | HTTP / SSE | Must use `http://` or `https://`. |
| `type` | HTTP / SSE | Omitted means Streamable HTTP; `"sse"` selects the legacy HTTP+SSE transport. |
| `headers` | HTTP / SSE | Request headers. |
| `description` | all | Optional service-level description injected into the search tool's description (max 500 code points). |

The transport is inferred from the fields: exactly one of `command` / `url` must be set.
`env` and `headers` values are passed **literally** — the proxy does not expand `${VAR}`
syntax. `description` is the only config field that enters the prompt; never put secrets
there.

### Settings

Every key is optional. Unknown keys fail fast (a typo must not silently fall back to a
default).

| Key | Type | Default | Meaning |
|---|---|---|---|
| `threshold` | int ≥ 1 | `30` | Maximum number of search results; above this the proxy refuses to list and asks the agent to narrow the query. |
| `refresh_interval` | int ≥ 1 | `600` | Seconds between timed refreshes (which also heal dead upstreams). |
| `fallback_sample_size` | int ≥ 1 | `10` | Maximum samples in the OR-fallback / keyword-split layer when an AND search finds nothing. |
| `description_max_servers` | int ≥ 1 | `15` | Maximum number of services listed in the injected description; beyond it the list is truncated and marked `(of M)`. |
| `handshake_timeout` | int ≥ 1 | `10` | Upstream handshake timeout in seconds, also used when re-spawning on refresh. |
| `index_dir` | string / null | `null` | Index directory. `null` means `tools_index/` next to the config file; a relative path is resolved against the config file's directory. |

### Fail-fast validation

Configuration errors exit immediately with code `2` and name the offending entry:

- file missing / not valid UTF-8 / invalid JSON / top level not an object / missing `mcpServers`
- `mcpServers` not an object; a server entry not an object
- server name outside `^[A-Za-z0-9_-]+$`, containing `__`, or a case-insensitive duplicate
- both `command` and `url` set, or neither
- invalid `type`, `type` conflicting with the transport, `url` not `http(s)://`
- wrong field types, unknown `settings` keys, integer settings below 1

### Search behavior

`search_mcp_tool` is case-insensitive **substring** matching, not a regex; regex
metacharacters are treated literally. Multiple keywords are AND-ed. The whole index line is
the match domain, so the server name itself works as a keyword (`["hr", "leave"]` narrows
to the `hr` service).

| Hit situation | Behavior |
|---|---|
| AND matches 1..`threshold` | Full definition list, each with a copyable target, parameter types and descriptions; destructive tools are marked `[destructive]`. |
| AND matches 0, some keywords match | Partial samples (sorted by number of matched keywords, at most `fallback_sample_size`), plus per-keyword hit counts such as `Keyword hits: invoice=35, archive=0`; CJK compound words also get fragment matches marked `[loose]`. |
| AND matches more than `threshold` | No list; a message to add keywords or a server name. |
| Nothing matches | A signpost of available services with their tool counts, plus usage hints. |
| Empty keywords | Usage hint plus the service list. |

Search with 1–2 domain words first. **Match the language of the index:** if upstream
descriptions are English, Chinese keywords will not match them.

## Run artifacts

### `tools_index/`

Created next to the config file by default (not in the current working directory), or at
`settings.index_dir` when set.

```text
tools_index/
├─ hr.jsonl            # one file per service, one tool per line
├─ itops.jsonl
└─ _status.json        # human-readable health snapshot
```

- `*.jsonl` is a plain-text index — open it to see exactly what the agent can find, or grep
  it for auditing.
- Each line has `server`, `name`, `title`, `description`, `inputSchema`, `annotations`.
- Writes are atomic (`tmp` + rename, UTF-8). **The index contains no config content**, so
  credentials never land on disk.
- A service that handshakes successfully but exposes zero tools gets no file.
- Only services from the most recent successful handshake are searchable, so a dead
  service's stale index is never treated as live.
- `_status.json` is the persisted health snapshot; check it first when something is not
  searchable.

### `call_log.jsonl` (optional, off by default)

Enable with `--call-log [path]`. Without a path it writes `call_log.jsonl` next to the
config file; relative paths are resolved against the config directory.

```bash
grep-mcp-tools --config config.json --call-log
grep-mcp-tools --config config.json --call-log logs/calls.jsonl
```

One JSON object per line, three kinds:

- `startup`: version, pid, config path, settings, initial health snapshot;
- `session`: each downstream handshake (session boundaries);
- `call`: every tool call — `seq`, timestamp, tool name, raw arguments, duration, error
  flag and category, response length and content; `search_mcp_tool` also records a
  structured `outcome` and `targets`.

Notes:

- The log records the config **path**, never its content (`env` / `headers` are never
  written).
- `invoke_this_tool` arguments and results are upstream business data, recorded truncated
  (4000 characters of response, 8000 of arguments). **Enable this for testing and
  diagnosis only.**
- If the log cannot be opened at startup the process exits (so "I thought it was logging"
  cannot happen silently); a mid-run write failure prints one stderr line and does not
  affect tool calls.
- The log never touches stdout; stdout stays a clean protocol channel.

## Host integration

### Claude Code, Claude Desktop, Cherry Studio and other stdio hosts

Add one entry as shown in Quick start. The proxy spawns or connects to the upstreams
itself, so the host only manages this one process.

Note: v1 is **stdio only and single-client**. One proxy process per downstream process.

### LangChain DeepAgents

`langchain-mcp-adapters` `get_tools()` opens a **new session per tool call** by default.
Against this proxy that means every search and invoke restarts the proxy, re-handshakes
every upstream and rebuilds the index. Because the proxy is a resident-index service, hold
one session for the whole agent lifetime:

```python
import asyncio

from deepagents import create_deep_agent
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_mcp_adapters.tools import load_mcp_tools

CONFIG = "/path/to/config.json"  # absolute path

SYSTEM_PROMPT = """\
When a task needs external data or actions:
1. Call search_mcp_tool with domain keywords first (employee, leave, alert, ...).
2. Copy the exact target from the result into invoke_this_tool.
3. Never invent a tool name or assume a tool exists.
If a search returns nothing, read the service list, then retry with other words or a server name.
"""

async def main():
    client = MultiServerMCPClient(
        {"tool-search": {"transport": "stdio", "command": "grep-mcp-tools",
                         "args": ["--config", CONFIG]}}
    )
    # Key: one proxy process for the whole agent lifetime.
    async with client.session("tool-search") as session:
        tools = await load_mcp_tools(session)
        agent = create_deep_agent(
            model="openai:gpt-5.5",  # your model
            tools=tools,
            system_prompt=SYSTEM_PROMPT,
        )
        result = await agent.ainvoke({"messages": [{"role": "user", "content": "How many leave days does E-1 have left?"}]})
        print(result["messages"][-1].content)

if __name__ == "__main__":
    asyncio.run(main())
```

- Keep the session wrapping the whole agent lifetime; do not use the agent after the
  `async with` block closes.
- Sub-agents do not inherit tools automatically: pass the same `tools` list explicitly.
- Do not share one proxy process across multiple agents/sessions.

### LangChain native `MCPAdapter`

`langchain.mcp.MCPAdapter` is shorter but **exposes no long-session API**: it opens a
session per tool call and closes it afterwards. Functionally fine; expect extra latency and
a discontinuous refresh state. Use it for one-off scripts, not for long tasks.

## Using a package index mirror

Behind a corporate mirror, point the installer at it:

- **uv** reads `UV_DEFAULT_INDEX` (replaces the default index) and `UV_INDEX` (adds an
  extra index). `UV_INDEX_URL` still works as a deprecated alias. **uv does not read
  `PIP_INDEX_URL`.**
- **pip** reads `PIP_INDEX_URL` and `PIP_EXTRA_INDEX_URL`.

```bash
UV_DEFAULT_INDEX=https://mirror.example.com/simple/ uvx grep-mcp-tools@0.1.0 --config /path/to/config.json
```

## System prompt tip

The upstream descriptions belong to your business. Tell the agent:

> When you need external data or actions, call `search_mcp_tool` with domain keywords
> first. Copy the target from the result into `invoke_this_tool`; do not compose tool
> names yourself. If a search returns nothing, read the service list and retry with other
> words or the server name.

Proxy-generated text is English, so asking the model to search in English keywords (when
the index is English) improves recall noticeably.

## Try the demo

The repository ships five fake upstreams
([`tests/e2e/probe.py`](https://github.com/qtalen/grep-mcp-tools/blob/main/tests/e2e/probe.py)).
From a checkout:

```bash
uv sync
uv run python tests/e2e/probe.py
```

Probe commands: `leave` (keyword search), `invoke hr__get_employee {"employee_id": "E-1"}`,
`status`, `tools`, `kill itops`, `start itops`. The fake HR service has 8 tools (records,
leave, payroll).

## CLI reference

```text
grep-mcp-tools --config <path> [--call-log [path]]
```

| Argument | Required | Meaning |
|---|---|---|
| `--config` | yes | Path to the JSON config file. |
| `--call-log` | no | Enable the call log; without a value, writes `<config dir>/call_log.jsonl`. |

Exit codes: `0` clean exit; `2` configuration error or call-log open failure.

All proxy-generated messages, signposts and errors are English; service-level
`description` values are kept verbatim in whatever language you write them.

## Known limits

Deliberate v1 trade-offs, not bugs:

| Limit | Explanation |
|---|---|
| stdio only, single client | No HTTP service form, no auth or multi-tenancy (v2 candidate). |
| No semantic/vector search | Pure keyword substring matching; search in the index's language. |
| No prompt-injection defense | Upstream descriptions appear verbatim in search results; same risk as attaching the upstream directly. |
| Results are not truncated | Pass-through principle: what the upstream returns is the upstream's business. |
| One tool per call | No batch invocation. |
| No tool governance or allow-listing | Per-client tool filtering is a v2 candidate. |
| Some CJK compound words may not match | When an AND search returns nothing, 2-gram fragments are added; the AND-hit branch does not split keywords. |
| Description injection depends on the host | `list_changed` is best-effort; when the host ignores it, the search signpost and `check_mcp_status` are the fallback. |

## Development

```bash
uv sync

# unit tests
uv run pytest tests/unit -q

# end-to-end tests (about 2 minutes on Windows; -n 4 is the recommended parallelism)
uv run pytest tests/e2e -n 4

# everything (spike-marked tests are skipped by default)
uv run pytest -q
```

Release smoke check (wheel and sdist manifest, then the installed package end to end):

```bash
uv build
uv run python -m tests.release.smoke --dist dist
```

Design and decision records live in
[`docs/design/`](https://github.com/qtalen/grep-mcp-tools/tree/main/docs/design) (start with
`vision.md`, then `architecture.md`); contribution and review rules are in
[`AGENTS.md`](https://github.com/qtalen/grep-mcp-tools/blob/main/AGENTS.md); release history
is in [`CHANGELOG.md`](https://github.com/qtalen/grep-mcp-tools/blob/main/CHANGELOG.md).

## License

MIT
