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

Support assistants get more useful when they can look things up themselves: the help-centre article that answers the question, the team's reply macros, and the order or ticket in the database. They also get more dangerous. `mcp-tools-server` is a TypeScript [Model Context Protocol](https://modelcontextprotocol.io) server, built on the official SDK, that gives any MCP client (Claude Desktop, Claude Code, an IDE, your own agent) six read-only tools for a support team. Every boundary is enforced in code: files are confined to one folder with path traversal and symlink checks, SQL is SELECT-only on a read-only connection, inputs are validated with zod, and every failure comes back as a clear, typed error the model can act on.

## Architecture

```mermaid
flowchart LR
    C[MCP client<br/>Claude Desktop, Claude Code,<br/>IDE, custom agent] <-->|stdio, JSON-RPC| S[McpServer<br/>zod input schemas]
    S --> H[Tool handler<br/>typed errors, stderr log]
    H --> KB[KnowledgeBase<br/>BM25 over sections,<br/>extractive summary]
    H --> F[FileArea<br/>resolveInside:<br/>no .., no absolute,<br/>no hidden, realpath check]
    H --> Q[ReadOnlyDatabase<br/>readonly + query_only,<br/>SELECT only, row cap]
    KB --> MD[(Help-centre<br/>Markdown)]
    F --> FS[(Shared folder<br/>macros, playbooks, reports)]
    Q --> DB[(SQLite<br/>customers, orders,<br/>refunds, tickets)]
```

## Quickstart

No API key is needed: the server calls no model, the client does.

```bash
git clone https://github.com/Mateen-Rahmat/mcp-tools-server.git
cd mcp-tools-server
npm ci
npm run build    # compile to dist/ and create the sample database
npm test         # 51 vitest tests, including a real stdio session
npm run demo     # scripted support-ticket walk-through over stdio
npm run eval     # retrieval and security evaluation
```

`make setup`, `make test`, `make demo` and `make eval` do the same.

To poke at it interactively, use the MCP Inspector:

```bash
npx @modelcontextprotocol/inspector node dist/index.js
```

## Connecting a client

The server speaks MCP over stdio. By default it serves the bundled sample data; point it at your own folders with flags or environment variables (`MCP_KB_DIR`, `MCP_FILES_DIR`, `MCP_DB_PATH`).

### Claude Desktop

