Skip to main content
Glama
README.md
# mcp-tool-server

[![CI](https://github.com/faizkhantech/mcp-tool-server/actions/workflows/ci.yml/badge.svg)](https://github.com/faizkhantech/mcp-tool-server/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.11%2B-blue)
![License](https://img.shields.io/badge/license-MIT-green)

A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gives LLM agents
structured, sandboxed access to a working directory: reading and searching files, querying
CSV/JSON/JSONL data and SQLite databases, inspecting git repositories, doing arithmetic, and
fetching URLs from an allowlist.

Any MCP client (Claude Desktop, Claude Code, the MCP Inspector, or your own agent harness) can
connect over stdio or streamable HTTP, discover the tools and their JSON schemas, and call them
through the standard `tools/list` and `tools/call` interface.

I built it around the things I actually want an agent to be able to do when working through an
evaluation run: look around a repo, grep for something, page through a long log, and ask
questions of a `results.jsonl` without pasting the whole file into context.

## Tools

All tools are read-only and return structured output (a JSON object with a published
`outputSchema`) as well as a text rendering for clients that only read text.

| Tool | What it does | Key inputs |
| --- | --- | --- |
| `list_files` | List directory entries with type and size; optional recursion and glob filter. | `path`, `pattern`, `recursive`, `include_hidden`, `max_entries` |
| `read_file` | Read a UTF-8 text file, or a window of lines from it, with total line count and a truncation flag. | `path`, `start_line`, `max_lines` |
| `search_files` | grep-style search across the workspace (plain text or regex). Skips hidden dirs and binary files. | `query`, `path`, `glob`, `regex`, `case_sensitive`, `max_results` |
| `query_records` | Filter, sort, project, group and summarise records in `.csv`, `.tsv`, `.json`, `.jsonl` or `.ndjson` files. Supports dotted paths for nested fields. | `path`, `filters`, `fields`, `sort_by`, `group_by`, `stats_field`, `limit` |
| `calculate` | Evaluate an arithmetic expression with math and statistics functions, without `eval`. | `expression` |
| `fetch_url` | HTTP GET against allowlisted hosts with a timeout and response size cap. Redirects are re-checked against the allowlist. | `url`, `max_bytes` |
| `sqlite_query` | Run a single read-only `SELECT` (or schema `PRAGMA`) against a SQLite file in the workspace. | `database`, `sql`, `params`, `max_rows` |
| `git_info` | Branch, HEAD, uncommitted changes, remotes and recent commits for a repo inside the workspace. | `path`, `max_commits` |

### Resources

| URI | Contents |
| --- | --- |
| `config://server` | JSON: workspace root, HTTP allowlist, timeouts and size limits the server is running with. |
| `workspace://tree` | Plain-text tree of the workspace, two levels deep. |

### Prompts

| Name | Arguments | Purpose |
| --- | --- | --- |
| `review_file` | `path` | Walks the model through reading a file and reporting bugs, risky patterns and readability issues with line numbers. |
| `analyze_eval_results` | `path`, `outcome_field` (default `passed`) | Has the model use `query_records` to compute the overall score, find which slices fail most, and summarise failure modes. |

### Example calls

```jsonc
// query_records: failures per category in an eval run
{
  "path": "runs/2024-11-02/results.jsonl",
  "filters": [{ "field": "passed", "op": "eq", "value": false }],
  "group_by": "category",
  "limit": 0
}
// -> { "total_records": 500, "matched": 87, "group_counts": { "docker": 41, "bash": 30, ... }, ... }

// query_records: pass rate (booleans average as 0/1)
{ "path": "runs/2024-11-02/results.jsonl", "stats_field": "passed", "limit": 0 }
// -> { "stats": { "field": "passed", "count": 500, "mean": 0.826, ... }, ... }

// sqlite_query
{ "database": "data/evals.db", "sql": "SELECT model, avg(score) FROM runs GROUP BY model" }

// calculate
{ "expression": "mean([0.71, 0.64, 0.80]) * 100" }
```

Filter operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `contains`, `in`, `exists`. Comparisons
coerce numeric strings, so CSV columns behave like their JSON equivalents.

## Quickstart

Requires Python 3.11+ and [uv](https://docs.astral.sh/uv/).

```bash
git clone https://github.com/faizkhantech/mcp-tool-server.git
cd mcp-tool-server
uv sync

# stdio (what desktop and CLI clients use)
uv run mcp-tool-server --root ~/code/my-project

# streamable HTTP on http://127.0.0.1:8000/mcp
uv run mcp-tool-server --root ~/code/my-project --transport streamable-http --port 8000

# allow fetch_url to reach specific hosts
uv run mcp-tool-server --root . --allow-host api.github.com --allow-host '*.python.org'
```

To poke at it interactively, run it under the MCP Inspector:

```bash
npx @modelcontextprotocol/inspector uv --directory /path/to/mcp-tool-server run mcp-tool-server --root /path/to/workspace
```

### Configuration

Every option can be set with an environment variable (handy in client config files) or a CLI
flag. Flags take precedence.

| Flag | Environment variable | Default | Meaning |
| --- | --- | --- | --- |
| `--root` | `MCP_TOOL_ROOT` | current directory | Workspace the tools are confined to. |
| `--allow-host` (repeatable) | `MCP_TOOL_ALLOWED_HOSTS` (comma separated) | none | Hosts `fetch_url` may contact. `example.com` is exact, `*.example.com` matches subdomains, `*` allows any host. Empty disables outbound HTTP. |
| `--http-timeout` | `MCP_TOOL_HTTP_TIMEOUT` | `10` | Seconds per HTTP request. |
| `--max-fetch-bytes` | `MCP_TOOL_MAX_FETCH_BYTES` | `1000000` | Response bodies are truncated beyond this. |
| `--max-read-bytes` | `MCP_TOOL_MAX_READ_BYTES` | `2000000` | Larger files are refused by `read_file`/`query_records` and skipped by `search_files`. |
| `--sql-timeout` | `MCP_TOOL_SQL_TIMEOUT` | `5` | Seconds a single SQLite query may run. |
| `--transport` | | `stdio` | `stdio` or `streamable-http`. |
| `--host`, `--port` | | `127.0.0.1`, `8000` | Bind address for streamable HTTP. |
| `--log-level` | | `WARNING` | Logs go to stderr; stdout is reserved for the protocol. |

## Connecting a client

### Claude Desktop

Add the server to `claude_desktop_config.json` (macOS:
`~/Library/Application Support/Claude/claude_desktop_config.json`, Windows:
`%APPDATA%\Claude\claude_desktop_config.json`) and restart the app:

```json
{
  "mcpServers": {
    "workspace-tools": {
      "command": "uv",
      "args": [
        "--directory", "/absolute/path/to/mcp-tool-server",
        "run", "mcp-tool-server",
        "--root", "/absolute/path/to/workspace"
      ],
      "env": {
        "MCP_TOOL_ALLOWED_HOSTS": "api.github.com,docs.python.org"
      }
    }
  }
}
```

Without cloning, `uvx` can run it straight from GitHub:

```json
{
  "mcpServers": {
    "workspace-tools": {
      "command": "uvx",
      "args": [
        "--from", "git+https://github.com/faizkhantech/mcp-tool-server",
        "mcp-tool-server", "--root", "/absolute/path/to/workspace"
      ]
    }
  }
}
```

### Claude Code

```bash
# stdio, scoped to the current project
claude mcp add workspace-tools -- \
  uv --directory /absolute/path/to/mcp-tool-server run mcp-tool-server --root "$PWD"

# or connect to a server already running with --transport streamable-http
claude mcp add --transport http workspace-tools http://127.0.0.1:8000/mcp
```

The same `mcpServers` block shown above also works in a project-level `.mcp.json`.

### Any MCP client (Python)

```python
import anyio
from mcp import Client, StdioServerParameters

params = StdioServerParameters(
    command="uv",
    args=[
        "--directory",
        "/path/to/mcp-tool-server",
        "run",
        "mcp-tool-server",
        "--root",
        "/path/to/workspace",
    ],
)


async def main() -> None:
    async with Client(params) as client:  # or Client("http://127.0.0.1:8000/mcp")
        tools = await client.list_tools()
        print([t.name for t in tools.tools])

        result = await client.call_tool("search_files", {"query": "TODO", "glob": "*.py"})
        print(result.structured_content)


anyio.run(main)
```

## Architecture

```
src/mcp_tool_server/
├── cli.py          argument parsing, env/flag merge, transport selection
├── config.py       ServerConfig (frozen dataclass) + MCP_TOOL_* env loading
├── server.py       build_server(config): registers tools, resources, prompts on MCPServer
└── tools/
    ├── sandbox.py  Workspace.resolve(): the single path-validation choke point
    ├── files.py    list_files, read_file, search_files, render_tree
    ├── data.py     query_records + CSV/JSON/JSONL loading
    ├── calc.py     AST-walking arithmetic evaluator
    ├── http.py     fetch_url (httpx, allowlist, redirects, size cap)
    ├── sqlite.py   sqlite_query (read-only connection + authorizer)
    └── git.py      git_info (subprocess, hardened config)
```

The server is built on the official [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
(`mcp.server.mcpserver.MCPServer`, the high-level API that was called `FastMCP` in SDK 1.x).

A few design decisions:

- **Tool logic is separate from registration.** Each module in `tools/` is plain Python that
  takes its dependencies (the `Workspace`, the `ServerConfig`) explicitly and returns a pydantic
  model. `server.py` wraps each one in a thin function whose signature is the tool's input
  schema. That keeps the tool code unit-testable without an MCP session, and the wrappers are
  where the agent-facing descriptions live.
- **Schemas come from type hints.** Parameters are annotated with `Annotated[..., Field(...)]`, so
  descriptions, defaults and bounds (`ge`/`le`) end up in the published JSON Schema, and the SDK
  rejects invalid arguments before the tool runs. Return types are pydantic models, which gives
  each tool an `outputSchema` and structured results.
- **Errors are results, not crashes.** Anticipated failures (bad path, invalid SQL, blocked host,
  timeout) raise `ToolError`, which the SDK turns into a `CallToolResult` with `isError: true` and
  a message the model can read and act on. Unexpected exceptions are logged with a traceback on
  the server and surface to the client as a generic tool error, so the session keeps running.
- **Config is built once and closed over.** `build_server(config)` creates a fresh server bound to
  one workspace, which makes it easy to run several isolated instances in tests.

## Security notes

This server is meant to give an agent useful, bounded access, not to be a hardened multi-tenant
sandbox. What it does and does not protect against:

- **Filesystem.** Every path goes through `Workspace.resolve`, which resolves symlinks and
  rejects anything that ends up outside the root (`../`, absolute paths, symlinks pointing out,
  NUL bytes). Directory walks skip symlinks that escape the root and do not follow symlinked
  directories. No tool writes to disk.
- **SQLite.** Databases are opened with `mode=ro`, and an authorizer callback denies everything
  except reads, functions and a handful of introspection pragmas, so `ATTACH`, DDL, writes and
  state-changing pragmas are rejected before they run. A progress handler aborts queries that
  exceed the time budget.
- **Git.** Commands run without a shell, with a timeout, and with `core.fsmonitor`,
  `core.hooksPath`, `core.pager` and `diff.external` overridden so a malicious repo config cannot
  execute programs. `GIT_CEILING_DIRECTORIES` stops repo discovery at the workspace boundary.
  Credentials embedded in remote URLs are stripped from the output.
- **HTTP.** Outbound requests are off unless you allowlist hosts. Only `http`/`https`, no
  credentials in URLs, every redirect hop is re-checked, bodies are capped and requests time out.
  Matching is by hostname, so allowlisting a name that resolves to an internal address will allow
  it; keep the list tight and avoid `*` on machines with access to internal services.
- **Calculator.** Expressions are parsed with `ast` and evaluated by walking a whitelist of node
  types. There is no `eval`, no attribute access and no names beyond a few constants. Exponents,
  integer size and factorial inputs are bounded to avoid CPU/memory blowups.
- **Streamable HTTP** binds to `127.0.0.1` by default and has no authentication. Do not expose
  it on a public interface without putting it behind something that does.
- **Prompt injection.** File contents and fetched pages are returned to the model verbatim. If the
  workspace or allowed hosts contain untrusted text, treat the agent's follow-up actions
  accordingly.

## Development

```bash
uv sync                      # creates .venv with runtime + dev dependencies
uv run pytest                # full test suite
uv run pytest tests/test_server.py -v
uv run ruff check . && uv run ruff format --check .
```

Tests are split into two layers:

- **Unit tests** (`test_files.py`, `test_data.py`, `test_calc.py`, `test_http.py`,
  `test_sqlite.py`, `test_git.py`, `test_config.py`) call the tool functions directly against a
  temporary workspace built in `conftest.py` (source files, a JSONL results file, a CSV, a SQLite
  database and a throwaway git repo). HTTP is tested with `httpx.MockTransport`, so nothing goes
  over the network.
- **Protocol tests** (`test_server.py`) connect a real MCP client to the server in-process and
  exercise `tools/list`, `tools/call`, resources and prompts, check the published schemas and
  error results, and launch the CLI as a subprocess over stdio.

CI runs lint and the test suite on Python 3.11 to 3.13 (Linux) and 3.13 on macOS.

### Adding a tool

1. Write the implementation in `tools/<name>.py` as a function that returns a pydantic model
   and raises `ToolError` for expected failures.
2. Register a wrapper in `build_server` with `@app.tool(...)`, annotating each parameter with a
   `Field(description=...)`.
3. Add unit tests for the function and extend `EXPECTED_TOOLS` in `tests/test_server.py`.

## License

[MIT](LICENSE)

TDQS

A3.6/5.0

Scored across 8 tools

Disambiguation4/5

Most tools have clearly distinct targets: list_files/read_file/search_files operate on workspace text, fetch_url on HTTP, git_info on repos. The only real boundary risk is query_records vs sqlite_query, both being 'query data' tools, but their descriptions clearly separate tabular files (jsonl/csv) from SQLite databases. Minor overlap keeps this from a perfect score.

Naming Consistency4/5

Five tools follow a clean verb_noun pattern (list_files, read_file, search_files, query_records, fetch_url). The deviations are mild and still readable: calculate is a bare verb, and sqlite_query/git_info are noun-first. No camelCase/snake_case mixing.

Tool Count5/5

Eight tools is well within the sweet spot and each covers a distinct capability: file listing/reading/search, structured data querying, arithmetic, HTTP fetch, SQLite access, and git status. Nothing feels padded or redundant.

Completeness3/5

The surface is heavily read-only: there is no write_file/create_file, no delete or move/rename, so an agent cannot produce or modify workspace content, which is an obvious gap for a workspace-oriented server. Read, search, query, fetch and git inspection are otherwise well covered.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues