Personal Knowledge MCP
by sethships
README.md
# Personal Knowledge MCP
An AI-first knowledge management service built on the Model Context Protocol (MCP) that enables Claude Code and other AI assistants to efficiently access, retrieve, and utilize knowledge from software development projects and educational materials.
[](https://github.com/sethships/PersonalKnowledgeMCP/actions/workflows/ci.yml) []() []() []() []()
## Overview
Personal Knowledge MCP is a purpose-built MCP service that creates a semantic bridge between AI development workflows and diverse knowledge sources. Unlike traditional knowledge management systems retrofitted for AI access, this project is designed from the ground up for AI assistant integration.
**Current Status**: V1.0 Complete (Phases 1-5 Complete, Phase 4 Enterprise Features Framework Only)
### Current Capabilities
Personal Knowledge MCP provides a comprehensive suite of AI-powered code intelligence features:
| Capability | Description | Status |
|------------|-------------|--------|
| **Semantic Search** | Natural language code search across repositories | Complete |
| **Multi-Provider Embeddings** | OpenAI, Transformers.js (local), Ollama support | Complete |
| **Knowledge Graph** | FalkorDB-powered code dependency analysis | Complete |
| **Dependency Analysis** | Forward dependencies (what code depends on) | Complete |
| **Impact Analysis** | Reverse dependencies (what depends on code) | Complete |
| **Architecture Insights** | Module structure and inter-module dependencies | Complete |
| **Path Finding** | Trace execution flow between code entities | Complete |
| **AST Parsing** | Code-aware indexing for 13 languages | Complete |
| **Incremental Updates** | Fast index updates after PR merges | Complete |
| **Multi-Instance Isolation** | Separate Private/Work/Public knowledge bases | Complete |
| **HTTP Transport** | Cursor, VS Code Continue, and other client support | Complete |
| **Token Authentication** | Secure API access with scoped tokens | Complete |
| **Rate Limiting** | Configurable per-minute/per-hour limits | Complete |
| **OIDC Framework** | Microsoft Entra ID, Auth0, Okta support | Framework Ready |
| **Local Folder as Repository** | Index any local folder as a first-class repository (code + docs + graph) | Complete |
| **Document Graph Extraction** | Markdown links, headings, and `[[wikilinks]]` participate in the knowledge graph | Complete |
### Supported Repository Sources
Repositories can be registered from three different source types. All three are first-class at the MCP tool layer — `list_indexed_repositories`, `semantic_search`, and the graph tools (`get_dependencies`, `get_dependents`, `get_architecture`, `find_path`, `get_graph_metrics`) work identically across them.
| Source | `RepositoryInfo.source` | How to register | Notes |
|--------|------------------------|-----------------|-------|
| GitHub / git remote | `git-remote` | `pk-mcp index <git-url>` | Cloned to `./data/repositories/` and refreshed via the GitHub Compare API. |
| Local git checkout | `local-git` | `pk-mcp index <local-path>` (auto-detected when the path contains a `.git` dir) | Uses the existing local checkout; `git pull` drives incremental updates. |
| Local folder (no git) | `local-folder` | `pk-mcp index <local-path>` or the `register_local_folder` MCP tool | Per-repo manifest tracks `mtime`/`size`/SHA-256 for change detection. `tier='public'` is refused. See [ADR-0009](docs/architecture/adr/0009-local-folder-as-repository.md). |
### When to Use What
| Use Case | Tool | Example Query |
|----------|------|---------------|
| Find code by concept | `semantic_search` | "JWT authentication middleware" |
| Pre-change analysis | `get_dependencies` | "What does auth.ts depend on?" |
| Refactoring impact | `get_dependents` | "What will break if I change validateToken?" |
| Understand structure | `get_architecture` | "Show me the module organization" |
| Trace execution flow | `find_path` | "How does login connect to database?" |
| Repository health | `get_graph_metrics` | "Show dependency statistics" |
| Register a local folder as a repo | `register_local_folder` | Index `D:\notes` as a `local-folder` source with the watcher enabled |
### Key Features
- **MCP-Native Architecture**: Purpose-built for AI assistant integration via the Model Context Protocol
- **Semantic Code Search**: AI assistants can find relevant code and documentation without full codebase scans
- **Knowledge Graph**: FalkorDB-powered dependency analysis and impact assessment
- **Private Repository Support**: Secure indexing of private GitHub repositories via PAT
- **Vector-Based Retrieval**: Fast, accurate semantic search using ChromaDB
- **Flexible Embedding Providers**: OpenAI (highest quality), Transformers.js (zero-config local), Ollama (GPU acceleration)
- **Multi-Transport Support**: stdio for Claude Code, HTTP/SSE for Cursor and VS Code
- **Local-First Deployment**: Runs entirely on localhost with Docker Compose
- **Local Folder as Repository**: Register a local folder as a first-class repository — same MCP tools, same lifecycle, no git remote required
## Use Cases
### Software Project Knowledge Management
Manage knowledge for active coding projects with intelligent semantic indexing:
- Index GitHub repositories (private and public)
- Semantic search across code, documentation, and reference materials
- Code dependency analysis and impact assessment
- Efficient context retrieval for AI assistants (reduces token waste)
- Query response times under 500ms (95th percentile)
**Example Query**: *"Find authentication middleware that validates JWT tokens"*
## Technology Stack
| Component | Technology | Purpose |
|-----------|------------|---------|
| Runtime | Bun 1.0+ | Fast all-in-one JavaScript runtime |
| Language | TypeScript 5.3+ | Type-safe development |
| MCP SDK | @modelcontextprotocol/sdk | Official MCP implementation |
| Vector DB | ChromaDB | Semantic search and similarity |
| Graph DB | FalkorDB 4.x (default), Neo4j (optional) | Code dependency graph and relationships |
| AST Parsing | tree-sitter (web-tree-sitter), Roslyn | Code entity extraction for 13 languages |
| Embeddings | OpenAI, Transformers.js, Ollama | Embedding generation |
| HTTP Server | Express 5.x | HTTP/SSE transport |
| Authentication | Bearer Token, OIDC | Secure API access |
| Deployment | Docker Compose | Container orchestration |
| Testing | Bun Test | Built-in test runner with coverage |
### Supported Languages
The following languages are supported for AST parsing, graph population, and semantic search filtering:
| Category | Languages | Parser |
|----------|-----------|--------|
| TypeScript/JavaScript | TypeScript, TSX, JavaScript, JSX | tree-sitter |
| Systems | Rust, C, C++ | tree-sitter |
| JVM | Java | tree-sitter |
| Go | Go | tree-sitter |
| Scripting | Python, Ruby, PHP | tree-sitter |
| .NET | C# | Roslyn |
## Architecture
```mermaid
graph TB
subgraph HOST["HOST SYSTEM (Windows)"]
CC[Claude Code<br/>Client]
CURSOR[Cursor/VS Code<br/>HTTP Clients]
subgraph MCP_SVC["MCP Service (Bun/Node.js)"]
STDIO[stdio Transport]
HTTP[HTTP/SSE Transport]
AUTH[Auth Middleware]
TH[Tool Handlers]
SS[semantic_search]
LR[list_indexed_repositories]
GD[get_dependencies]
GT[get_dependents]
GA[get_architecture]
FP[find_path]
SL[Service Layer]
SRCH[Search Service]
REPO[Repository Service]
GRAPH[Graph Service]
STDIO --> TH
HTTP --> AUTH --> TH
TH --> SS
TH --> LR
TH --> GD
TH --> GT
TH --> GA
TH --> FP
SS --> SL
LR --> SL
GD --> GRAPH
GT --> GRAPH
GA --> GRAPH
FP --> GRAPH
SL --> SRCH
SL --> REPO
end
subgraph DOCKER["Docker Containers"]
CDB[ChromaDB<br/>Vector Database<br/>Port: 8000]
FALKR[FalkorDB<br/>Graph Database<br/>Port: 6380]
VOL[Volume: ./data/chromadb]
FALKRVOL[Volume: ./data/falkordb]
CDB -.->|persists to| VOL
FALKR -.->|persists to| FALKRVOL
end
FS[Local File System<br/>./data/repos/]
CC <-->|stdio| STDIO
CURSOR -->|HTTPS| HTTP
MCP_SVC -->|HTTP| CDB
MCP_SVC -->|Redis| FALKR
MCP_SVC -->|clone/read| FS
end
subgraph EMBED["Embedding Providers (Choose One)"]
LOCAL[Transformers.js<br/>Local CPU - Default]
OLLAMA[Ollama Server<br/>Local GPU]
OAI[OpenAI API<br/>Cloud - Optional]
end
MCP_SVC -.->|default| LOCAL
MCP_SVC -.->|optional| OLLAMA
MCP_SVC -.->|optional| OAI
classDef client fill:#e1f5ff,stroke:#01579b,stroke-width:3px,color:#000
classDef service fill:#fff9c4,stroke:#f57f17,stroke-width:3px,color:#000
classDef storage fill:#e8f5e9,stroke:#1b5e20,stroke-width:3px,color:#000
classDef external fill:#ffe0b2,stroke:#e65100,stroke-width:3px,color:#000
classDef embed fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
class CC,CURSOR client
class MCP_SVC,STDIO,HTTP,AUTH,TH,SS,LR,GD,GT,GA,FP,SL,SRCH,REPO,GRAPH service
class CDB,FALKR,VOL,FALKRVOL,FS storage
class LOCAL,OLLAMA embed
class OAI external
```
## Getting Started
### Prerequisites
- **Bun**: 1.0 or later ([install](https://bun.sh/))
- **Docker Desktop**: For running ChromaDB and FalkorDB
- **Git**: For repository cloning
- **GitHub PAT** (optional): For private repository access
**Note**: No OpenAI API key is required. The system works fully offline with local embedding providers (Transformers.js or Ollama). OpenAI is available as an optional provider for highest quality embeddings.
### Quick Start
1. **Clone the repository**:
```bash
git clone https://github.com/sethships/PersonalKnowledgeMCP.git
cd PersonalKnowledgeMCP
```
2. **Install dependencies**:
```bash
bun install
```
3. **Configure environment**:
```bash
cp .env.example .env
# Edit .env and set FALKORDB_PASSWORD (required for graph database)
# OpenAI API key is OPTIONAL - local embeddings work without it
```
4. **Start ChromaDB and FalkorDB**:
```bash
docker compose --profile default up -d
```
5. **Build the project**:
```bash
bun run build
```
6. **Run database migrations** (for FalkorDB):
```bash
bun run cli graph migrate
```
7. **Index a repository**:
```bash
bun run cli index https://github.com/user/repo.git
```
8. **Populate the knowledge graph**:
```bash
bun run cli graph populate repo-name
```
9. **Configure Claude Code**:
Add to your Claude Code MCP configuration (`~/.config/claude-code/mcp.json`):
```json
{
"mcpServers": {
"personal-knowledge": {
"command": "bun",
"args": ["run", "C:/src/PersonalKnowledgeMCP/dist/index.js"],
"env": {
"OPENAI_API_KEY": "${OPENAI_API_KEY}",
"GITHUB_PAT": "${GITHUB_PAT}",
"FALKORDB_HOST": "localhost",
"FALKORDB_PORT": "6380",
"FALKORDB_PASSWORD": "${FALKORDB_PASSWORD}"
}
}
}
}
```
10. **Query from Claude Code**:
```
Use the semantic_search tool to find authentication middleware
```
### Docker Troubleshooting
If you encounter issues with Docker Compose:
**ChromaDB won't start:**
```bash
# Check if Docker Desktop is running
docker --version
# Check if port 8000 is in use
netstat -an | findstr :8000
# View detailed logs
docker compose logs chromadb
```
**FalkorDB won't start:**
```bash
# View detailed logs
docker compose logs falkordb
# Check FalkorDB health
docker compose exec falkordb redis-cli -a YOUR_PASSWORD ping
```
**Need to reset data:**
```bash
# WARNING: This deletes all data
docker compose down -v
docker compose --profile default up -d
```
For detailed Docker operations guide, see [docs/docker-operations.md](docs/docker-operations.md).
## Claude Code Integration
Personal Knowledge MCP is designed to seamlessly integrate with Claude Code, providing AI-assisted code search and retrieval capabilities directly in your development workflow.
### Quick Setup
1. **Prerequisites**:
- Personal Knowledge MCP built and containers running
- At least one repository indexed and graph populated
- Bun or Node.js installed
2. **Configure Claude Code**:
Add the MCP server configuration to your Claude Code MCP settings file (location varies by platform):
- **Windows**: `%APPDATA%\Claude Code\mcp.json`
- **macOS**: `~/Library/Application Support/Claude Code/mcp.json`
- **Linux**: `~/.config/claude-code/mcp.json`
```json
{
"mcpServers": {
"personal-knowledge": {
"command": "bun",
"args": ["run", "/absolute/path/to/PersonalKnowledgeMCP/dist/index.js"],
"env": {
"OPENAI_API_KEY": "${OPENAI_API_KEY}",
"GITHUB_PAT": "${GITHUB_PAT}",
"CHROMADB_HOST": "localhost",
"CHROMADB_PORT": "8000",
"FALKORDB_HOST": "localhost",
"FALKORDB_PORT": "6380",
"FALKORDB_PASSWORD": "${FALKORDB_PASSWORD}"
}
}
}
}
```
3. **Restart Claude Code** to load the new MCP server
4. **Verify Integration**:
- In Claude Code, you should see tools available:
- **`semantic_search`**: Search your indexed code semantically
- **`list_indexed_repositories`**: View indexed repositories
- **`get_dependencies`**: Analyze code dependencies
- **`get_dependents`**: Analyze code impact
- **`get_architecture`**: View module structure
- **`find_path`**: Trace code connections
Try asking: *"Can you list my indexed repositories?"*
### Usage Examples
Once integrated, Claude Code can help you find code across your indexed projects:
**Find specific implementations**:
```
Find authentication middleware that validates JWT tokens
```
**Explore code patterns**:
```
Show me examples of error handling in the API layer
```
**Dependency analysis**:
```
What does src/services/auth.ts depend on?
```
**Impact analysis before refactoring**:
```
What code will be affected if I change the validateToken function?
```
**Architecture overview**:
```
Show me the module organization of the services directory
```
**Cross-repository search**:
```
Find all implementations of rate limiting across my projects
```
### HTTP Client Configuration (Cursor, VS Code)
For clients that use HTTP transport instead of stdio:
1. **Enable HTTP transport** in your `.env`:
```bash
HTTP_TRANSPORT_ENABLED=true
HTTP_PORT=3001
HTTP_HOST=127.0.0.1
```
2. **Create an authentication token**:
```bash
bun run cli token create --name "cursor-dev" --scopes read,write
```
3. **Configure your client** with the HTTP endpoint:
- **Endpoint**: `http://localhost:3001/api/v1/mcp`
- **Authorization**: `Bearer <your-token>`
See [docs/client-configuration.md](docs/client-configuration.md) for detailed client setup.
### Incremental Update Workflow
After merging a PR to an indexed repository, update your index to include the latest changes. You can trigger updates directly from Claude Code using MCP tools (recommended) or via CLI.
#### MCP Tools (Recommended for AI Workflows)
The easiest way to keep your index current is to use the MCP tools directly from Claude Code:
**Quick Update (Synchronous)**:
```
Use the trigger_incremental_update tool with repository "my-project"
```
Claude Code will wait for the update to complete and report results including files changed, chunks updated, and the latest commit.
**Background Update (Asynchronous)**:
```
Use the trigger_incremental_update tool with repository "my-project" and async true
```
This returns immediately with a `job_id`. Check progress with:
```
Use the get_update_status tool with job_id "<job-id-from-above>"
```
**Requirements**:
- `GITHUB_PAT` environment variable must be set in your MCP configuration
- Repository must already be indexed (use `list_indexed_repositories` to check)
- Rate limited to 1 update per repository per 5 minutes
**Example Response (Synchronous)**:
```json
{
"success": true,
"repository": "my-project",
"status": "updated",
"files_added": 2,
"files_modified": 5,
"files_deleted": 1,
"chunks_upserted": 42,
"chunks_deleted": 8,
"duration_ms": 3250,
"commit_sha": "abc1234",
"commit_message": "feat: add new authentication flow"
}
```
#### CLI Commands (For Automation/Scripts)
For automated workflows or shell scripts, use the CLI:
**Typical Post-PR Workflow:**
```bash
# 1. After PR is merged, update the index
bun run cli update my-project
# 2. Update the knowledge graph
bun run cli graph populate my-project
# 3. Verify update completed
bun run cli status
# 4. (Optional) View update history
bun run cli history my-project
```
**Daily Sync for Multiple Projects:**
```bash
# Update all indexed repositories at once
bun run cli update-all
```
### Performance
The MCP integration is optimized for fast response times:
- Tool discovery: <100ms
- Repository listing: <50ms
- Semantic search: <500ms (95th percentile)
- Dependency queries: <300ms
- Architecture queries: <500ms
### Requirements
- **Bun 1.0+** or **Node.js 18+** (for running the MCP server)
- **Docker Desktop** (for ChromaDB and FalkorDB)
- **At least one indexed repository** (use `bun run cli index <url>`)
**Note**: No API keys required for basic operation. Local embedding providers (Transformers.js, Ollama) work offline without external dependencies.
## MCP Tools
### semantic_search
Search indexed repositories using natural language queries.
**Parameters**:
- `query` (string, required): Natural language search query
- `limit` (number, optional): Maximum results to return (default: 10, max: 50)
- `threshold` (number, optional): Minimum similarity score 0.0-1.0 (default: 0.7)
- `repository` (string, optional): Filter to specific repository
- `language` (string, optional): Filter by programming language
**Supported Languages for `language` filter**:
`typescript`, `tsx`, `javascript`, `jsx`, `python`, `java`, `go`, `rust`, `csharp`, `c`, `cpp`, `ruby`, `php`
**Example**:
```json
{
"query": "error handling middleware",
"limit": 5,
"threshold": 0.75,
"language": "typescript"
}
```
### list_indexed_repositories
List all indexed repositories with status and statistics.
**Returns**:
- Repository name and URL
- File count and chunk count
- Last indexed timestamp
- Indexing status (ready, indexing, error)
### get_dependencies
Query what a file, function, or class depends on. Returns imports, calls, and inheritance relationships.
**Parameters**:
- `entity_type` (string, required): Type of entity - `"file"`, `"function"`, or `"class"`
- `entity_path` (string, required): Path or identifier (e.g., `"src/auth/middleware.ts"`)
- `repository` (string, required): Repository name to scope the query
- `depth` (number, optional): Transitive dependency depth 1-5 (default: 1)
- `relationship_types` (array, optional): Filter by relationship type - `["imports", "calls", "extends", "implements", "references"]`
**Example**:
```json
{
"entity_type": "file",
"entity_path": "src/services/auth.ts",
"repository": "my-api",
"depth": 2
}
```
**Requires**: FalkorDB graph database with indexed repository data.
### get_dependents
Query what depends on a file, function, or class. Use for impact analysis before refactoring.
**Parameters**:
- `entity_type` (string, required): Type of entity - `"file"`, `"function"`, `"class"`, or `"package"`
- `entity_path` (string, required): Path or identifier of the entity
- `repository` (string, optional): Repository name (omit to search all)
- `depth` (number, optional): Transitive dependent depth 1-5 (default: 1)
- `include_cross_repo` (boolean, optional): Search across repositories (default: false)
**Example**:
```json
{
"entity_type": "function",
"entity_path": "validateToken",
"repository": "my-api",
"depth": 2
}
```
**Response includes**:
- List of dependent entities with relationship types
- Impact analysis metrics (direct count, transitive count, impact score)
**Requires**: FalkorDB graph database with indexed repository data.
### get_architecture
Get the module structure and inter-module dependencies for a repository.
**Parameters**:
- `repository` (string, required): Repository name
- `module_path` (string, optional): Specific module to analyze
**Returns**: Module hierarchy with dependency relationships.
### find_path
Find the shortest path between two code entities in the dependency graph.
**Parameters**:
- `source_type` (string, required): Source entity type
- `source_path` (string, required): Source entity path
- `target_type` (string, required): Target entity type
- `target_path` (string, required): Target entity path
- `repository` (string, required): Repository name
**Returns**: Path of entities connecting source to target.
> **Note**: Graph tools require FalkorDB and AST-parsed repository data. See [Graph Tools Documentation](docs/graph-tools.md) for detailed setup and usage examples.
### trigger_incremental_update
Trigger an incremental index update for an already-indexed repository. Use this to refresh the knowledge base after merging PRs or making code changes.
**Parameters**:
- `repository` (string, required): Repository name (must already be indexed)
- `async` (boolean, optional): If `true`, return immediately with a job ID for background processing. Default: `false`
**Synchronous Response** (`async=false`):
```json
{
"success": true,
"repository": "my-project",
"status": "updated",
"files_added": 2,
"files_modified": 5,
"files_deleted": 1,
"chunks_upserted": 42,
"chunks_deleted": 8,
"duration_ms": 3250,
"commit_sha": "abc1234",
"commit_message": "feat: add new feature"
}
```
**Asynchronous Response** (`async=true`):
```json
{
"success": true,
"async": true,
"job_id": "update-abc123-1706789012345",
"repository": "my-project",
"message": "Update started. Use get_update_status tool with this job_id to check progress."
}
```
**Rate Limiting**: Limited to 1 update per repository per 5 minutes. If rate limited, the response includes `retry_after_seconds`.
**Requirements**:
- `GITHUB_PAT` environment variable must be set
- Repository must already be indexed
### get_update_status
Check the status of an async incremental update job.
**Parameters**:
- `job_id` (string, required): Job ID returned from `trigger_incremental_update` when `async=true`
**Response**:
```json
{
"success": true,
"job_id": "update-abc123-1706789012345",
"repository": "my-project",
"status": "completed",
"started_at": "2026-02-01T12:30:12.345Z",
"completed_at": "2026-02-01T12:30:45.678Z",
"result": {
"files_added": 2,
"files_modified": 5,
"files_deleted": 1,
"chunks_upserted": 42,
"chunks_deleted": 8
}
}
```
**Status Values**:
- `pending` - Job created, waiting to start
- `running` - Update in progress
- `completed` - Update finished successfully
- `failed` - Update failed (includes `error` message)
- `timeout` - Update exceeded 10-minute timeout
**Note**: Jobs are automatically cleaned up after 1 hour.
### register_local_folder
Register a local filesystem folder as a `local-folder` repository. The folder is scanned, embeddings are generated, and (by default) a filesystem watcher is started so the index re-syncs as files change. See [ADR-0009](docs/architecture/adr/0009-local-folder-as-repository.md) for the design rationale.
**Parameters**:
- `path` (string, required): Absolute or relative path to the folder to register
- `name` (string, optional): Repository display name. Defaults to the basename of the resolved path
- `tier` (string, optional): Security tier — `"private"` (default) or `"work"`. `"public"` is **refused** for local folders
- `force` (boolean, optional): Re-register even if a repo with the same name or absolute path is already registered (default: `false`)
- `watch` (boolean, optional): Start the filesystem watcher after the initial scan (default: `true`)
- `followSymlinks` (boolean, optional): Follow filesystem symlinks inside the folder. Out-of-folder targets are rejected even when this is `true` (default: `false`)
- `async` (boolean, optional): If `true`, return a job ID immediately and run registration in the background. Poll `get_update_status` with the `job_id` (default: `false`)
**Example**:
```json
{
"path": "D:\\notes",
"name": "research-notes",
"tier": "private",
"watch": true
}
```
**Notes**:
- The registered folder appears in `list_indexed_repositories` with `source: "local-folder"` and the absolute path.
- All graph and search MCP tools accept the registered name as a `repository` filter.
- Markdown files participate in the document graph (headings, links, `[[wikilinks]]`); PDF/DOCX participate at lower fidelity (edges carry a `confidence` attribute).
## Embedding Providers
Personal Knowledge MCP is designed to work **fully offline** with local embedding providers. No external API keys are required.
### Local-First Design
The system defaults to local embedding providers that require no configuration, API keys, or internet access:
| Provider | Setup Required | Offline | GPU | Quality | Cost |
|----------|---------------|---------|-----|---------|------|
| **Transformers.js** | None (default) | Yes | No | Good | Free |
| **Ollama** | Install Ollama | Yes | Yes | Good-High | Free |
| **OpenAI** | API key | No | N/A | Highest | Per-token |
### Recommended Configuration
| Scenario | Recommendation |
|----------|---------------|
| **Getting started** | Use defaults (Transformers.js) |
| **Have a GPU** | Configure Ollama for faster indexing |
| **Need highest quality** | Optional: Add OpenAI API key |
| **Air-gapped/offline** | Transformers.js or Ollama (pre-download models) |
### Default Behavior
- **Default (no configuration)**: Uses Transformers.js - works immediately
- **With `EMBEDDING_PROVIDER=ollama`**: Uses Ollama for GPU acceleration
- **With `EMBEDDING_PROVIDER=openai`**: Uses OpenAI (an `OPENAI_API_KEY` alone does not select it; opting into per-token cost is explicit)
> **Upgrading from the old auto-detection** (where a set `OPENAI_API_KEY` implied OpenAI): repositories already indexed with OpenAI keep querying through OpenAI via the provider recorded in their metadata, so existing search keeps working. Indexing *new* repositories with OpenAI now requires `EMBEDDING_PROVIDER=openai`.
### Usage
```bash
# Default selection (Transformers.js unless EMBEDDING_PROVIDER is set)
bun run cli index https://github.com/user/repo
# Explicit provider selection
bun run cli index --provider openai https://github.com/user/repo
bun run cli index --provider transformersjs https://github.com/user/repo
bun run cli index --provider ollama https://github.com/user/repo
# Check available providers
bun run cli providers status
```
For detailed configuration, model options, offline usage, and troubleshooting, see the [Embedding Provider Guide](docs/embedding-providers.md).
## CLI Usage
The Personal Knowledge MCP includes a command-line interface (`pk-mcp`) for managing indexed repositories.
### Installation
After building the project, you can use the CLI directly or install it globally:
```bash
# Build the CLI
bun run build
# Run directly
bun run dist/cli.js --help
# Or install globally
bun link
pk-mcp --help
```
### Commands
#### index - Index a Repository or Local Folder
Index a git repository **or** a local folder for semantic search. The first argument is auto-detected: a git URL is cloned, an absolute or relative filesystem path is registered as a local folder. A local path that contains a `.git` directory is registered as a `local-git` source; otherwise it is registered as `local-folder`.
```bash
pk-mcp index <url-or-path> [options]
```
**Options:**
- `-n, --name <name>` - Custom repository name (defaults to repo name from URL or basename of the path)
- `-b, --branch <branch>` - Branch to clone (git only; ignored for local folders)
- `-f, --force` - Force reindexing if a repository with this name or path is already registered
- `--provider <provider>` - Embedding provider (openai, transformersjs, ollama)
- `--tier <tier>` - Security tier: `private` | `work` | `public`. Local folders default to `private`; `public` is **refused** for local folders
- `--watch` / `--no-watch` - Enable / disable the filesystem watcher for a local folder (default: enabled)
- `--follow-symlinks` - Follow filesystem symlinks inside a local folder. Out-of-folder targets are rejected even when set (default: skip)
**Examples:**
```bash
# Index a public git repository
pk-mcp index https://github.com/user/my-project.git
# Index with custom name and specific branch
pk-mcp index https://github.com/user/repo.git --name my-repo --branch develop
# Reindex an existing repository
pk-mcp index https://github.com/user/repo.git --force
# Register a local folder as a repository (auto-detected from the path)
pk-mcp index D:\notes --name research-notes --tier private
# Register a local folder without starting the filesystem watcher
pk-mcp index ./scratch-project --no-watch
```
> See [ADR-0009](docs/architecture/adr/0009-local-folder-as-repository.md) for the design rationale behind the `local-folder` source type and how it relates to Phase 6 WatchedFolders.
#### search - Semantic Search
Search indexed repositories using natural language queries.
```bash
pk-mcp search <query> [options]
```
**Options:**
- `-l, --limit <number>` - Maximum results (1-100, default: 10)
- `-t, --threshold <number>` - Similarity threshold (0.0-1.0, default: 0.7)
- `-r, --repo <name>` - Filter to specific repository
- `--json` - Output as JSON
#### status - List Repositories
List all indexed repositories with their status and statistics.
```bash
pk-mcp status [options]
```
**Options:**
- `--json` - Output as JSON
#### update - Update Repository Index
Incrementally update a repository's index with changes since last indexing.
```bash
pk-mcp update <repository-name> [options]
```
**Options:**
- `-f, --force` - Force full re-index instead of incremental update
- `--json` - Output as JSON
- `-v, --verbose` - Show all errors with actionable guidance
#### graph migrate - Run Graph Migrations
Set up or update the FalkorDB schema.
```bash
pk-mcp graph migrate [options]
```
#### graph populate - Populate Knowledge Graph
Parse code and populate the FalkorDB knowledge graph for a repository.
```bash
pk-mcp graph populate <repository-name> [options]
```
**Options:**
- `-f, --force` - Force full repopulation
#### graph populate-all - Populate All Repositories
Populate the knowledge graph for all indexed repositories.
```bash
pk-mcp graph populate-all [options]
```
#### token create - Create Authentication Token
Create a new authentication token for HTTP access.
```bash
pk-mcp token create --name <name> --scopes <scopes> [options]
```
**Options:**
- `--name <name>` - Token name (required)
- `--scopes <scopes>` - Comma-separated scopes: read, write, admin
- `--instances <instances>` - Comma-separated instance access: private, work, public
- `--expires <duration>` - Expiration: hours, days, weeks, months, years, never
#### health - Health Check
Check the health of all required services.
```bash
pk-mcp health
```
#### watch add - Register a Watched Folder
Register a local folder for watching and indexing.
```bash
pk-mcp watch add <folder-path> [options]
```
**Options:**
- `-n, --name <name>` - Custom folder name (defaults to folder basename)
- `--json` - Output as JSON
#### watch list - List Watched Folders
Display all watched folders with status.
```bash
pk-mcp watch list [options]
```
**Options:**
- `--json` - Output as JSON
#### watch remove - Remove a Watched Folder
Unregister a watched folder.
```bash
pk-mcp watch remove <name-or-path> [options]
```
**Options:**
- `-f, --force` - Skip confirmation prompt
- `--json` - Output as JSON
#### watch pause - Pause a Watched Folder
Disable watching without removing registration.
```bash
pk-mcp watch pause <name-or-path> [options]
```
**Options:**
- `--json` - Output as JSON
#### watch resume - Resume a Watched Folder
Re-enable a paused watched folder.
```bash
pk-mcp watch resume <name-or-path> [options]
```
**Options:**
- `--json` - Output as JSON
#### watch rescan - Rescan a Watched Folder
Manually trigger re-indexing for a watched folder.
```bash
pk-mcp watch rescan <name-or-path> [options]
```
**Options:**
- `--full` - Delete existing collection and perform a full re-index
- `--provider <provider>` - Embedding provider (openai, transformersjs, ollama)
- `--json` - Output as JSON
### CLI Configuration
The CLI uses the same environment variables as the MCP server:
```bash
# Embedding provider (defaults to local Transformers.js)
# Options: transformers (default), ollama, openai
EMBEDDING_PROVIDER=transformers
# Optional: OpenAI API key (only needed if using OpenAI provider)
# OPENAI_API_KEY=sk-...
# Required for FalkorDB graph database
FALKORDB_HOST=localhost
FALKORDB_PORT=6380
FALKORDB_PASSWORD=your-password
# Optional (defaults shown)
CHROMADB_HOST=localhost
CHROMADB_PORT=8000
DATA_PATH=./data
CLONE_PATH=./data/repositories
LOG_LEVEL=warn
```
## Development
### Project Structure
```
PersonalKnowledgeMCP/
├── src/ # Source code
│ ├── index.ts # MCP server entry point
│ ├── cli.ts # CLI entry point
│ ├── mcp/ # MCP server implementation
│ │ └── tools/ # MCP tool handlers
│ ├── services/ # Business logic
│ ├── providers/ # Embedding providers
│ ├── storage/ # ChromaDB client
│ ├── graph/ # FalkorDB graph operations
│ │ ├── parsing/ # AST parsing (tree-sitter, Roslyn)
│ │ ├── extraction/ # Entity and relationship extraction
│ │ └── migration/ # Schema migrations
│ ├── http/ # HTTP/SSE transport
│ ├── auth/ # Authentication (token, OIDC)
│ └── ingestion/ # File processing
├── tests/ # Test suite
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── docs/ # Documentation
│ ├── architecture/ # Technical design docs
│ └── pm/ # Project management
├── config/ # Configuration files
├── docker-compose.yml # Container deployment
└── package.json # Dependencies
```
### Available Scripts
```bash
bun run build # Compile TypeScript with Bun
bun run dev # Development mode with watch
bun test # Run test suite with Bun's built-in runner
bun test --watch # Run tests in watch mode
bun test --coverage # Run tests with coverage report (90% minimum)
bun run lint # Run ESLint
bun run format # Format code with Prettier
bun run typecheck # TypeScript type checking
bun run cli # Run CLI commands
```
### Running Tests
```bash
# Run all tests
bun test
# Run with coverage (minimum 90% required)
bun test --coverage
# Run specific test file
bun test tests/unit/search-service.test.ts
# Run in watch mode
bun test --watch
```
## Documentation
### Getting Started
- **[Claude Code Setup Guide](docs/claude-code-setup.md)** - Complete MCP integration guide
- **[Client Configuration](docs/client-configuration.md)** - HTTP client setup (Cursor, VS Code)
### Reference Documentation
- **[CLI Commands Reference](docs/cli-commands-reference.md)** - Complete CLI command documentation
- **[MCP Tools API Reference](docs/mcp-tools-reference.md)** - Formal API documentation for all MCP tools
- **[Configuration Reference](docs/configuration-reference.md)** - All environment variables and settings
### Feature Guides
- **[Embedding Provider Guide](docs/embedding-providers.md)** - OpenAI, Transformers.js, and Ollama configuration
- **[Graph Tools Guide](docs/graph-tools.md)** - Dependency analysis and impact assessment tools
- **[FalkorDB Setup Guide](docs/graph-database-setup.md)** - Knowledge graph database setup
### Operations
- **[Docker Operations Guide](docs/docker-operations.md)** - ChromaDB and container management
- **[Troubleshooting Guide](docs/troubleshooting.md)** - Common issues and solutions
- **[Performance Tuning Guide](docs/performance-tuning-guide.md)** - Optimization strategies
### Architecture & Design
- **[Feature Summary](docs/feature-summary.md)** - Complete feature list, status, and known limitations (all phases)
- **[System Design Document](docs/architecture/Phase1-System-Design-Document.md)** - Technical architecture and implementation details
- **[Docker Containerization PRD](docs/pm/Docker-Containerization-PRD.md)** - Multi-transport MCP, security architecture, and deployment strategy
- **[Knowledge Graph PRD](docs/pm/knowledge-graph-PRD.md)** - Graph database design and tools
### Development
- **[Project Configuration](.claude/CLAUDE.md)** - Development guidelines for Claude Code
## Performance Targets
### Query Performance
- MCP query response: **<500ms** (95th percentile)
- MCP query response: **<200ms** (50th percentile)
- Vector similarity search: **<200ms**
- Dependency queries: **<300ms**
- Architecture queries: **<500ms**
### Ingestion Performance
- Small repository (<500 files): **<5 minutes**
- Medium repository (500-2000 files): **<15 minutes**
- Batch embedding generation: **>100 files/min**
## Testing
The project maintains **90% minimum test coverage** across all components.
**Test Priorities**:
- MCP tool handlers: 95% coverage (P0)
- Search service: 95% coverage (P0)
- Embedding provider: 90% coverage (P0)
- ChromaDB client: 90% coverage (P0)
- Graph service: 90% coverage (P0)
- File processing: 85-95% coverage (P1)
## Security
- **Localhost Only**: No network exposure by default
- **Secret Management**: All secrets in `.env` files (never committed)
- **Input Validation**: All MCP tool inputs validated with Zod schemas
- **GitHub PAT**: Secure private repository access
- **No Credential Logging**: API keys and tokens never logged or exposed in errors
- **Bearer Token Auth**: Scoped tokens with configurable expiration
- **Rate Limiting**: Configurable per-minute/per-hour request limits
### Data Privacy
**Local Processing by Default**: Personal Knowledge MCP processes all data locally using Transformers.js embeddings. No external API calls are required for basic functionality.
**Optional OpenAI Usage**: When using OpenAI embeddings:
- Code snippets are sent to OpenAI API for embedding generation
- The service sets `X-OpenAI-Data-Usage: off` header to opt out of training
- For sensitive code, use local providers (Transformers.js or Ollama)
**No Telemetry**: The application does not collect usage telemetry. ChromaDB telemetry is explicitly disabled in the default configuration.
### ChromaDB Authentication
ChromaDB supports optional token-based authentication to secure the vector database from unauthorized access.
#### Enabling Authentication
1. **Generate a secure token**:
```bash
openssl rand -hex 32
```
2. **Configure the token** in your `.env` file:
```bash
CHROMADB_AUTH_TOKEN=your-generated-token-here
```
3. **Restart the services**:
```bash
docker compose down
docker compose --profile default up -d
```
## Contributing
We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:
- Setting up your development environment
- Code standards and conventions
- Testing requirements
- Pull request process
**Quick Start for Contributors**:
```bash
git clone https://github.com/YOUR_USERNAME/PersonalKnowledgeMCP.git
cd PersonalKnowledgeMCP
bun install
cp .env.example .env
# Edit .env with your API keys
docker compose --profile default up -d
bun test --coverage
```
Development workflow:
- Follow guidelines in [.claude/CLAUDE.md](.claude/CLAUDE.md)
- Work in feature branches (`feature/`, `fix/`, `docs/`)
- Create PRs for all changes
- Ensure tests pass and coverage >= 90%
- Pre-commit hooks will auto-format and lint your code
## Code Statistics
Generated with [cloc](https://github.com/AlDanial/cloc) (tracked files only, via `git ls-files`):
| Language | Files | Blank | Comment | Code |
|:---------|------:|------:|--------:|-----:|
| TypeScript | 548 | 28,488 | 49,994 | 131,397 |
| Markdown | 83 | 10,561 | 9 | 33,137 |
| YAML | 68 | 332 | 597 | 3,185 |
| Bourne Shell | 7 | 471 | 526 | 1,934 |
| PowerShell | 4 | 399 | 281 | 1,232 |
| C# | 6 | 219 | 312 | 1,009 |
| JSON | 8 | 5 | 0 | 743 |
| Go | 1 | 38 | 40 | 154 |
| Rust | 1 | 42 | 47 | 150 |
| Java | 3 | 28 | 58 | 104 |
| SQL | 4 | 77 | 213 | 94 |
| PHP | 1 | 22 | 70 | 87 |
| C++ | 1 | 22 | 15 | 65 |
| Python | 5 | 44 | 59 | 59 |
| Text | 1 | 31 | 0 | 40 |
| C | 1 | 12 | 20 | 38 |
| Dockerfile | 1 | 22 | 38 | 36 |
| Ruby | 1 | 10 | 20 | 35 |
| JavaScript | 2 | 7 | 9 | 33 |
| Visual Studio Solution | 1 | 0 | 1 | 31 |
| TOML | 1 | 12 | 20 | 15 |
| MSBuild script | 1 | 3 | 0 | 14 |
| **SUM** | **749** | **40,845** | **52,329** | **173,592** |
*Generated with `cloc --vcs=git --md .` against `feature/587-incremental-update-reliability` (merge of `main @ 039407f`) on 2026-06-05.*
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
For detailed information about dependency licensing, including graph database options (FalkorDB vs Neo4j), see [Licensing Information](docs/licensing.md).
## Acknowledgments
Built using:
- [Model Context Protocol](https://modelcontextprotocol.io/) by Anthropic
- [Bun](https://bun.sh/) - Fast all-in-one JavaScript runtime
- [ChromaDB](https://www.trychroma.com/) vector database
- [FalkorDB](https://www.falkordb.com/) graph database
- [OpenAI Embeddings API](https://platform.openai.com/docs/guides/embeddings)
- [tree-sitter](https://tree-sitter.github.io/) parser
- [simple-git](https://github.com/steveukx/git-js) for Git operations
- [TypeScript](https://www.typescriptlang.org/)
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo recent community issues