---
title: "How to Build an MCP Server with RAG"
url: "https://zuey.me/articles/huong-dan-xay-dung-mcp-server-ap-dung-co-che-rag?lang=en"
locale: en
access: free
full_text: true
published_at: "2025-05-16T12:18:42.000Z"
tags: ["MCP", "RAG", "Programming", "AI"]
translations:
  vi: "https://zuey.me/articles/huong-dan-xay-dung-mcp-server-ap-dung-co-che-rag.md?lang=vi"
  zh: "https://zuey.me/articles/huong-dan-xay-dung-mcp-server-ap-dung-co-che-rag.md?lang=zh"
  ko: "https://zuey.me/articles/huong-dan-xay-dung-mcp-server-ap-dung-co-che-rag.md?lang=ko"
  ja: "https://zuey.me/articles/huong-dan-xay-dung-mcp-server-ap-dung-co-che-rag.md?lang=ja"
---
# How to Build an MCP Server with RAG

> Drop in a document or a URL, the AI processes it, stores it in a vector database, then pulls out exactly the right info to answer you. Let's build an MCP server with RAG together – sounds fancy, right? 😎

Hey everyone! Goon here. Today I'll walk you through building a **Model Context Protocol (MCP)** server with **Retrieval Augmented Generation (RAG)** built in – sounds fancy, right? 😎

The goal is a system where you toss in a document or a URL, the AI processes it and stores it in a vector database, and whenever you ask something, it digs out the relevant info and answers like a champ.

I'll build on top of an MCP server boilerplate and borrow ideas from Airweave – a pretty solid tool for preparing data for AI.

> **TIP:** **TL;DR:** The MCP server has 2 tools: `processDocument` (read a file/scrape a URL → chunk → create embeddings → store in Qdrant) and `searchDatabase` (take a question → find relevant text chunks in Qdrant). Stack: MCP server boilerplate + Qdrant + Transformers.js.

### Step 1: Understand RAG and MCP

What is **RAG**? Simply put, it's how an AI looks up information in a data store (a vector database) and then uses that information to answer questions. For example, you ask “How do I make good milk tea?”, the AI finds the related documents in the database and answers based on them.

**MCP**, on the other hand, is a protocol that lets AI call tools or data from a server. Think of it as a “middleman” that connects the AI to external services, like processing documents or searching for information.

In this post, I'll create two tools in the MCP server: one to process documents/URLs, and one to search for answers.

```mermaid
flowchart TD
  D["Document or URL"] -->|"processDocument"| PC["processDocument controller"]
  PC --> DS["documentService: read file, scrape URL, split into chunks"]
  DS --> EM["vectorDbService: create embeddings with all-MiniLM-L6-v2"]
  EM --> Q[("Qdrant")]
  U["User question"] -->|"searchDatabase"| SC["searchDatabase controller"]
  SC --> Q
  Q -->|"relevant text chunks"| AI["AI answers"]
```

*How the RAG-powered MCP server processes data*

### Step 2: Set up the boilerplate

First, clone the boilerplate from GitHub:

```bash
git clone https://github.com/aashari/boilerplate-mcp-server.git
cd boilerplate-mcp-server
npm install
```

Then run the server to check it works:

```bash
npm run dev:server
```

This boilerplate gives you a layered architecture (CLI, tools, controllers, services, utils) that's super easy to extend. If you want a quick check, try the CLI:

```bash
npm run dev:cli -- get-ip-details
```

### Step 3: Install the vector database

I picked **Qdrant** as the vector database because it's what Airweave uses and it's quite powerful. Install Qdrant with Docker:

```bash
docker run -p 6333:6333 qdrant/qdrant
```

Qdrant will run at `http://localhost:6333`. You can use Qdrant Cloud if you like, but running it locally is enough for this post.

### Step 4: Install dependencies

Install the required libraries:

```bash
npm install @qdrant/js-client-rest @xenova/transformers axios cheerio
```

- `@qdrant/js-client-rest`: to talk to Qdrant.
- `@xenova/transformers`: to create embeddings with the `sentence-transformers/all-MiniLM-L6-v2` model.
- `axios` and `cheerio`: to scrape content from URLs.

### Step 5: Create the services

#### 5.1. Vector Database Service

Create `services/vectorDbService.ts` to handle storing and searching embeddings:

```typescript
import { QdrantClient } from '@qdrant/js-client-rest';
import { pipeline } from '@xenova/transformers';

const qdrantClient = new QdrantClient({ url: 'http://localhost:6333' });

let extractor;

async function getExtractor() {
  if (!extractor) {
    extractor = await pipeline('feature-extraction', 'sentence-transformers/all-MiniLM-L6-v2');
  }
  return extractor;
}

export async function storeEmbeddings(chunks: string[]) {
  const extractor = await getExtractor();
  const embeddings = await Promise.all(chunks.map(chunk => extractor(chunk, { pooling: 'mean', normalize: true })));
  const points = chunks.map((chunk, i) => ({
    id: i,
    vector: Array.from(embeddings[i].data),
    payload: { text: chunk }
  }));
  await qdrantClient.upsert('my_collection', { points });
}

export async function searchEmbeddings(query: string, topK: number = 5) {
  const extractor = await getExtractor();
  const queryEmbedding = await extractor(query, { pooling: 'mean', normalize: true });
  const searchResult = await qdrantClient.search('my_collection', {
    vector: Array.from(queryEmbedding.data),
    limit: topK,
    with_payload: true
  });
  return searchResult.map(result => result.payload.text);
}

async function initializeCollection() {
  const collections = await qdrantClient.getCollections();
  if (!collections.collections.find(c => c.name === 'my_collection')) {
    await qdrantClient.createCollection('my_collection', {
      vectors: { size: 384, distance: 'Cosine' }
    });
  }
}

initializeCollection();
```

