← All posts
How-ToNovember 16, 2026 · 9 min

How to build MCP server for local vector search without cloud costs

You can build an MCP server that runs on your own hardware, connects a local vector database like pgvector or chromadb to an LLM, and keeps all data on-premise. Start with the Model Context Protocol specification, write a gRPC or HTTP server in Python using LangChain to handle vector embeddings, and deploy it in Docker alongside your vector store. Use llama.cpp or Anthropic's Claude locally, or point to OpenAI's API for embeddings only while keeping retrieval private. This approach eliminates cloud storage fees, reduces latency for large document sets, and gives you full control over data residency. The entire stack runs on a single machine or Kubernetes cluster, with pgvector handling SQL-backed vectors and chromadb offering a simpler embedded alternative for smaller workloads.

What you need

To build an MCP server that keeps your data on-premise, you need a local LLM runtime, a vector database, a protocol handler, and orchestration glue. Here's what runs the stack:

ToolPlan/PriceRole
llama.cppFree, open-sourceLocal LLM inference engine; runs quantized models without cloud calls
pgvector (PostgreSQL extension)Free, open-sourceVector storage and similarity search; runs in your own Postgres instance
ChromaDBFree (self-hosted) or check current pricing (cloud)Lightweight vector store alternative; simpler than pgvector for small deployments
LangChainFree, open-sourcePython library to chain LLM calls, vector retrieval, and prompt templates; integrates MCP clients
DockerFree (Community Edition)Container runtime to isolate your MCP server, Postgres, and llama.cpp in reproducible environments
gRPCFree, open-sourceProtocol for MCP server communication; handles request/response between client and your local services
Anthropic Claude (optional) or OpenAI API (optional)Claude: check current pricing; OpenAI: from $0.02/1K tokens (GPT-4 Turbo)Fallback LLM if you want hybrid on-prem + cloud; not required for fully local setup

How it works

  1. Local vector store ingestion. Your documents (PDFs, markdown, code) land in a ChromaDB or pgvector instance running on your machine or private server. LangChain handles the chunking and embedding step - you point it at OpenAI's embedding API or run an open-source model like Ollama locally to avoid cloud calls for every document.
  1. MCP server initialization. You spin up how to build mcp server by writing a Python or TypeScript service that exposes the Model Context Protocol interface. This server listens on a local port (or gRPC for higher throughput) and registers two core tools: vector search and document retrieval. Docker containerizes it so the same config runs anywhere - dev, staging, production.
  1. LLM connection. Anthropic's Claude or OpenAI's GPT connects to your MCP server as a tool. The LLM sees "search_documents" and "fetch_context" as callable functions. When Claude needs grounding, it calls your server; your server queries ChromaDB or pgvector and returns ranked results.
  1. Query execution. User asks a question. Claude receives it, decides it needs context, calls your MCP server's search tool with the query. pgvector or ChromaDB returns the top-k vectors and their source documents in milliseconds.
  1. Response generation. Claude augments its response with the retrieved context and streams the answer back. No data leaves your infrastructure; no per-token embedding fees to OpenAI or Anthropic for retrieval.
  1. Logging and refresh. Your MCP server logs all queries and context hits to a local database. You re-embed new documents on a schedule using llama.cpp or Ollama - no external API calls required.

How to build it

  1. Set up a local vector database. Choose either ChromaDB (lightweight, file-based, no external dependencies) or pgvector (PostgreSQL extension, better for production scale). For this guide, use ChromaDB. Install it in a Python virtual environment:
bash
 python3 -m venv mcp_env
 source mcp_env/bin/activate
 pip install chromadb langchain langchain-community langchain-openai
 

ChromaDB runs in-process by default; no separate server needed. If you choose pgvector, install PostgreSQL 12+, then CREATE EXTENSION vector; in your database.

  1. Ingest your documents into the vector store. Use LangChain to load, chunk, and embed documents locally. Create a Python script ingest.py:
