Knowledge Base MCP Server
README.md
# Knowledge Base MCP Server
A small, local [MCP](https://modelcontextprotocol.io) server that gives an AI agent read/write access to a folder of markdown "knowledge base" files. It persists research, decisions, and findings across sessions, workspaces, and git worktrees — and works with any MCP-compatible IDE (Kiro, Cursor, Windsurf, VS Code + Continue, Claude Code/Desktop).
> **Platform:** developed and verified on **macOS**. The server is plain cross-platform Python, and Windows/Linux paths are provided throughout, but they are **unverified** — treat non-macOS use as untested until someone confirms it (a PR adding that confirmation is welcome).
`server.py` in this repository is the **canonical source** of the server. This README is the canonical setup + usage guide. (Some users also keep a companion `knowledge-base-server-guide.md` in their own knowledge base for the *agent operating protocol* — how an agent should use the KB day to day — but the code and its setup live here.)
---
## What it does
- **Persists context** as plain markdown files in a directory you choose (`KNOWLEDGE_DIR`). All tools operate on **`.md` files only** (bare names, no subdirectories).
- **Nine tools**: list, read (whole file or one section), search (regex), create/overwrite, append, replace-a-section, delete, list backups, restore backup. (The recommended config disables `delete_knowledge_file`, so a default install exposes **eight** — see "Register in your IDE's MCP config".)
- **Safe by default**: rejects filenames that escape the knowledge directory (`/`, `\`, `..`, absolute paths); timestamped backups before every destructive write; refuses to clobber an h1 title; refuses a section replace that would eat >80% of a file; keeps the 5 newest backups per file.
## Requirements
- Python 3.12
- [`uv`](https://docs.astral.sh/uv/) (used once to build the virtualenv)
- `fastmcp` (pinned — see `requirements.txt`)
> Commands below use `python3` (macOS/Linux). On Windows the interpreter is usually `python` — substitute accordingly.
## Install
```bash
# 1. Clone
git clone <REPO_URL> knowledge-mcp-server
cd knowledge-mcp-server
# 2. Build the dedicated virtualenv (Python 3.12) and install fastmcp into it
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python -r requirements.txt
# (Windows: uv pip install --python .venv\Scripts\python.exe -r requirements.txt)
# 3. Verify the install (boots the real server in an isolated temp KB; exits non-zero on failure).
.venv/bin/python verify_install.py
```
**Why a dedicated venv and not `uvx`?** An earlier version launched via `uvx --from fastmcp fastmcp run ...`, which re-resolved `fastmcp` from PyPI on *every* launch and failed when PyPI was unreachable (offline, or behind a VPN with TLS inspection) — `uvx` would hang ~49s then report "can't connect". Installing `fastmcp` once into a local `.venv` and launching its console binary directly removes all network from startup.
> Do **not** launch with `python -m fastmcp` — `fastmcp` has no `__main__` and errors with "cannot be directly executed". Always use the venv's `fastmcp` binary.
### Automated / agent install
An AI agent with shell access can install the server end-to-end with the deterministic sequence below. It clones, builds the venv, and **prints the exact MCP config block with real absolute paths filled in** — the agent then merges that block into the IDE config and triggers a reconnect (the one step that needs IDE/config access, not just a shell).
```bash
# Inputs the agent should set:
REPO_URL="<REPO_URL>" # the server's git URL
KNOWLEDGE_SERVER_DIR="$HOME/Documents/projects/knowledge-mcp-server" # where the code goes
KNOWLEDGE_DIR="$HOME/Documents/projects/knowledge" # where THIS user's .md files live
set -e
git clone "$REPO_URL" "$KNOWLEDGE_SERVER_DIR"
cd "$KNOWLEDGE_SERVER_DIR"
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python -r requirements.txt
mkdir -p "$KNOWLEDGE_DIR"
# Boot-check via the bundled verifier (isolated temp KB; exits non-zero on failure).
.venv/bin/python "$KNOWLEDGE_SERVER_DIR/verify_install.py"
# Emit the ready-to-merge MCP config block with absolute paths resolved:
cat <<JSON
"knowledge-base": {
"command": "$KNOWLEDGE_SERVER_DIR/.venv/bin/fastmcp",
"args": ["run", "$KNOWLEDGE_SERVER_DIR/server.py"],
"env": {
"KNOWLEDGE_DIR": "$KNOWLEDGE_DIR",
"FASTMCP_LOG_LEVEL": "ERROR"
},
"disabled": false,
"disabledTools": ["delete_knowledge_file"]
}
JSON
```
**Then (the human/config step):** merge that printed block into the `"mcpServers"` object of the correct IDE config file (see the locations table below), and reconnect the server (or restart the IDE). Verify with `list_knowledge_files()`. An agent that can also edit the IDE's JSON config can do the merge itself; triggering the client reconnect is usually the only part a shell cannot do.
## Configure your knowledge directory
The server stores files wherever `KNOWLEDGE_DIR` points. **Set it explicitly** — do not rely on the fallback. The code:
```python
KNOWLEDGE_DIR = Path(
os.environ.get("KNOWLEDGE_DIR", Path.home() / "Documents" / "projects" / "knowledge")
).expanduser()
```
- Set `KNOWLEDGE_DIR` in your MCP client's `env` block (below). A leading `~` is expanded.
- The `~/Documents/projects/knowledge` fallback is a last resort for a user who sets nothing; it is **not** recommended for a shared/ported setup.
- The directory and its `.backups/` are created automatically on first launch.
## Register in your IDE's MCP config
Same JSON shape for every IDE; only the config-file location differs.
```json
"knowledge-base": {
"command": "<KNOWLEDGE_SERVER_DIR>/.venv/bin/fastmcp",
"args": [
"run",
"<KNOWLEDGE_SERVER_DIR>/server.py"
],
"env": {
"KNOWLEDGE_DIR": "/absolute/path/to/your/knowledge",
"FASTMCP_LOG_LEVEL": "ERROR"
},
"disabled": false,
"disabledTools": ["delete_knowledge_file"]
}
```
Set three things for your machine:
1. `command` — absolute path to the venv's `fastmcp` binary (`.venv/bin/fastmcp`; on Windows `.venv\Scripts\fastmcp.exe`).
2. `args[1]` — absolute path to `server.py`.
3. `env.KNOWLEDGE_DIR` — absolute path to **your** knowledge folder.
Use absolute paths for `command`/`args` — a `~` or `$HOME` is **not** expanded inside JSON by the launcher. (`KNOWLEDGE_DIR` is the exception: the server expands a leading `~` itself.)
`disabledTools: ["delete_knowledge_file"]` is optional hardening that hides the destructive delete tool from the client. Recommended; drop it if you want delete available.
### Config file locations
| IDE | Config Path | Wrapper |
|-----|-------------|---------|
| Kiro | `~/.kiro/settings/mcp.json` (global) or `.kiro/settings/mcp.json` (workspace) | `{"mcpServers": {...}}` |
| Cursor | `.cursor/mcp.json` or `~/.cursor/mcp.json` | `{"mcpServers": {...}}` |
| Windsurf | `~/.codeium/windsurf/mcp_config.json` | `{"mcpServers": {...}}` |
| VS Code + Continue | `~/.continue/config.json` | `{"mcpServers": [...]}` (array) |
| Claude Code (CLI) | `~/.claude.json` (user scope, via `claude mcp add-json --scope user`) or `.mcp.json` (project scope) | `{"mcpServers": {...}}` - see the Claude Code note below |
| Claude Desktop (macOS) | `~/Library/Application Support/Claude/claude_desktop_config.json` | `{"mcpServers": {...}}` |
After saving, reconnect the MCP server (or restart the IDE), then verify by calling `list_knowledge_files()`.
**Claude Code note.** Register with the CLI rather than hand-editing JSON, so the entry lands in the right file and scope:
```bash
claude mcp add-json --scope user knowledge-base '{"type":"stdio","command":"<KNOWLEDGE_SERVER_DIR>/.venv/bin/fastmcp","args":["run","<KNOWLEDGE_SERVER_DIR>/server.py"],"env":{"KNOWLEDGE_DIR":"/absolute/path/to/your/knowledge","FASTMCP_LOG_LEVEL":"ERROR"}}'
claude mcp list # expect: knowledge-base ... Connected
```
- Claude Code does **not** honor `disabledTools` (or `disabled`), so `delete_knowledge_file` stays exposed. Block it with a permission deny rule in `~/.claude/settings.json`: `"permissions": {"deny": ["mcp__knowledge-base__delete_knowledge_file"]}`.
- Claude Code loads MCP servers at startup. A server added during a running session does not appear until Claude Code is restarted; `claude --continue` restarts and keeps the conversation.
## Tools
| Tool | Purpose | Safety |
|------|---------|--------|
| `list_knowledge_files()` | List all KB files with size + mtime | Read-only |
| `read_knowledge_file(filename, section?)` | Read a whole file, or one section by heading (exact heading first, then substring) | Read-only |
| `search_knowledge(query, case_sensitive?)` | Regex search across all files | Read-only |
| `update_knowledge_file(filename, content)` | Create or overwrite a file | Backup before overwrite |
| `append_to_knowledge_file(filename, content)` | Append to an existing file | Additive only |
| `replace_knowledge_section(filename, section_heading, new_content)` | Replace one section in place (pass the heading text without `#`; the body is written after one blank line) | Refuses h1; refuses >80%; refuses when several headings have that text; backup first; not-found lists headings containing the text |
| `delete_knowledge_file(filename)` | Delete a file | Backup before delete — *disabled by the recommended config* |
| `list_backups(filename?)` | List backups (all or one file) | Read-only |
| `restore_backup(backup_filename, target_filename?)` | Restore from a backup | Backs up current first |
## Design rationale (why the code is the way it is)
- **FastMCP + stdio.** The server is a single small `server.py` using `fastmcp`. stdio transport means each MCP client spawns its **own** server subprocess — there is no shared network service and no single-agent limit. The shared resource is the files in `KNOWLEDGE_DIR`; there is **no cross-process file lock**, so avoid concurrent writes to the *same* file from multiple agents.
- **Markdown files, not a database.** Human-readable, git-diffable, editable by hand, and trivially portable. No schema, no migrations.
- **`KNOWLEDGE_DIR` via env var.** Keeps the committed `server.py` identical for every user; each user points at their own folder from their MCP config. This is what makes the server portable.
- **Backups + guard rails exist because a real incident happened.** A `replace_knowledge_section` call once targeted an h1 heading and destroyed a ~50 KB file. The guards are the fix: (1) refuse to replace an h1 (it has no same-level sibling, so the "section" is the whole body); (2) refuse a replace spanning >80% of the file (catches heading-level edge cases); (3) timestamped backup before every destructive op; (4) keep 5 newest per file; (5) `restore_backup` also backs up the current copy so a bad restore is itself undoable.
- **Section addressing is regex over markdown headings, and read vs. replace differ on purpose.** Both locate a heading and take everything up to the next heading at the same-or-higher level. **`read_knowledge_file` matches leniently**: an exact heading first (whole heading equals `section`), then a substring fallback (first heading *containing* `section`). **`replace_knowledge_section` matches strictly**: the heading must equal `section_heading` exactly. So a string that reads a section may be broader than one that can replace it — when in doubt, pass the full exact heading; if a replace finds no match, its error lists the headings that contain the text. Headings should be unique within a file: replace refuses (and changes nothing) when more than one heading has the text, because picking the first one once overwrote the wrong section. Replace's heading pattern allows only spaces/tabs around the text (never newlines), so the match is exactly the heading line and repeating the same replace leaves the file unchanged. A copy of the same heading at the start of `new_content` is dropped, so the heading never ends up twice; the copy is matched at the same level, ignoring case, trailing spaces and CRLF line endings, while a deeper heading with the same text (`### Notes` under `## Notes`) is kept as content. Known limit: `#` lines inside fenced code blocks still count as headings.
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| "Failed to connect" in IDE logs | Server crashes on startup | Run manually: `<KNOWLEDGE_SERVER_DIR>/.venv/bin/fastmcp run <KNOWLEDGE_SERVER_DIR>/server.py` and read stderr |
| `ModuleNotFoundError: mcp.server.fastmcp` | Installed `mcp[cli]`, not `fastmcp` | `uv pip install --python .venv/bin/python -r requirements.txt` |
| "cannot be directly executed" | Launched `python -m fastmcp` | Use the venv's `fastmcp` **binary** |
| Server connects, no tools listed | Syntax error in `server.py` | `python3 -c "import ast; ast.parse(open('server.py').read())"` |
| Writes fail | `KNOWLEDGE_DIR` unwritable | Check the path; it is auto-created on boot |
| Python version mismatch | System Python too old | Build the venv with `uv venv --python 3.12 .venv` |
| "refusing to replace an h1 heading" | Tried to replace a doc title | Use `update_knowledge_file`, or target an h2+ section |
| "refusing to replace section… spans N%" | Section too large relative to file | Use `update_knowledge_file`, or split into smaller headings |
| "Section '## X' not found ... without the leading '#' characters" | `replace_knowledge_section` takes the heading text, not the markdown line | Pass `X`; the error lists the matching headings |
| "refusing to replace section 'X': N headings ... have that text (lines ...)" | The file repeats a heading (e.g. `### Tickets` under several parents) | Rename them so each is unique (e.g. `### Acme - Tickets`), or rewrite the file with `update_knowledge_file` |
| Many blank lines between a heading and its body | Written by a server before the 2026-11-30 fix (each replace added one) | Update the server; the next replace of that section normalizes it |
| Data loss | File overwritten/corrupted | `list_backups(filename="x.md")` then `restore_backup(...)` |
| A write seems to lose another agent's edit | Two clients wrote the **same** file concurrently (no cross-process lock) | Avoid concurrent writes to one file; recover the lost side from `.backups/` via `list_backups` / `restore_backup`. See "Roadmap / possible enhancements". |
| Server exits immediately at startup with a traceback about `KNOWLEDGE_DIR` | `KNOWLEDGE_DIR` points at an unwritable / invalid path — the dir is created at import time, so a bad value crashes the boot | Set `KNOWLEDGE_DIR` to a writable absolute path and reconnect. Run the server manually (see the "Failed to connect" row) to see the exact path in the traceback. |
| Claude Code: server shows Connected in `claude mcp list` but its tools are missing in the current session | Server was added after the session started; Claude Code loads MCP servers at startup | Restart Claude Code (`claude --continue` keeps the conversation) |
| Claude Code: `delete_knowledge_file` is still callable despite `disabledTools` | Claude Code ignores `disabledTools` | Add `mcp__knowledge-base__delete_knowledge_file` to `permissions.deny` in `~/.claude/settings.json` |
| Code change to `server.py` isn't taking effect | The MCP client holds ONE long-lived server subprocess — it does not re-read `server.py` per call | Reconnect the server in your IDE (or restart it) after editing `server.py`; the new process picks up the change. |
## Roadmap / possible enhancements
Not implemented today — candidates for a future PR:
- **Concurrency safety.** There is no cross-process file lock, so two clients writing the *same* file can clobber one another (the losing write is still recoverable from `.backups/`). A future enhancement could add an advisory lock (e.g. `fcntl`/`msvcrt`) or a last-modified-time check that refuses a write when the file changed since it was read. Kept out of v1 to stay small and dependency-light.
- **Soft delete / deprecation instead of hard delete.** `delete_knowledge_file` currently backs up then removes the file outright (and is disabled by the recommended config for that reason). A safer model would *deprecate* rather than destroy: e.g. move the file to a `.deprecated/` (or `.archive/`) subfolder and/or stamp a `Status: Deprecated` marker in its Meta, so it drops out of normal `list`/`search` results but remains recoverable without digging through timestamped `.backups/`. This would let the tool stay enabled by default while making "deletion" reversible and auditable. Add matching `list_deprecated` / `restore_deprecated` (or an `include_deprecated` flag on `list`/`search`) in the same change.
- **Indexing / scale for large knowledge bases (more than a few dozen files).** Today `search_knowledge` and `list_knowledge_files` read and scan **every** `.md` on every call (linear, full-file reads, line-by-line regex). That is fine for a handful of files but degrades as the base grows — large files, many files, and big result sets all cost more each call, and there is no ranking. Future enhancements: a persisted index (e.g. an SQLite FTS table, or a cached `{file → headings, mtime, size}` manifest refreshed on change) so `list`/search skip unchanged files; result ranking and pagination; a headings-only/outline mode so an agent can locate a section without pulling whole files; and optionally scoping search to a subset (by filename glob or by `_index.md` mapping). Keep any index derived and disposable — the markdown files remain the source of truth.
## Testing
The repo ships three layers of tests. Run them from the repo root inside the venv.
**First time (or if you have not run them yet)** — install the dev dependencies, then run both the suite and the verifier:
```bash
cd <KNOWLEDGE_SERVER_DIR> # the repo root
# 1. one-time: install dev dependencies (pytest etc.) into the venv
uv pip install --python .venv/bin/python -r requirements-dev.txt
# 2. unit + end-to-end tests (expect: "N passed")
.venv/bin/python -m pytest
# 3. post-install verification (expect: "VERIFY OK")
.venv/bin/python verify_install.py
```
`pytest` needs the dev dependencies from step 1 — without them it fails with
`No module named pytest`. `verify_install.py` needs only the runtime deps, so it also
works standalone right after install. On Windows use `.venv\Scripts\python.exe`.
- **Unit tests** (`tests/test_unit.py`) — call each tool's logic directly against a
temp `KNOWLEDGE_DIR`: the `_safe_name` guard, create/read, exact-vs-substring section
matching, append, replace (h1 refuse, >80% refuse, happy path), search, backup
rotation, restore, delete.
- **End-to-end tests** (`tests/test_e2e.py`) — spawn `server.py` as a real MCP
subprocess over stdio and drive it through a `fastmcp` client (initialize handshake,
tool-schema check, tool calls). This catches schema/transport regressions a unit test
cannot.
- **Install verification** (`verify_install.py`) — a standalone, pytest-free smoke check
that boots the server in an isolated throwaway `KNOWLEDGE_DIR`, confirms all 9 tools
are advertised, round-trips a file, and checks the safety guard. Exits non-zero on
failure. **Run it right after installing** and after any config change.
**When to run what:**
- After **installing or updating** the server → `verify_install.py`.
- Before opening a **PR**, and after any change to `server.py` → `pytest` (unit + e2e) **and** `verify_install.py`.
- In **CI** → both; all must pass.
Tests use only throwaway temp directories and never touch a real knowledge base.
## Contributing
Improvements to the server are welcome via pull request — bug fixes, new tools, better guard rails, cross-platform fixes.
1. **Fork / branch** off the default branch.
2. **Change `server.py`** (and `requirements.txt` if you touch dependencies — keep `fastmcp` pinned).
3. **Validate**: run `.venv/bin/python -m pytest` (unit + e2e) **and** `.venv/bin/python verify_install.py`; both must pass. Add a short note in the PR of what you tested. If you changed behavior, add or update a test for it.
4. **Update the docs in the same PR** whenever behavior changes:
- this `README.md` (tools table, config, troubleshooting, design rationale), and
- a `CHANGELOG.md` entry.
If you also maintain the companion `knowledge-base-server-guide.md` in your knowledge base, update its tool list / protocol too — but that file is per-user and is **not** in this repo.
5. **Open the PR** against `<REPO_URL>`. Describe the problem, the change, and how you verified it.
> Keep the server small and dependency-light. The whole point is a single file an agent can reason about and a user can audit.
## What is NOT in this repo
Your actual knowledge `.md` files are **per-user and private** — they are not committed here (the `.gitignore` excludes a top-level `knowledge/` directory if you keep one inside the repo). Point `KNOWLEDGE_DIR` at a folder outside the repo.
## License
See `LICENSE`.
## Changelog
See [`CHANGELOG.md`](CHANGELOG.md) for the full, dated history. Add an entry there in the same PR as any behavior change (see Contributing).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues