Skip to main content
Glama
nailmailster

LightRAG MCP Server

by nailmailster
README.md
# LightRAG MCP Server

Model Context Protocol (MCP) server for the [LightRAG](https://github.com/HKUDS/LightRAG) API — **30 tools** covering queries, document management, knowledge graph operations, and server utilities.

---

## Table of Contents

- [Overview](#overview)
- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [All 30 Tools](#all-30-tools)
- [Transport Modes](#transport-modes)
- [n8n Integration](#n8n-integration)
- [Docker Daemon](#docker-daemon)
- [Workspace Support](#workspace-support)
- [Claude Desktop / Zed](#claude-desktop--zed)
- [Development](#development)
- [Troubleshooting](#troubleshooting)

---

## Overview

This MCP server acts as a bridge between any MCP-compatible AI client (n8n, Claude Desktop, Zed, Cursor, etc.) and a running [LightRAG](https://github.com/HKUDS/LightRAG) server.

```
AI Client (n8n / Claude Desktop / Zed)
        │
        │  MCP protocol (SSE or stdio)
        ▼
┌─────────────────────────┐
│  LightRAG MCP Server    │  ← this project
│  (Node.js + TypeScript) │
└─────────────────────────┘
        │
        │  HTTP REST
        ▼
┌────────────────────────┐
│  LightRAG API          │
│  http://localhost:9621 │
└────────────────────────┘
```

**Key features:**
- **30 tools** covering all major LightRAG API endpoints
- **Two transports**: HTTP+SSE for n8n / remote clients, stdio for local desktop clients
- **Workspace support**: all tools accept an optional `workspace` parameter to target specific knowledge bases
- **Docker daemon**: runs as a background service, survives Ctrl+C and host reboots
- **Graceful shutdown**: handles SIGTERM/SIGINT properly so Docker can stop it cleanly

---

## Prerequisites

| Requirement       | Version | Notes                                                   |
|-------------------|---------|---------------------------------------------------------|
| Node.js           | ≥ 18    | LTS recommended                                         |
| npm               | ≥ 9     | Comes with Node.js                                      |
| LightRAG server   | any     | Must be running on `localhost:9621` (or configured URL) |
| Docker (optional) | ≥ 24    | For daemon mode                                         |

LightRAG must already be running before you start the MCP server. If it's currently running from PowerShell on port 9621, that's perfect — no changes needed.

---

## Quick Start

### 1. Install dependencies

```powershell
# From the devstral-mcp directory
npm install
```

### 2. Build TypeScript

```powershell
npm run build
```

### 3. Configure (optional)

```powershell
# Copy the example config and edit if needed
Copy-Item .env.example .env
# Edit .env — most defaults work out of the box for a local LightRAG install
```

The only value you typically need to change is `LIGHTRAG_BASE_URL` if LightRAG is not on `localhost:9621`.

### 4. Start the server

```powershell
# HTTP+SSE mode (for n8n) — default
npm run start:http

# stdio mode (for Claude Desktop / Zed)
npm run start:stdio
```

You should see:
```
┌──────────────────────────────────────────────────────┐
│         LightRAG MCP Server — Configuration          │
├──────────────────────────────────────────────────────┤
│  LightRAG URL  : http://localhost:9621               │
│  Transport     : http                                │
│  Listen        : 0.0.0.0:3000                        │
│  SSE endpoint  : http://localhost:3000/sse           │
└──────────────────────────────────────────────────────┘
```

### 5. Test connectivity

```powershell
# Check the MCP server itself
Invoke-RestMethod http://localhost:3000/health

# Verify it can reach LightRAG
Invoke-RestMethod http://localhost:3000/
```

---

## Configuration

All settings can be set in `.env` or as environment variables. Environment variables always take priority over `.env`.

| Variable                     | Default                 | Description                                                                        |
|------------------------------|-------------------------|------------------------------------------------------------------------------------|
| `LIGHTRAG_BASE_URL`          | `http://localhost:9621` | LightRAG server URL (no trailing slash)                                            |
| `LIGHTRAG_API_KEY`           | *(empty)*               | API key for LightRAG. Leave empty if auth is disabled (default for local installs) |
| `LIGHTRAG_TIMEOUT`           | `30000`                 | HTTP request timeout in milliseconds                                               |
| `LIGHTRAG_DEFAULT_WORKSPACE` | *(empty)*               | Default workspace. Empty = server default                                          |
| `MCP_TRANSPORT`              | `http`                  | Transport mode: `http` or `stdio`                                                  |
| `MCP_HOST`                   | `0.0.0.0`               | Bind host for HTTP transport                                                       |
| `MCP_PORT`                   | `3000`                  | Port for HTTP+SSE transport                                                        |
| `LOG_LEVEL`                  | `info`                  | Log verbosity: `error`, `warn`, `info`, `debug`                                    |

The transport can also be set via CLI flag, which takes highest priority:

```powershell
node dist/index.js --transport http
node dist/index.js --transport stdio
```

---

## All 30 Tools

### Query Tools (1–3)

| # | Tool name               | Description                                                                             |
|---|-------------------------|-----------------------------------------------------------------------------------------|
| 1 | `lightrag_query`        | Query the knowledge base and get an LLM-generated answer. Supports all retrieval modes. |
| 2 | `lightrag_query_stream` | Same as above but uses the `/query/stream` endpoint (different server code path).       |
| 3 | `lightrag_query_data`   | Returns raw retrieval data (entities, relationships, chunks) without LLM generation.    |

**Query modes** (all query tools accept a `mode` parameter):

| Mode     | Description |
|----------|---------------------------------------------------------------|
| `mix`    | ⭐ Recommended — combines knowledge graph with vector search  |
| `local`  | Focuses on specific entities and their direct relationships   |
| `global` | Analyses broad relationship patterns across the whole graph   |
| `hybrid` | Combines local + global strategies                            |
| `naive`  | Plain vector similarity search, no knowledge graph            |
| `bypass` | Direct LLM call, no retrieval at all                          |

---

### Document Management Tools (4–18)

| #  | Tool name                             | Description                                                       |
|----|---------------------------------------|-------------------------------------------------------------------|
| 4  | `lightrag_insert_text`                | Insert a single text string into the knowledge base               |
| 5  | `lightrag_insert_texts`               | Insert multiple texts in one request (batch)                      |
| 6  | `lightrag_scan_documents`             | Trigger a scan of the server's input directory for new files      |
| 7  | `lightrag_list_documents`             | List all documents grouped by status (up to 1000)                 |
| 8  | `lightrag_get_documents_paginated`    | Paginated document list with filtering and sorting                |
| 9  | `lightrag_get_document_status_counts` | Quick count summary: PROCESSED / PENDING / FAILED / etc.          |
| 10 | `lightrag_get_track_status`           | Check indexing progress using a track_id                          |
| 11 | `lightrag_delete_documents`           | Delete documents by ID (async, with optional file/cache deletion) |
| 12 | `lightrag_delete_entity`              | Remove an entity node from the knowledge graph                    |
| 13 | `lightrag_delete_relation`            | Remove a relationship edge from the knowledge graph               |
| 14 | `lightrag_clear_all_documents`        | ⚠️ Wipe everything — all documents, entities, vectors             |
| 15 | `lightrag_get_pipeline_status`        | Monitor the document processing pipeline (busy/idle, progress)    |
| 16 | `lightrag_cancel_pipeline`            | Request graceful cancellation of the running pipeline             |
| 17 | `lightrag_reprocess_failed`           | Retry documents stuck in FAILED or PENDING state                  |
| 18 | `lightrag_clear_cache`                | Clear LLM response cache (forces fresh extraction on next insert) |

**Typical insert workflow:**
```
lightrag_insert_text → returns track_id
lightrag_get_track_status(track_id) → poll until PROCESSED
lightrag_query → ask questions
```

---

### Graph / Entity / Relation Tools (19–28)

| #  | Tool name                      | Description                                                    |
|----|--------------------------------|----------------------------------------------------------------|
| 19 | `lightrag_get_graph_labels`    | List all entity names in the knowledge graph                   |
| 20 | `lightrag_get_popular_labels`  | Get the most-connected entities (sorted by degree)             |
| 21 | `lightrag_search_labels`       | Fuzzy search for entity names                                  |
| 22 | `lightrag_get_knowledge_graph` | Get a subgraph around a specific entity (nodes + edges)        |
| 23 | `lightrag_check_entity_exists` | Check if an entity with a given name exists                    |
| 24 | `lightrag_create_entity`       | Manually create a new entity node                              |
| 25 | `lightrag_edit_entity`         | Update entity properties, rename, or merge with another entity |
| 26 | `lightrag_create_relation`     | Create a relationship between two existing entities            |
| 27 | `lightrag_edit_relation`       | Update relationship properties                                 |
| 28 | `lightrag_merge_entities`      | Consolidate duplicate entities, transferring all relationships |

---

### Utility Tools (29–30)

| # | Tool name                   | Description                                                               |
|---|-----------------------------|---------------------------------------------------------------------------|
| 29 | `lightrag_health_check`    | Full server health: version, LLM config, storage backends, pipeline state |
| 30 | `lightrag_get_auth_status` | Authentication configuration status                                       |

---

## Transport Modes

### HTTP + SSE (recommended for n8n)

The default mode. Starts an Express server with two endpoints:

| Endpoint    | Method | Purpose                                         |
|-------------|--------|-------------------------------------------------|
| `/sse`      | GET    | MCP client connects here to open an SSE session |
| `/messages` | POST   | MCP client sends tool call requests             |
| `/health`   | GET    | Liveness check (no auth required)               |
| `/`         | GET    | Server info                                     |

```powershell
npm run start:http
# or
npm start  # same thing
```

### stdio (for Claude Desktop, Zed, Cursor)

Used when the MCP client spawns this process as a child and communicates via stdin/stdout.

```powershell
npm run start:stdio
```

---

## n8n Integration

### Step 1: Start the MCP server

```powershell
npm run start:http
# MCP server now listening at http://localhost:3000/sse
```

Or via Docker (see [Docker Daemon](#docker-daemon) section).

### Step 2: Create MCP Client credential in n8n

1. Open n8n → **Settings → Credentials → New Credential**
2. Search for **MCP Client API**
3. Set **SSE URL** to:
   - Local: `http://localhost:3000/sse`
   - Docker (same compose network): `http://lightrag-mcp:3000/sse`
   - Docker (host machine): `http://host.docker.internal:3000/sse`
4. Save the credential

### Step 3: Import the workflow template

1. In n8n, go to **Workflows → Import from file**
2. Select `n8n/lightrag-workflow.json` from this project
3. Open the imported workflow
4. Update the **OpenAI GPT-4o-mini** node with your OpenAI credential
5. Update the **LightRAG MCP Tools** node with the MCP credential you just created
6. Click **Save** and **Activate**

### Step 4: Test

Open the chat in n8n and try:
- *"Is LightRAG running?"* → triggers `lightrag_health_check`
- *"What documents do you know about?"* → triggers `lightrag_get_document_status_counts`
- *"Tell me about [topic]"* → triggers `lightrag_query`

### Network configuration

| Scenario | `LIGHTRAG_BASE_URL` | n8n MCP SSE URL |
|----------|---------------------|-----------------|
| Everything on host machine | `http://localhost:9621` | `http://localhost:3000/sse` |
| MCP in Docker, LightRAG on host | `http://host.docker.internal:9621` | `http://localhost:3000/sse` |
| Everything in Docker (same network) | `http://lightrag:9621` | `http://lightrag-mcp:3000/sse` |

---

## Docker Daemon

Running the MCP server in Docker keeps it alive even after closing the terminal window. It will restart automatically after crashes or host reboots.

### Build and start

```powershell
# From the devstral-mcp directory
docker compose -f docker/docker-compose.yml up -d --build
```

### Common commands

```powershell
# Check status
docker compose -f docker/docker-compose.yml ps

# Follow logs
docker compose -f docker/docker-compose.yml logs -f

# Stop the daemon (Ctrl+C does NOT stop it — this does)
docker compose -f docker/docker-compose.yml down

# Restart without rebuilding
docker compose -f docker/docker-compose.yml restart

# Rebuild after code changes
docker compose -f docker/docker-compose.yml up -d --build
```

### Why it survives Ctrl+C

- `restart: unless-stopped` — Docker automatically restarts the container if it exits for any reason
- `init: true` — Uses tini as PID 1 so Node.js receives SIGTERM properly
- `stop_grace_period: 15s` — Docker waits 15 seconds for graceful shutdown before force-killing
- The Node.js process handles SIGTERM/SIGINT gracefully, closing SSE sessions and the HTTP server

### Environment variables for Docker

Create a `.env` file next to `docker/docker-compose.yml` (or in the project root):

```powershell
# If LightRAG runs on the host machine (not in Docker)
LIGHTRAG_BASE_URL=http://host.docker.internal:9621

# If LightRAG runs in Docker on the same network
# LIGHTRAG_BASE_URL=http://lightrag:9621

MCP_PORT=3000
LOG_LEVEL=info
```

---

## Workspace Support

LightRAG supports multiple isolated knowledge bases called **workspaces**. All 30 tools accept an optional `workspace` parameter.

**How it works:**
- When `workspace` is provided in a tool call, the MCP server sends it as the `LIGHTRAG-WORKSPACE` HTTP header to LightRAG
- LightRAG routes the request to the workspace-specific storage
- Workspace names must contain only letters, digits, and underscores (`[a-zA-Z0-9_]+`)

**Example use cases:**
- `workspace: "python_books"` — knowledge base with Python programming books
- `workspace: "company_docs"` — internal company documentation
- `workspace: "research_papers"` — academic papers collection

**Set a default workspace** so you don't have to pass it every time:

```
# .env
LIGHTRAG_DEFAULT_WORKSPACE=python_books
```

Individual tool calls can still override the default by passing a different `workspace` value.

---

## Claude Desktop / Zed

To use this MCP server with Claude Desktop or Zed, use **stdio** transport.

### Claude Desktop

Add to `%APPDATA%\Claude\claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "lightrag": {
      "command": "node",
      "args": ["C:/path/to/devstral-mcp/dist/index.js", "--transport", "stdio"],
      "env": {
        "LIGHTRAG_BASE_URL": "http://localhost:9621",
        "LIGHTRAG_DEFAULT_WORKSPACE": ""
      }
    }
  }
}
```

### Zed

Add to Zed `settings.json`:

```json
{
  "context_servers": {
    "lightrag-mcp": {
      "command": {
        "path": "node",
        "args": ["C:/path/to/devstral-mcp/dist/index.js", "--transport", "stdio"],
        "env": {
          "LIGHTRAG_BASE_URL": "http://localhost:9621"
        }
      }
    }
  }
}
```

Replace `C:/path/to/devstral-mcp` with the actual absolute path to this project.

---

## Development

```powershell
# Install dependencies
npm install

# Run in development mode with hot reload (HTTP transport)
npm run dev:http

# Run in development mode (stdio transport)
npm run dev:stdio

# Type-check without building
npm run typecheck

# Build for production
npm run build

# Clean build output
npm run clean
```

### Project structure

```
devstral-mcp/
├── src/
│   ├── index.ts           # Entry point — transport selection and startup
│   ├── server.ts          # McpServer factory — registers all 30 tools
│   ├── config.ts          # Typed environment configuration + logger
│   ├── client.ts          # Axios HTTP client for LightRAG API
│   └── tools/
│       ├── query.ts       # Tools 1–3: query, query_stream, query_data
│       ├── documents.ts   # Tools 4–18: insert, scan, list, delete, pipeline
│       └── graph.ts       # Tools 19–30: entities, relations, labels, health
├── docker/
│   ├── Dockerfile         # Multi-stage production build
│   └── docker-compose.yml # Daemon with restart:unless-stopped
├── n8n/
│   └── lightrag-workflow.json  # n8n AI Agent workflow template
├── .env.example           # All configurable environment variables
├── package.json
├── tsconfig.json
└── README.md
```

---

## Troubleshooting

### "Cannot connect to LightRAG at http://localhost:9621"

The LightRAG server is not reachable. Check:
```powershell
# Is LightRAG running?
Invoke-RestMethod http://localhost:9621/health

# Is the URL correct in .env?
Get-Content .env | Select-String LIGHTRAG_BASE_URL
```

If LightRAG is running in Docker and the MCP server is on the host:
```
LIGHTRAG_BASE_URL=http://localhost:9621   # ✅ correct (Docker maps the port)
```

If both are in Docker containers on different compose files:
```
LIGHTRAG_BASE_URL=http://host.docker.internal:9621   # ✅ correct
```

### n8n cannot connect to the MCP server

1. Verify the MCP server is running: `Invoke-RestMethod http://localhost:3000/health`
2. Check the SSE URL in your n8n MCP credential
3. If n8n is in Docker and MCP server is on the host, use `http://host.docker.internal:3000/sse`
4. If both are in Docker on the same network, use `http://lightrag-mcp:3000/sse`

### Tools return "Request timed out"

LightRAG operations (especially document insertion with LLM extraction) can take several minutes.

```
# .env — increase timeout to 5 minutes
LIGHTRAG_TIMEOUT=300000
```

### Documents stuck in PENDING or PROCESSING

```
# Use lightrag_get_pipeline_status to see what's happening
# Then try lightrag_reprocess_failed to retry stuck documents
```

### "Session not found" on POST /messages

The SSE session expired. The MCP client needs to reconnect to `/sse` first. This is handled automatically by most MCP clients.

### TypeScript build errors

```powershell
# Clean and rebuild
npm run clean
npm run build

# Check for type errors
npm run typecheck
```

---

## License

MIT