python
 from langchain.document_loaders import DirectoryLoader, TextLoader
 from langchain.text_splitter import RecursiveCharacterTextSplitter
 from langchain.embeddings.openai import OpenAIEmbeddings
 from langchain.vectorstores import Chroma
 
 loader = DirectoryLoader('./documents', glob='**/*.txt', loader_cls=TextLoader)
 docs = loader.load()
 splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
 chunks = splitter.split_documents(docs)
 
 embeddings = OpenAIEmbeddings(model='text-embedding-3-small')
 vectorstore = Chroma.from_documents(chunks, embeddings, persist_directory='./chroma_db')
 print(f"Ingested {len(chunks)} chunks into ChromaDB")
 

Run python ingest.py. This creates a local ./chroma_db directory with your embeddings. If you want to avoid OpenAI API calls, replace OpenAIEmbeddings with HuggingFaceEmbeddings (free, runs locally) or use llama.cpp with a quantized embedding model.

  1. Build the MCP server skeleton. The Model Context Protocol is a JSON-RPC 2.0 interface. Create mcp_server.py to expose your vector store as an MCP resource:
python
 import json
 import sys
 from langchain.vectorstores import Chroma
 from langchain.embeddings.openai import OpenAIEmbeddings
 
 class MCPVectorServer:
 def __init__(self):
 self.embeddings = OpenAIEmbeddings(model='text-embedding-3-small')
 self.vectorstore = Chroma(persist_directory='./chroma_db', embedding_function=self.embeddings)
 
 def query(self, text: str, k: int = 5):
 results = self.vectorstore.similarity_search(text, k=k)
 return [{"content": doc.page_content, "metadata": doc.metadata} for doc in results]
 
 def handle_request(self, request):
 method = request.get('method')
 params = request.get('params', {})
 
 if method == 'resources/list':
 return {"resources": [{"uri": "vector://store", "name": "Local Vector Store"}]}
 elif method == 'resources/read':
 return {"contents": [{"uri": "vector://store", "mimeType": "application/json", "text": json.dumps({"status": "ready"})}]}
 elif method == 'tools/call':
 tool_name = params.get('name')
 if tool_name == 'search':
 results = self.query(params.get('arguments', {}).get('query', ''), k=params.get('arguments', {}).get('k', 5))
 return {"content": [{"type": "text", "text": json.dumps(results)}]}
 return {"error": "Unknown method"}
 
 server = MCPVectorServer()
 while True:
 line = sys.stdin.readline()
 if not line:
 break
 request = json.loads(line)
 response = server.handle_request(request)
 print(json.dumps(response))
 sys.stdout.flush()
 

This server reads JSON-RPC requests from stdin and writes responses to stdout, making it compatible with MCP clients.

  1. Wrap the server in a Docker container (optional but recommended for isolation and reproducibility):
dockerfile
 FROM python:3.11-slim
 WORKDIR /app
 COPY requirements.txt .
 RUN pip install -r requirements.txt
 COPY mcp_server.py ingest.py ./
 COPY documents ./documents
 RUN python ingest.py
 ENTRYPOINT ["python", "mcp_server.py"]
 

Build: docker build -t mcp-vector-server .

