Knowledge Base MCP Server
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Knowledge Base MCP Server
A small, local MCP 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.mdfiles 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.
Related MCP server: Obsidian Second Brain MCP
Requirements
Python 3.12
uv(used once to build the virtualenv)fastmcp(pinned — seerequirements.txt)
Commands below use
python3(macOS/Linux). On Windows the interpreter is usuallypython— substitute accordingly.
Install
# 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.pyWhy 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—fastmcphas no__main__and errors with "cannot be directly executed". Always use the venv'sfastmcpbinary.
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).
# 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"]
}
JSONThen (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:
KNOWLEDGE_DIR = Path(
os.environ.get("KNOWLEDGE_DIR", Path.home() / "Documents" / "projects" / "knowledge")
).expanduser()Set
KNOWLEDGE_DIRin your MCP client'senvblock (below). A leading~is expanded.The
~/Documents/projects/knowledgefallback 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.
"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:
command— absolute path to the venv'sfastmcpbinary (.venv/bin/fastmcp; on Windows.venv\Scripts\fastmcp.exe).args[1]— absolute path toserver.py.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 |
|
|
Cursor |
|
|
Windsurf |
|
|
VS Code + Continue |
|
|
Claude Code (CLI) |
|
|
Claude Desktop (macOS) |
|
|
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:
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 ... ConnectedClaude Code does not honor
disabledTools(ordisabled), sodelete_knowledge_filestays 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 --continuerestarts and keeps the conversation.
Tools
Tool | Purpose | Safety |
| List all KB files with size + mtime | Read-only |
| Read a whole file, or one section by heading (exact heading first, then substring) | Read-only |
| Regex search across all files | Read-only |
| Create or overwrite a file | Backup before overwrite |
| Append to an existing file | Additive only |
| Replace one section in place (pass the heading text without | Refuses h1; refuses >80%; refuses when several headings have that text; backup first; not-found lists headings containing the text |
| Delete a file | Backup before delete — disabled by the recommended config |
| List backups (all or one file) | Read-only |
| 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.pyusingfastmcp. 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 inKNOWLEDGE_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_DIRvia env var. Keeps the committedserver.pyidentical 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_sectioncall 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_backupalso 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_filematches leniently: an exact heading first (whole heading equalssection), then a substring fallback (first heading containingsection).replace_knowledge_sectionmatches strictly: the heading must equalsection_headingexactly. 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 ofnew_contentis 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 (### Notesunder## 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: |
| Installed |
|
"cannot be directly executed" | Launched | Use the venv's |
Server connects, no tools listed | Syntax error in |
|
Writes fail |
| Check the path; it is auto-created on boot |
Python version mismatch | System Python too old | Build the venv with |
"refusing to replace an h1 heading" | Tried to replace a doc title | Use |
"refusing to replace section… spans N%" | Section too large relative to file | Use |
"Section '## X' not found ... without the leading '#' characters" |
| Pass |
"refusing to replace section 'X': N headings ... have that text (lines ...)" | The file repeats a heading (e.g. | Rename them so each is unique (e.g. |
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 |
|
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 |
Server exits immediately at startup with a traceback about |
| Set |
Claude Code: server shows Connected in | Server was added after the session started; Claude Code loads MCP servers at startup | Restart Claude Code ( |
Claude Code: | Claude Code ignores | Add |
Code change to | The MCP client holds ONE long-lived server subprocess — it does not re-read | Reconnect the server in your IDE (or restart it) after editing |
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_filecurrently 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 aStatus: Deprecatedmarker in its Meta, so it drops out of normallist/searchresults but remains recoverable without digging through timestamped.backups/. This would let the tool stay enabled by default while making "deletion" reversible and auditable. Add matchinglist_deprecated/restore_deprecated(or aninclude_deprecatedflag onlist/search) in the same change.Indexing / scale for large knowledge bases (more than a few dozen files). Today
search_knowledgeandlist_knowledge_filesread and scan every.mdon 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) solist/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.mdmapping). 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:
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.pypytest 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 tempKNOWLEDGE_DIR: the_safe_nameguard, 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) — spawnserver.pyas a real MCP subprocess over stdio and drive it through afastmcpclient (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 throwawayKNOWLEDGE_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) andverify_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.
Fork / branch off the default branch.
Change
server.py(andrequirements.txtif you touch dependencies — keepfastmcppinned).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.Update the docs in the same PR whenever behavior changes:
this
README.md(tools table, config, troubleshooting, design rationale), anda
CHANGELOG.mdentry. If you also maintain the companionknowledge-base-server-guide.mdin your knowledge base, update its tool list / protocol too — but that file is per-user and is not in this repo.
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 for the full, dated history. Add an entry there in the same PR as any behavior change (see Contributing).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Markdown workspace for AI agents: read, write, organize, and share markdown documents.
Markdown notes in folders, with files, that your AI assistant can read, write and organise.
- Very Simple NotesDeprecatedcom.verysimplenotes
Markdown notes in folders, with files, that your AI assistant can read, write and organise.
Persistent docs and memory for AI agents — read, write, organize & search a shared workspace.
Related MCP Servers
- FlicenseNot gradedqualityBmaintenancePersistent memory for AI agents enabling saving, searching, and managing knowledge across sessions with local markdown files.-
- AlicenseAqualityDmaintenanceEnables AI agents to store and retrieve project context, bugs, decisions, and session logs by reading and appending markdown files in a local Obsidian vault, without requiring any cloud services.6MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to securely read and write to an Obsidian-compatible Markdown vault with per-agent access control, audit logging, and conflict resolution.Apache 2.0
- AlicenseNot gradedqualityBmaintenanceTurns a folder of Markdown notes into an agent-native knowledge base, providing long-term memory with provenance, token-budgeted retrieval, and safe write-back with versioning.MIT