Cybersecurity

The Problem: AI Without Context

Python Docker Kubernetes LLMs RAG MCP AI Agents Authentication Cloud REST API Databases Statistics Embeddings Vector Search Semantic Search Passwords Hashing HTTPS
1,089 words Includes Code
🎯 Key Takeaway: RAG retrieves relevant knowledge from your documents. MCP connects AI agents to tools and data sources. Together, they give AI agents the ability to both search your private knowledge and take actionsβ€”without sending data to external APIs.
MCP and RAG pipeline showing documents, embeddings, vector store, MCP, agent, and LLM
The complete flow: Documents β†’ Embeddings β†’ Vector Store β†’ MCP β†’ Agent β†’ LLM.

The Problem: AI Without Context

By default, AI models don't know about your private data. Ask Claude about your company's API documentation, and it will say it doesn't have that information.

The solution: give AI access to your knowledge through two complementary approaches:

  • RAG β€” Retrieves relevant documents from your vector store
  • MCP β€” Connects agents to tools and data sources

How RAG Works

RAG (Retrieval-Augmented Generation) follows this flow:

User Question: "How do I reset my password?"

1. Question β†’ Embedding (vector)
2. Vector Store β†’ Similarity search
3. Find relevant chunks: "Password Reset Guide"
4. Chunks β†’ Context window
5. LLM generates answer using context

RAG strengths:

  • Excellent for Q&A over documents
  • Uses vector similarity for semantic search
  • Provides grounded answers with sources
  • Keeps data local (no cloud APIs needed)

RAG limitations:

  • Read-only: retrieves but doesn't act
  • No tool execution
  • Fixed to document retrieval
  • No standard protocol for other data sources

How MCP Works

MCP (Model Context Protocol) connects agents to tools:

User Request: "Search my docs for API info"

1. Agent receives request
2. MCP Client discovers available tools
3. Agent calls: search_docs("API")
4. MCP Server executes tool
5. Returns results to agent
6. Agent processes and responds

MCP strengths:

  • Standard protocol for tool integration
  • Auto-discovery of available tools
  • Supports read and write operations
  • Works with any data source

MCP limitations:

  • Tools must be explicitly defined
  • No built-in semantic search
  • Requires server implementation
  • Doesn't natively handle embeddings

The Complement: MCP + RAG

Architecture showing MCP and RAG working together with agent orchestrating both paths
MCP and RAG complement each other: RAG for retrieval, MCP for tools.
Aspect πŸ“š RAG πŸ”§ MCP πŸ”— MCP + RAG
Purpose Retrieve knowledge Connect to tools Retrieve + Act
Input Question Request Question + Intent
Process Vector search Tool execution Search + Execute
Output Relevant context Tool results Context + Actions
Use Case Q&A over documents Tool integration Intelligent agents

Practical Example: MCP + RAG Server

Here's a Python MCP server that combines document retrieval (RAG) with tool access:

"""MCP Server with RAG-capable document search."""

import json
from pathlib import Path
from mcp.server import MCPServer

mcp = MCPServer("Knowledge Base Server")

# ── Configuration ──────────────────────────────────────────
DOCS_DIR = Path("./knowledge_base").resolve()
DOCS_DIR.mkdir(exist_ok=True)


# ── Simple in-memory vector store (for demo) ──────────────
documents = []
vectors = []

def simple_embed(text: str) -> list[float]:
    """Simple keyword-based embedding (use real model in production)."""
    words = text.lower().split()
    # Create a simple frequency vector
    vocab = ["api", "password", "reset", "login", "error", "database",
             "security", "deploy", "test", "install"]
    return [words.count(w) for w in vocab]


def add_document(path: str, content: str):
    """Add a document to the vector store."""
    doc = {"path": path, "content": content, "chunks": []}
    # Split into chunks
    paragraphs = content.split("\n\n")
    for i, para in enumerate(paragraphs):
        if para.strip():
            chunk = {"text": para.strip(), "index": i}
            doc["chunks"].append(chunk)
            vectors.append({
                "doc_path": path,
                "chunk_index": i,
                "vector": simple_embed(para),
                "text": para.strip()
            })
    documents.append(doc)