5. Connect the MCP server to an LLM client. If using Anthropic Claude, configure your MCP client to call the server as a subprocess or gRPC endpoint. If using OpenAI, you'll bridge via LangChain's tool-calling layer. Create client.py: ```python import subprocess import json from langchain.chat_models import ChatOpenAI from langchain.agents import AgentExecutor, create_openai_tools_agent from langchain.prompts import ChatPromptTemplate def call_mcp_server(query: str): request = {"method": "tools/call", "params": {"name": "search", "arguments": {"query": query, "k": 5}}} proc = subprocess.Popen(['python', 'mcp_server.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) proc.stdin.write(json.dumps(request) + '\n') proc.stdin.flush() response = json.loads(proc.stdout.readline()) proc.terminate() return response llm = ChatOpenAI(model='gpt-4o', temperature=0) prompt = ChatPromptTemplate

What it costs to run

Component100 uses/mo1,000 uses/mo10,000 uses/mo
Self-hosted vector DB (pgvector on Docker)$0$0$20-50 (compute)
LLM inference (llama.cpp local)$0$0$0
LLM inference (Anthropic Claude API)$2-5$20-50$200-500
LLM inference (OpenAI GPT-4 API)$3-8$30-80$300-800
gRPC + MCP server hosting (Docker on VPS)$5-15$5-15$30-100
Total (self-hosted + local LLM)$5-15$5-15$50-150
Total (self-hosted + Claude API)$7-20$25-65$230-650

Assumptions: Vector storage via pgvector scales with data size, not queries (assume 10GB dataset, $0.10/GB/mo on commodity hardware). Local llama.cpp inference costs only compute (no API calls). API costs assume 2K tokens average per use; Claude pricing from Anthropic's published rates; OpenAI at standard tier. gRPC server runs on a $5-15 VPS (Hetzner, DigitalOcean); check current pricing for your region and model tier.

Where this breaks

Vector embedding drift across model versions. Your pgvector or chromadb store was built with OpenAI's text-embedding-3-small, but you later switch to Anthropic's embeddings or llama.cpp's local model for cost reasons - queries now return irrelevant chunks because the embedding space changed. Rebuild your entire vector store with the new embedding model, or maintain a versioned index for each model and route queries to the matching index; store the embedding model name as metadata in every document chunk.

gRPC connection timeouts under load. Your MCP server handles 10 concurrent requests fine in testing, but production traffic causes gRPC connections to hang or reset, leaving the LLM waiting indefinitely for vector search results. Increase the gRPC keepalive interval (set grpc.keepalive_time_ms to 10000 and grpc.keepalive_timeout_ms to 5000 in your server config), add connection pooling, and wrap all vector database calls in a timeout context (e.g., 5-second hard limit) that returns a fallback response if the store doesn't answer in time.

Out-of-memory crashes on large vector batches. You're indexing 500,000 documents into chromadb or pgvector in a single batch, and the Docker container OOM-kills the process halfway through. Split ingestion into chunks of 5,000-10,000 documents, commit after each batch, and set explicit memory limits in your Docker compose file (memory: 4g) so you catch the constraint before production.

Stale embeddings in production while code deploys. You push a new version of your MCP server that changes how text is chunked or preprocessed, but the old vectors in pgvector still exist - queries hit both old and new embeddings, causing inconsistent results. Tag every vector with an ingestion timestamp and schema version; on deploy, either re-embed everything or route queries only to vectors matching the current schema version until migration is complete.

Can I run an MCP server on-premise without touching the cloud?

Yes. Deploy the MCP server and vector database (pgvector, chromadb, or llama.cpp) on your own hardware or private cloud, then connect your local LLM via gRPC or HTTP. Data never leaves your infrastructure, and you avoid per-token fees from OpenAI or Anthropic - you only pay for compute resources you own.

What's the difference between building an MCP server and just using LangChain directly?

LangChain is a framework for chaining LLM calls; an MCP server is a standardized protocol that lets any client (Claude, custom apps, other tools) talk to your context sources without rewriting integration code. If you build how to build mcp server properly, you get a reusable, vendor-agnostic interface that works across multiple LLMs and applications.

Do I need Docker to deploy an MCP server?

No, but Docker makes it portable and reproducible. You can run the server directly on Linux, macOS, or Windows if you install dependencies (Python, pgvector, chromadb), but containerizing with Docker eliminates "works on my machine" problems and simplifies deployment to production or a remote server.

Can an MCP server talk to both local LLMs like Llama and cloud models like OpenAI?

Yes. The MCP server is agnostic about which LLM consumes the context it serves. Your server retrieves documents from pgvector or chromadb and returns them over gRPC; the client (your application, Claude, or a local llama.cpp instance) decides whether to send that context to OpenAI, Anthropic, or a self-hosted model.

For a deeper technical reference, see OpenAI's docs.

Get the full toolkit

Grab the free guide with the node-by-node build for all 10 automations.

By subscribing, you agree to receive this guide plus occasional AI Automation Blueprint educational and product emails. Unsubscribe anytime. Privacy policy.