Open Settings, Developer, Edit Config (the file is `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS and `%APPDATA%\Claude\claude_desktop_config.json` on Windows) and add:

```json
{
  "mcpServers": {
    "support-tools": {
      "command": "node",
      "args": [
        "/absolute/path/to/mcp-tools-server/dist/index.js",
        "--kb", "/absolute/path/to/help-centre",
        "--files", "/absolute/path/to/shared-support-folder",
        "--db", "/absolute/path/to/support.db"
      ]
    }
  }
}
```

Leave out `--kb`, `--files` and `--db` to use the sample data. Restart Claude Desktop; the tools appear under the tools icon in the chat box. Ask something like "What do we tell a customer whose tracking has not moved, and how many open shipping tickets do we have?"

### Claude Code

```bash
claude mcp add support-tools -- node /absolute/path/to/mcp-tools-server/dist/index.js
```

### Other MCP clients

Any client that can launch a stdio server works: the command is `node /absolute/path/to/dist/index.js` with the optional flags above. Logs go to stderr as JSON lines (one per tool call, with duration and error code), so stdout stays clean for the protocol.

## Tools

| Tool | Input | What it returns |
|---|---|---|
| `search_knowledge_base` | `query`, `limit` (1 to 10) | Best help-centre sections: path, title, section, BM25 score, snippet |
| `summarize_article` | `path`, `max_sentences` (1 to 10), optional `focus` | Section headings and the most relevant sentences, quoted verbatim |
| `list_files` | `folder`, `recursive` | Files and folders in the shared folder, with sizes |
| `read_file` | `path` | Contents of one text file, up to 256 KB |
| `describe_database` | none | Tables, columns and row counts |
| `query_database` | `sql`, `max_rows` (1 to 500) | Columns, rows and whether the result was truncated |

All six carry the `readOnlyHint` annotation, so clients can skip confirmation prompts for them.

Errors look like `Error (outside_allowed_folder): "../secret.txt" points outside the allowed folder.` or `Error (query_failed): SQLite could not run the query: no such column: nope. Call describe_database to check table and column names.` The code is stable for programs, and the sentence tells the model what to do next. Unexpected exceptions are logged in full to stderr but reported to the client only as an internal error, so stack traces and local paths do not leak into the conversation.

## How it works

**Knowledge base.** Each Markdown article is split into sections at `##` and `###` headings, and sections are ranked with BM25. The title and heading are indexed with the body (the heading twice), so a query that names the topic lands on that section. Search returns sections rather than whole articles, which keeps tool results short.

**Summaries without a model.** `summarize_article` is extractive: it picks the sentences that share the most words with the `focus` (or the first sentence of each section) and returns them verbatim, in document order. The client's model writes the actual answer; the tool's job is to hand it a compact, faithful extract that cannot contain invented facts.

**File sandbox.** Every path goes through `resolveInside(root, path)`, which refuses NUL bytes, absolute and drive-letter paths, any segment starting with `.` (so `.env` and `.git` are unreachable), anything that leaves the root after `..` is resolved, and anything whose `realpath` leaves the root, which catches symlinks pointing out. Backslashes are normalised so Windows-style traversal is caught too. Listings skip hidden files and symlinks; reads refuse folders, files over 256 KB and binary files.

**Read-only SQL, in layers.** The database is opened with `readonly: true` and `PRAGMA query_only = ON`. Before running anything, the server strips comments, requires the statement to start with `SELECT` or `WITH`, refuses `WITH RECURSIVE`, lets SQLite reject multiple statements, and checks that SQLite reports the prepared statement as read-only and returning rows. Rows are streamed and capped. Any single layer would stop most writes; together they mean a mistake in one is not a hole.

**Sample data.** `data/kb` holds ten help-centre articles (the same corpus as [rag-eval-kit](https://github.com/Mateen-Rahmat/rag-eval-kit)), `data/files` holds reply macros, an escalation playbook, refund approval limits and a ticket-volume report, and `src/seed.ts` generates a deterministic SQLite database with 6 customers, 24 orders, refunds and 40 tickets.

## Evaluation results

These come from real runs of `npm run eval` on 2026-12-03. No model is involved: the evaluation drives the server through the MCP protocol with an in-memory client. Raw output: [`results/2026-12-03/eval.json`](results/2026-12-03/eval.json).

**Retrieval** on 25 customer-phrased questions, each labelled with the article and section that answers it ([`eval/search-queries.json`](eval/search-queries.json)):

| Metric | Value |
|---|---|
| Right article at rank 1 | 0.80 |
| Right article in top 3 | 0.92 |
| Right section at rank 1 | 0.68 |
| Right section in top 3 | 0.80 |
| Section MRR@5 | 0.743 |

**Security**, every attempt sent through the protocol as a client would ([`eval/security-cases.json`](eval/security-cases.json)):

| Check | Result |
|---|---|
| Path traversal attempts blocked (`..`, backslashes, absolute, `.env`, symlinks out, NUL byte) | 15 / 15 |
| SQL write attempts blocked (DML, DDL, PRAGMA, ATTACH, stacked statements, comment tricks, writes inside CTEs, recursive CTE) | 16 / 16 |
| Secret file contents in any response | none |
| Row counts after the run | unchanged |

What the retrieval misses show: the search is lexical, so it fails when the customer and the article use different words. "My blender arrived broken" finds nothing, because the article says "damaged". "I was charged twice" ranks "When you are charged" above "Double charges". "Can I cancel my order before it ships" ranks the subscriptions article's "Cancelling" first. I did not tune the tokenizer against these questions, because that would make the numbers meaningless; synonyms or embeddings are the next step.

## Design decisions and trade-offs

- **Read-only by design.** No tool can change anything, so a manipulated or confused model can read too much at worst, never break something. Write actions (refunds, ticket updates) belong behind a confirmation gate like the one in [support-agent-reference](https://github.com/Mateen-Rahmat/support-agent-reference), not in a general-purpose server.
- **Raw SQL rather than fixed query tools.** A `query_database` tool lets the model answer questions nobody anticipated ("open urgent billing tickets this week"), at the cost of trusting it with the whole schema. The layered read-only checks make that safe for data access; it would not be the right choice for a database with personal data that the model should only see per customer.
- **Lexical search, no embeddings.** BM25 is deterministic, fast, offline and explainable, and the evaluation shows exactly where it fails. The cost is vocabulary mismatch, measured above.
- **Extractive summaries.** No model call inside the server keeps it keyless and cheap, and quoted sentences cannot be hallucinated. The summary is less fluent, which is fine because the client's model rewrites it anyway.
- **Errors as results, not exceptions.** MCP tool errors returned with `isError` reach the model, which can correct itself (fix a column name, pick another path). Protocol-level exceptions would just fail the turn.
- **stdio only.** It is what desktop clients use and needs no auth. Serving a team over HTTP would need authentication and per-user scoping first.

## Limitations

- Search is keyword-based and English-only; paraphrased questions miss (see the results).
- There is no query timeout. Recursive CTEs are refused, but a deliberately expensive cross join on a large database could still run for a long time.
- The SQL tool exposes every table to the client. Column-level or row-level restrictions would need a view layer.
- Symlinks inside the shared folder are followed only when they stay inside it; they are not shown in listings.
- The knowledge base is loaded at start-up; edits need a restart.

## Next steps

- Run SQL in a worker thread with a time limit, and add an allowlist of tables or views.
- Add a synonym table or an optional embedding index, and compare it with BM25 on the same 25 questions.
- Watch the knowledge base folder and re-index on change.
- Add a Streamable HTTP transport with authentication for shared deployments.
- Expose articles as MCP resources so clients can attach them directly.

## Project layout

```
src/
  index.ts        stdio entry point
  server.ts       tool registration, schemas, error handling, logging
  config.ts       flags, environment variables and defaults
  kb.ts           Markdown parsing, BM25 search, extractive summaries
  files.ts        listing and reading inside the allowed folder
  paths.ts        resolveInside: the path traversal guard
  sql.ts          read-only SQLite access
  seed.ts         deterministic sample database
data/             sample help-centre articles and shared files
scripts/          seed and demo scripts
eval/             labelled search questions, security cases, eval runner
results/          committed evaluation output
tests/            unit, protocol and stdio tests (vitest)
```

## License

MIT