# ── MCP Tools ──────────────────────────────────────────────

@mcp.tool()
def search_knowledge(query: str, top_k: int = 3) -> str:
    """
    Search the knowledge base using semantic similarity.

    Args:
        query: Search query
        top_k: Number of results to return

    Returns:
        Relevant document chunks
    """
    if not vectors:
        return "Knowledge base is empty. Add documents first."

    query_vector = simple_embed(query)

    # Calculate similarity (cosine-like)
    scored = []
    for v in vectors:
        score = sum(a * b for a, b in zip(query_vector, v["vector"]))
        total = sum(x * x for x in v["vector"]) ** 0.5
        query_total = sum(x * x for x in query_vector) ** 0.5
        if total > 0 and query_total > 0:
            score = score / (total * query_total)
        scored.append((score, v))

    # Sort by score
    scored.sort(key=lambda x: x[0], reverse=True)

    # Return top results
    results = []
    for score, v in scored[:top_k]:
        results.append(f"[Score: {score:.2f}] {v['doc_path']}:\n{v['text'][:200]}")

    return "\n\n".join(results) if results else "No relevant documents found."


@mcp.tool()
def add_to_knowledge_base(file_path: str, content: str) -> str:
    """
    Add a document to the knowledge base.

    Args:
        file_path: Path/name for the document
        content: Document content

    Returns:
        Confirmation message
    """
    add_document(file_path, content)
    return f"Added '{file_path}' with {content.count(chr(10)) + 1} lines"


@mcp.tool()
def list_documents() -> str:
    """List all documents in the knowledge base."""
    if not documents:
        return "No documents in knowledge base"
    return "\n".join(f"β€’ {doc['path']}" for doc in documents)


@mcp.resource("knowledge://stats")
def get_stats() -> str:
    """Get knowledge base statistics."""
    total_chunks = sum(len(doc["chunks"]) for doc in documents)
    return json.dumps({
        "documents": len(documents),
        "total_chunks": total_chunks,
        "vectors_indexed": len(vectors)
    })


# ── Initialize with sample data ────────────────────────────

sample_docs = {
    "api-guide.md": """# API Guide

Our REST API uses standard HTTP methods.
Authentication uses API keys in the Authorization header.
Rate limit: 100 requests per minute.
Base URL: https://api.example.com/v1""",

    "password-reset.md": """# Password Reset Guide

To reset your password:
1. Go to /forgot-password
2. Enter your email address
3. Check your inbox for reset link
4. Click the link and create new password
5. Password must be 8+ characters""",

    "deployment.md": """# Deployment Guide

Deploy to production:
1. Run tests: pytest
2. Build Docker image: docker build .
3. Push to registry
4. Deploy to Kubernetes cluster
5. Monitor logs for errors"""
}

for path, content in sample_docs.items():
    add_document(path, content)


if __name__ == "__main__":
    print(f"Knowledge base: {len(documents)} documents")
    mcp.run()

When to Use MCP + RAG Together

Scenario Use RAG Use MCP Use Both
Q&A over documents βœ… ⚠️ Overkill βœ… If tools needed
Search + act on results ❌ ❌ βœ…
Tool integration ❌ βœ… ⚠️ If docs needed
Intelligent agent ⚠️ Partial ⚠️ Partial βœ…
Private knowledge access βœ… βœ… βœ…

Key Takeaways

  • RAG retrieves relevant documents; MCP connects to tools
  • Together they enable intelligent agents that search AND act
  • MCP provides the standard protocol for exposing RAG as a tool
  • Keep data localβ€”no need to send private documents to cloud APIs
  • Use MCP servers to expose your vector store to any AI agent
  • The combination powers private AI assistants with real capabilities

Related BestWordz Articles

Related BestWordz Tools

πŸ’¬ Discuss MCP + RAG on BestWordz Community β€” Share your implementations and get feedback.

Try the JSON Formatter

Put what you've learned into practice with this free BestWordz tool.

Open Tool β†’

πŸ’¬ Discuss on BestWordz Community

Join the conversation about Python, Docker, Kubernetes on the BestWordz Community forum.

Visit Forum β†’