MCP RAG
MCP-RAG is a low-latency retrieval-augmented generation service providing intelligent knowledge management through a modular MCP protocol architecture.
Core Capabilities:
Knowledge Management
Add text content manually (facts, definitions, notes, conversation summaries)
Process 25+ document formats (PDF, DOCX, PPTX, XLSX, TXT, HTML, CSV, JSON, XML, ODT, ODP, ODS, RTF, images with OCR, emails) using advanced semantic chunking with structure preservation, automatic denoising, and metadata extraction
Get comprehensive statistics on document counts, file type distribution, processing methods, and structural complexity
Intelligent Retrieval
Query the knowledge base with semantic search (<100ms latency)
Use Raw mode for direct retrieval or Summary mode for LLM-powered intelligent summarization
Apply filters for targeted search by file type, document structure (tables, titles), or processing method
Performance Optimization
Monitor and optimize vector database performance with health diagnostics
Reindex with optimized profiles (small/medium/large/auto)
Manage embedding cache with performance monitoring (hit rates, memory usage) and cache clearing
Technical Features
Multi-provider support (Doubao, Ollama for LLMs; Doubao API and local sentence-transformers for embeddings)
Web interface for configuration management, document management, and API documentation (Swagger UI)
HTTP API and MCP protocol support
Enables local AI model inference for RAG operations, allowing private document processing and knowledge base interactions without sending data to external services.
Provides RAG (Retrieval-Augmented Generation) capabilities using OpenAI's language models and embedding models for intelligent document processing, semantic search, and knowledge base question answering.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MCP RAG search for quarterly sales projections in the uploaded documents"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP-RAG
✨100% written by AI
A service-oriented RAG service for AI clients, currently focused on FastAPI HTTP services and Streamable HTTP MCP endpoints.
The code currently provides a unified backend shell:
FastAPI HTTP service
Streamable HTTP MCP
Shared runtime, configuration hot-reloading, authentication, rate limiting, quotas, and observability
Retrieval and document management based on a knowledge base registry
Current Capabilities
Document Import: Supports direct text addition, as well as uploading
txt,md,pdf,docxRetrieval: Hybrid search (vector retrieval + keyword retrieval)
Q&A:
/search,/chat, MCPrag_askMulti-Knowledge Base: Supports single knowledge base and
kb_idsmulti-knowledge base aggregated retrieval/dialogueKnowledge Base Scope:
publicandagent_privateTenant Context:
base_collection + user_id + agent_idRuntime Governance: API key, memory rate limiting, upload/indexing quotas, request-level retrieval cache
Provider Governance: Provider budget, circuit breaking, fallback
Observability:
/health,/ready,/metricsFrontend: Built-in single-page management panel
/app
Related MCP server: FastGPT Knowledge Base MCP
Architecture
Main link:
HTTP / MCP
-> app_factory.py
-> http_server.py / mcp_server.py
-> context.py
-> service_facade.py
-> services/
- runtime.py
- indexing_service.py
- retrieval_service.py
- chat_service.py
-> knowledge_bases.py
-> core/indexing/
-> retrieval/Key files:
src/mcp_rag/cli.py: CLI entry point, providesserveandinitsrc/mcp_rag/main.py: HTTP service startup entry pointsrc/mcp_rag/http_server.py: HTTP API, SPA entry point, Streamable HTTP MCP mountingsrc/mcp_rag/mcp_server.py: MCP tool definition andrag_asksrc/mcp_rag/app_factory.py: Unified assembly of app context, runtime, and guardrailssrc/mcp_rag/knowledge_bases.py: Knowledge base registry and default knowledge base resolutionsrc/mcp_rag/config.py: Configuration model, JSON/SQLite persistence, hot-reloading
Environment Requirements
Python
>= 3.13uv
Installation
Install CLI:
uv tool install mcp-ragRun directly after installation:
mcp-rag serveDevelop in the repository:
uv syncIf local embedding is required:
uv sync --extra local-embeddingsBoundary Notes:
Users installing via
uv tool install mcp-ragdo not need Node.js orpnpmpnpmis only used for maintaining frontend builds and is not a service runtime dependency
Startup and Initialization
Start the service:
uv run mcp-rag serveInitialize data directory:
uv run mcp-rag init --data-dir ./dataThe default port is 8060, and the service listens on 0.0.0.0:8060 by default.
Common entry points:
Management Panel:
http://127.0.0.1:8060/appAPI Documentation:
http://127.0.0.1:8060/docsMCP Endpoint:
http://127.0.0.1:8060/mcp
Compatible entry points:
/redirects to/app/docredirects to/docs/documents-pageredirects to/app/documents/config-pageredirects to/app/config
First-time startup behavior:
If
./data/config.jsondoes not exist, default values are used when reading the configurationThe service calls
ensure_config_file()on startup to write the default configuration to disk./data/chromaand related SQLite files in the data directory are created on demand
Frontend and Static Assets
The release package bundles src/mcp_rag/static/ into the wheel / sdist.
This means:
Users running
uv tool install mcp-ragcan access/appdirectlyNo separate frontend build or Node.js is required
Frontend maintainers need to generate the latest static assets before releasing
Frontend source code is in frontend/, and build output goes to src/mcp_rag/static/app.
Typical workflow:
cd frontend
pnpm install
pnpm buildKnowledge Base Model
The current project no longer relies solely on raw collection to organize data, but instead uses a knowledge base registry.
Knowledge base features:
Persistent registry in the SQLite file pointed to by
knowledge_base_db_pathEnsures a public knowledge base exists by default
Ensures the corresponding default
agent_privateknowledge base exists whenuser_id + agent_idis passedAssigns stable internal collection names after creating a new knowledge base, e.g.,
kb_<id>
The interface layer still retains the collection parameter for compatibility with old calling methods. The current actual behavior is:
You can explicitly pass
kb_idYou can continue to pass the old
collectionThe service resolves the request to a specific knowledge base and actual collection name
HTTP Interface
System interfaces:
GET /healthGET /readyGET /metrics
Configuration interfaces:
GET /configPOST /configPOST /config/bulkPOST /config/resetPOST /config/reload
Provider interfaces:
GET /providers/{provider}/models
Knowledge base interfaces:
GET /collectionsGET /knowledge-basesPOST /knowledge-bases
Document interfaces:
POST /add-documentPOST /upload-filesGET /list-documentsDELETE /delete-documentGET /list-filesDELETE /delete-file
Retrieval and Q&A:
GET /searchPOST /chat
MCP debugging interfaces:
GET /debug/mcp/toolsPOST /debug/mcp/call
Points to clarify:
/searchand/chatsupportkb_id/searchand/chatalso supportkb_idsfor multi-knowledge base aggregation/upload-filesusesmultipart/form-data/delete-documentand/delete-filepass deletion parameters via the request body
If security policies are enabled, the API key can be passed in the following ways:
HTTP Header:
x-api-keyHeader:
Authorization: Bearer <token>api_keyin query parameters, JSON body, or form
MCP
The current primary form is Streamable HTTP MCP:
{
"mcpServers": {
"rag": {
"url": "http://127.0.0.1:8060/mcp"
}
}
}Implemented MCP tools:
rag_ask
rag_ask main parameters:
querymode:raworsummarycollectionkb_idscopelimitthresholdtenantuser_id/agent_id_user_id/_agent_idapi_keyrequest_idtrace_id
Example:
{
"name": "rag_ask",
"arguments": {
"query": "FastAPI 是什么",
"kb_id": 1,
"mode": "summary",
"limit": 5
}
}Configuration
Default configuration file:
./data/config.jsonDefault knowledge base database:
./data/knowledge_bases.sqlite3There is an important change in the current configuration:
General runtime configuration is saved in
config.jsonProvider-related configuration is persisted to SQLite instead of being fully written back to
config.json
That is to say, these fields are stored in service_provider_settings in SQLite:
embedding_providerembedding_fallback_providerprovider_configsllm_providerllm_fallback_providerllm_modelllm_base_urlllm_api_key
Other configurations are still saved in config.json, for example:
{
"http_port": 8060,
"chroma_persist_directory": "./data/chroma",
"knowledge_base_db_path": "./data/knowledge_bases.sqlite3",
"enable_llm_summary": false,
"security": {
"enabled": false,
"allow_anonymous": true,
"api_keys": [],
"tenant_api_keys": {}
},
"rate_limit": {
"requests_per_window": 120,
"window_seconds": 60,
"burst": 30
},
"quotas": {
"max_upload_files": 20,
"max_upload_bytes": 52428800,
"max_upload_file_bytes": 10485760,
"max_index_documents": 500,
"max_index_chunks": 2000,
"max_index_chars": 500000
},
"cache": {
"enabled": false,
"max_entries": 256,
"ttl_seconds": 300
},
"provider_budget": {
"enabled": true
}
}Current built-in provider capabilities:
Embedding provider default value is
zhipuLLM provider default value is
doubaoBuilt-in provider configurations include
doubao,zhipu,aliyunqwen/dashscopeare normalized toaliyun/providers/{provider}/modelssupports pulling model lists from OpenAI-compatible model servicesLocal embedding supports
m3e-smallande5-smallLLM additionally supports
ollama
Hot-Reloading and Runtime Refresh
Hot-reloading behavior:
After modification via
/config,/config/bulk,/config/reset,/config/reload, the runtime refreshes immediatelyWhen a request enters, it detects whether the disk configuration has changed via
reload_if_changed()After provider settings or retrieval configurations change, related runtime dependencies are rebuilt and the retrieval cache is cleared
Readiness and Metrics
/healthreturns a health summary, runtime snapshot, andconfig_revision/readyreturns503if bootstrap is incomplete or critical dependencies are not ready/metricsreturns observational metrics aggregated by operation / provider
The current readiness snapshot includes:
document_processorembedding_modelvector_storehybrid_servicellm_modelretrieval_cacheprovider_budget
Testing
Run full tests:
uv run python -m unittest discover -s testsCompilation check:
uv run python -m compileall srcCurrent test coverage:
Configuration defaults, disk reloading, and provider configuration migration
HTTP shell and MCP shell behavior
Request context / tenant resolution
Request-level retrieval cache
Provider budget / fallback
Readiness / health / metrics
Packaging metadata and static assets
License
MIT
Available Tools
10 toolsask_ragA
向 RAG 知识库提问,并根据存储的信息返回答案。 使用场景:
询问特定主题或概念
请求解释或定义
从处理过的文档中获取信息
基于学习的文本或文档获取答案
参数: query: 要向知识库提出的问题或查询。
Inputs: query (required). Returns: result
ask_rag_filteredA
向 RAG 知识库提问,并使用特定过滤器聚焦搜索。 使用场景:
仅搜索 PDF 文档:file_type=".pdf"
查找包含表格的文档:min_tables=1
查找结构良好的文档:min_titles=5
搜索增强处理的文档:processing_method="unstructured_enhanced"
参数: query: 要向知识库提出的问题或查询。 file_type: 按文件类型过滤(例如 ".pdf", ".docx", ".txt")。 min_tables: 文档必须包含的最小表格数量。 min_titles: 文档必须包含的最小标题数量。 processing_method: 按处理方法过滤(例如 "unstructured_enhanced", "markitdown")。
Inputs: query (required), file_type, min_tables, min_titles, +1 more. Returns: result
clear_embedding_cache_toolA
清除嵌入缓存以释放内存和磁盘空间。 使用场景:
在系统内存不足时释放内存
在更改嵌入模型后重置缓存
清除不再需要的旧缓存嵌入
排查与缓存相关的问题
返回: 有关缓存清理操作的确认消息。
Inputs: no named parameters. Returns: result
get_embedding_cache_statsA
获取有关嵌入缓存性能的详细统计信息。 使用场景:
检查缓存命中率以查看系统是否高效工作
监控缓存的内存使用情况
了解嵌入的重用频率
调试性能问题
返回: 有关嵌入缓存性能的详细统计信息。
Inputs: no named parameters. Returns: result
get_knowledge_base_statsA
获取有关知识库的综合统计信息,包括文档类型、处理方法和结构信息。 使用场景:
检查知识库中有多少文档
了解文件类型的分布
查看使用了哪些处理方法
分析存储文档的结构复杂性
返回: 有关知识库内容的详细统计信息。
Inputs: no named parameters. Returns: result
get_vector_database_statsB
获取向量数据库的详细统计信息。 使用场景:
检查数据库状态
分析文档分布
诊断性能问题
规划优化
返回: 向量数据库的详细统计信息。
Inputs: no named parameters. Returns: result
learn_documentA
使用高级非结构化处理技术(包含真正的语义分块)读取和处理文档文件,并将其添加到知识库。 当您想通过智能处理文档文件来训练人工智能时,可以使用此功能。
支持的文件类型:PDF、DOCX、PPTX、XLSX、TXT、HTML、CSV、JSON、XML、ODT、ODP、ODS、RTF、 图像(PNG、JPG、TIFF、带 OCR 的 BMP)、电子邮件(EML、MSG)以及超过 25 种格式。
高级功能:
基于文档结构(标题、章节、列表)的 REAL 语义分块
智能文档结构保存(标题、列表、表格)
自动去噪(页眉、页脚、无关内容)
结构化元数据提取
适用于任何文档类型的强大回退系统
通过语义边界增强上下文保存
使用示例:
处理布局复杂的研究论文或文章
从包含表格和列表的报告或手册中添加内容
从带格式的电子表格导入数据
将演示文稿转换为可搜索的知识
使用 OCR 处理扫描文档
文档将通过 REAL 语义分块进行智能处理,并与增强的元数据一起存储。
将保存处理后文档的副本以供验证。
参数: file_path:要处理的文档文件的绝对路径或相对路径。
Inputs: file_path (required). Returns: result
learn_textA
向 RAG 知识库添加一段新文本以供将来参考。 使用场景:
添加事实、定义或解释
存储对话中的重要信息
保存研究发现或笔记
添加特定主题的上下文
参数: text: 要学习并存储在知识库中的文本内容。 source_name: 来源的描述性名称(例如 "user_notes", "research_paper", "conversation_summary")。
Inputs: text (required), source_name. Returns: result
optimize_vector_databaseA
优化向量数据库以提高搜索性能。 使用场景:
搜索速度变慢
添加了许多新文档
希望提高系统的整体性能
返回: 有关优化过程的信息。
Inputs: no named parameters. Returns: result
reindex_vector_databaseA
使用优化配置重新索引向量数据库。 使用场景:
更改配置文件
搜索速度非常慢
希望针对特定数据库大小进行优化
存在持续的性能问题
参数: profile: 配置文件('small', 'medium', 'large', 'auto')。 'auto' 会自动检测最佳配置文件
返回: 有关重新索引过程的信息。
Inputs: profile. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
Each tool has a clear, distinct purpose: querying with/without filters, learning from files or text, and various statistics and maintenance operations. There is no functional overlap.
Tool names follow a consistent verb_noun pattern in snake_case, e.g., ask_rag, learn_document, get_knowledge_base_stats. The only deviation is 'clear_embedding_cache_tool' which includes an unnecessary 'tool' suffix.
With 10 tools covering querying, learning, statistics, and maintenance, the set is well-scoped for a RAG knowledge base server. No tool is redundant, and the number is appropriate for the domain.
The tools cover essential operations (add, query, manage, maintain), but lack delete or list/update for documents, which are common for a full lifecycle. The gaps are minor but notable.
Maintenance
Related MCP Connectors
Your private knowledge base: upload documents (.md, .txt, .docx, PDF, images), the platform indexes
Ingest, manage, and retrieve documents for RAG-powered AI applications
Governed, auditable knowledge your team curates for its AI assistants, self-hostable
Convert PDFs, Office docs, websites and audio into AI-ready Markdown, then search and ask your docs.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA document knowledge base system that enables users to upload PDFs and query them semantically through a web interface or via the Model Context Protocol, allowing integration with AI tools like Cursor.42-
- FlicenseNot gradedqualityDmaintenanceIntelligent knowledge base management tool that enables searching, browsing, and analyzing documents across multiple datasets with smart document analysis capabilities.24-
- AlicenseNot gradedqualityDmaintenanceA local knowledge base system based on ChromaDB that supports automatic chunking, vector storage, and efficient similarity retrieval of txt and pdf documents, with MCP protocol support allowing AI assistants to directly access knowledge management functions.MIT
- FlicenseBqualityNot gradedmaintenanceA RAG-based knowledge base system supporting document processing, semantic search, and intelligent Q\&A with multiple AI model integrations.1-