Exposing RAG as an MCP Server

Make your retrieval pipeline available to any AI agent through the Model Context Protocol.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 12 · Lesson 8 of 8 · Advanced

Exposing RAG as an MCP Server

Make your retrieval pipeline available to any AI agent through the Model Context Protocol.

The Model Context Protocol (MCP) is an open standard for connecting AI applications to tools and data. If you wrap your retrieval pipeline in an MCP server, any MCP-capable client (Claude Desktop, Claude Code, IDE assistants or your own agents) can search your knowledge base without custom integration code. This lesson builds a small MCP server over the index from earlier lessons.

MCP in one paragraph

An MCP server exposes tools (functions the model can call), resources (data the client can read) and prompts (reusable templates). An MCP client, built into an AI application, discovers them and makes them available to the model. Servers run locally (talking over standard input and output) or remotely (over HTTP). For RAG, the main thing to expose is a search tool.

Build the server

pip install mcp
docs_mcp_server.py
"""An MCP server that exposes the company policy index as tools."""
import json
from pathlib import Path
from mcp.server.fastmcp import FastMCP
from retriever import DenseRetriever          # from the top-k search lesson

BASE = Path(__file__).parent
records = json.loads((BASE / "index" / "chunks.json").read_text(encoding="utf-8"))
retriever = DenseRetriever(records)
by_source: dict[str, list[dict]] = {}
for r in records:
    by_source.setdefault(r["source"], []).append(r)

mcp = FastMCP("zentrix-docs")

@mcp.tool()
def search_docs(query: str, k: int = 5) -> str:
    """Search Zentrix Labs HR, travel, expense and IT policies.

    Returns the most relevant passages with their source file names. Use this before
    answering any question about company policies, and cite the sources.
    """
    hits = retriever.search(query, k=max(1, min(k, 10)))
    return "\n\n".join(f"[{h.id}] (score {h.score:.2f})\n{h.text}" for h in hits) or "No results."

@mcp.tool()
def get_document(source: str) -> str:
    """Return the full text of one policy document by its file name, e.g. 'leave-policy.txt'."""
    parts = by_source.get(source)
    if not parts:
        return f"Unknown document '{source}'. Available: {', '.join(sorted(by_source))}"
    return "\n\n".join(p["text"] for p in parts)

@mcp.resource("docs://index")
def list_documents() -> str:
    """List all documents in the knowledge base."""
    return "\n".join(sorted(by_source))

if __name__ == "__main__":
    mcp.run()          # stdio transport, for local clients

Type hints and docstrings become the tool schemas and descriptions the model sees, so write them as carefully as you would a prompt.

Test it

The MCP Inspector is a browser-based tool for calling a server's tools by hand (it needs Node.js):

npx @modelcontextprotocol/inspector python docs_mcp_server.py

Connect it to clients

Claude Code: register the server from your terminal:

claude mcp add zentrix-docs -- python /full/path/to/docs_mcp_server.py

Claude Desktop: add the server to claude_desktop_config.json (Settings, Developer, Edit Config) and restart the app:

{
  "mcpServers": {
    "zentrix-docs": {
      "command": "python",
      "args": ["C:/projects/rag-tutorial/docs_mcp_server.py"]
    }
  }
}

Ask "What is our policy on working from home?" and the assistant calls search_docs and answers with citations.

Remote servers and the Messages API

To share one server across a team, run it over HTTP with mcp.run(transport="streamable-http") behind authentication. Your own applications can then use it directly from the Claude API through the MCP connector, which needs both the server definition and a matching toolset entry:

import anthropic

client = anthropic.Anthropic()
response = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=4000,
    betas=["mcp-client-2025-11-20"],
    mcp_servers=[{"type": "url", "url": "https://docs-mcp.example.com/mcp", "name": "zentrix-docs"}],
    tools=[{"type": "mcp_toolset", "mcp_server_name": "zentrix-docs"}],
    messages=[{"role": "user", "content": "How many leave days do new employees get?"}],
)
print("".join(b.text for b in response.content if b.type == "text"))

Security checklist

  • Authenticate remote servers and pass the user's identity through, so the server can apply document permissions (see Access Control).
  • Expose read-only tools for knowledge bases. Write actions deserve separate, carefully reviewed servers.
  • Treat retrieved text as untrusted. Documents can contain prompt-injection attempts that the client model will read (see Prompt Injection).
  • Limit output size so a single tool call cannot flood the client's context.

Key takeaways

  • An MCP server makes your RAG pipeline usable by any MCP-capable AI application.
  • FastMCP turns typed, documented Python functions into tools and resources.
  • Run locally over stdio for desktop clients, or over HTTP for shared and API use.
  • Authenticate, keep tools read-only and pass user identity for permission checks.