Skip to main content
Glama

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, docx

  • Retrieval: Hybrid search (vector retrieval + keyword retrieval)

  • Q&A: /search, /chat, MCP rag_ask

  • Multi-Knowledge Base: Supports single knowledge base and kb_ids multi-knowledge base aggregated retrieval/dialogue

  • Knowledge Base Scope: public and agent_private

  • Tenant Context: base_collection + user_id + agent_id

  • Runtime Governance: API key, memory rate limiting, upload/indexing quotas, request-level retrieval cache

  • Provider Governance: Provider budget, circuit breaking, fallback

  • Observability: /health, /ready, /metrics

  • Frontend: 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, provides serve and init

  • src/mcp_rag/main.py: HTTP service startup entry point

  • src/mcp_rag/http_server.py: HTTP API, SPA entry point, Streamable HTTP MCP mounting

  • src/mcp_rag/mcp_server.py: MCP tool definition and rag_ask

  • src/mcp_rag/app_factory.py: Unified assembly of app context, runtime, and guardrails

  • src/mcp_rag/knowledge_bases.py: Knowledge base registry and default knowledge base resolution

  • src/mcp_rag/config.py: Configuration model, JSON/SQLite persistence, hot-reloading

Environment Requirements

  • Python >= 3.13

  • uv

Installation

Install CLI:

uv tool install mcp-rag

Run directly after installation:

mcp-rag serve

Develop in the repository:

uv sync

If local embedding is required:

uv sync --extra local-embeddings

Boundary Notes:

  • Users installing via uv tool install mcp-rag do not need Node.js or pnpm

  • pnpm is only used for maintaining frontend builds and is not a service runtime dependency

Startup and Initialization

Start the service:

uv run mcp-rag serve

Initialize data directory:

uv run mcp-rag init --data-dir ./data

The 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/app

  • API Documentation: http://127.0.0.1:8060/docs

  • MCP Endpoint: http://127.0.0.1:8060/mcp

Compatible entry points:

  • / redirects to /app

  • /doc redirects to /docs

  • /documents-page redirects to /app/documents

  • /config-page redirects to /app/config

First-time startup behavior:

  • If ./data/config.json does not exist, default values are used when reading the configuration

  • The service calls ensure_config_file() on startup to write the default configuration to disk

  • ./data/chroma and 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-rag can access /app directly

  • No 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 build

Knowledge 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_path

  • Ensures a public knowledge base exists by default

  • Ensures the corresponding default agent_private knowledge base exists when user_id + agent_id is passed

  • Assigns 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_id

  • You can continue to pass the old collection

  • The service resolves the request to a specific knowledge base and actual collection name

HTTP Interface

System interfaces:

  • GET /health

  • GET /ready

  • GET /metrics

Configuration interfaces:

  • GET /config

  • POST /config

  • POST /config/bulk

  • POST /config/reset

  • POST /config/reload

Provider interfaces:

  • GET /providers/{provider}/models

Knowledge base interfaces:

  • GET /collections

  • GET /knowledge-bases

  • POST /knowledge-bases

Document interfaces:

  • POST /add-document

  • POST /upload-files

  • GET /list-documents

  • DELETE /delete-document

  • GET /list-files

  • DELETE /delete-file

Retrieval and Q&A:

  • GET /search

  • POST /chat

MCP debugging interfaces:

  • GET /debug/mcp/tools

  • POST /debug/mcp/call

Points to clarify:

  • /search and /chat support kb_id

  • /search and /chat also support kb_ids for multi-knowledge base aggregation

  • /upload-files uses multipart/form-data

  • /delete-document and /delete-file pass 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-key

  • Header: Authorization: Bearer <token>

  • api_key in 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:

  • query

  • mode: raw or summary

  • collection

  • kb_id

  • scope

  • limit

  • threshold

  • tenant

  • user_id / agent_id

  • _user_id / _agent_id

  • api_key

  • request_id

  • trace_id

Example:

{
  "name": "rag_ask",
  "arguments": {
    "query": "FastAPI 是什么",
    "kb_id": 1,
    "mode": "summary",
    "limit": 5
  }
}

Configuration

Default configuration file:

./data/config.json

Default knowledge base database:

./data/knowledge_bases.sqlite3

There is an important change in the current configuration:

  • General runtime configuration is saved in config.json

  • Provider-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_provider

  • embedding_fallback_provider

  • provider_configs

  • llm_provider

  • llm_fallback_provider

  • llm_model

  • llm_base_url

  • llm_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 zhipu

  • LLM provider default value is doubao

  • Built-in provider configurations include doubao, zhipu, aliyun

  • qwen / dashscope are normalized to aliyun

  • /providers/{provider}/models supports pulling model lists from OpenAI-compatible model services

  • Local embedding supports m3e-small and e5-small

  • LLM additionally supports ollama

Hot-Reloading and Runtime Refresh

Hot-reloading behavior:

  • After modification via /config, /config/bulk, /config/reset, /config/reload, the runtime refreshes immediately

  • When 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

  • /health returns a health summary, runtime snapshot, and config_revision

  • /ready returns 503 if bootstrap is incomplete or critical dependencies are not ready

  • /metrics returns observational metrics aggregated by operation / provider

The current readiness snapshot includes:

  • document_processor

  • embedding_model

  • vector_store

  • hybrid_service

  • llm_model

  • retrieval_cache

  • provider_budget

Testing

Run full tests:

uv run python -m unittest discover -s tests

Compilation check:

uv run python -m compileall src

Current 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 tools
ask_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

    A3.9/5.0

    Scored across 10 tools

    Disambiguation5/5

    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.

    Naming Consistency4/5

    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.

    Tool Count5/5

    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.

    Completeness3/5

    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

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Intelligent knowledge base management tool that enables searching, browsing, and analyzing documents across multiple datasets with smart document analysis capabilities.
      24
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      A 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
    • F
      license
      B
      quality
      Not graded
      maintenance
      A RAG-based knowledge base system supporting document processing, semantic search, and intelligent Q\&A with multiple AI model integrations.
      1
      -