**What does this file do?** It initializes the Qdrant client, loads the embedding model, stores text chunks in Qdrant as vectors, and searches for the nearest vectors when a question comes in.

#### 5.2. Document Service

Create `services/documentService.ts` to handle documents or URLs:

```typescript
import fs from 'fs';
import path from 'path';
import axios from 'axios';
import cheerio from 'cheerio';

export async function readAttachment(attachmentId: string): Promise<string> {
  const filePath = path.join('/attachments', `${attachmentId}.txt`);
  return fs.promises.readFile(filePath, 'utf-8');
}

export async function scrapeUrl(url: string): Promise<string> {
  const response = await axios.get(url);
  const $ = cheerio.load(response.data);
  const mainContent = $('article').text() || $('main').text() || $('body').text();
  return mainContent;
}

export function processContent(content: string): string[] {
  return content.split('\n').filter(chunk => chunk.trim() !== '');
}
```

This file reads content from an uploaded file (assuming it's stored in `/attachments`) or scrapes content from a URL, then splits the content into small chunks.

### Step 6: Create the controllers

#### 6.1. Process Document Controller

Create `controllers/processDocument.controller.ts`:

```typescript
import { storeEmbeddings } from '../services/vectorDbService';
import { readAttachment, scrapeUrl, processContent } from '../services/documentService';

export async function processDocumentController(params: { type: 'attachment' | 'url', value: string }) {
  let content;
  if (params.type === 'attachment') {
    content = await readAttachment(params.value);
  } else if (params.type === 'url') {
    content = await scrapeUrl(params.value);
  } else {
    throw new Error('Invalid type');
  }
  const chunks = processContent(content);
  await storeEmbeddings(chunks);
  return { status: 'success', message: 'Document processed and stored' };
}
```

This controller handles the logic: it takes an attachment or URL as input, fetches the content, chunks it, creates embeddings, and stores them in Qdrant.

#### 6.2. Search Database Controller

Create `controllers/searchDatabase.controller.ts`:

```typescript
import { searchEmbeddings } from '../services/vectorDbService';

export async function searchDatabaseController(params: { query: string }) {
  const results = await searchEmbeddings(params.query);
  return { results };
}
```

This controller takes a question, searches Qdrant, and returns the relevant text chunks.

### Step 7: Create the tools

#### 7.1. Process Document Tool

Create `tools/processDocument.tool.ts`:

```typescript
import { z } from 'zod';
import { processDocumentController } from '../controllers/processDocument.controller';

export const processDocumentTool = {
  name: 'processDocument',
  description: 'Process a document or URL and store in vector database',
  parameters: z.object({
    type: z.enum(['attachment', 'url']),
    value: z.string(),
  }),
  run: async (params: { type: 'attachment' | 'url', value: string }) => {
    return processDocumentController(params);
  },
};
```

This tool defines the interface the AI calls, taking a type (attachment or URL) and a value (file ID or URL) as input.

#### 7.2. Search Database Tool

Create `tools/searchDatabase.tool.ts`:

```typescript
import { z } from 'zod';
import { searchDatabaseController } from '../controllers/searchDatabase.controller';

export const searchDatabaseTool = {
  name: 'searchDatabase',
  description: 'Search the vector database for relevant information',
  parameters: z.object({
    query: z.string(),
  }),
  run: async (params: { query: string }) => {
    return searchDatabaseController(params);
  },
};
```

This tool takes a question and returns the search results.

### Step 8: Register the tools

In `src/index.ts` or wherever your tools are registered, add the new tools:

```typescript
import { processDocumentTool } from './tools/processDocument.tool';
import { searchDatabaseTool } from './tools/searchDatabase.tool';

const tools = [/* existing tools */, processDocumentTool, searchDatabaseTool];
```

### Step 9: Test and deploy

Restart the server:

```bash
npm run dev:server
```

Test via the CLI or by calling the API to make sure the tools work:

- [ ] Call `processDocument` with a URL or an attachment ID
- [ ] Call `searchDatabase` with a question and check the results

### Practical tips from the trenches

#### Error handling

Make sure you handle error cases like missing files, invalid URLs, or Qdrant not responding.

#### Optimization

The all-MiniLM-L6-v2 model is lightweight, but if you need higher quality you can try other models from Hugging Face – just keep resource usage in mind.

#### Security

If you use Qdrant Cloud, add your API key to the client config. For file uploads, validate format and size carefully.

#### Extending it

You can add features like PDF processing (using the pdf-parse library) or integrate other services via MCP.

### Architecture summary

| Component | Role |
| --- | --- |
| **Services** | Core logic: reading documents, scraping URLs, creating embeddings, talking to Qdrant |
| **Controllers** | Business logic: call services and return results |
| **Tools** | Define the MCP interface the AI calls, using zod to validate input |
| **Vector DB** | Qdrant stores embeddings and supports nearest-vector search |

### Wrapping up

And there you go, you now have an MCP server with RAG, ready to let AI process documents and answer questions! 😎 This system can be extended to integrate with my products like **TopRanking.ai** or **SearchAPI.site**. If you want to experiment, just build it, break it, fix it – that's how I learned from building 15+ SaaS products.

Got questions? Just ask me, or join the Build in Public VN community to chat more! 🚀

### References

[coleam00/mcp-crawl4ai-rag](https://github.com/coleam00/mcp-crawl4ai-rag)

> github.com

- [Boilerplate MCP Server for Building Custom Tools](https://github.com/aashari/boilerplate-mcp-server)
- Airweave AI for Semantic Search and Data Integration
- Qdrant Vector Database Documentation
- Transformers.js for Running ML Models in JavaScript
