Skip to main content
Glama
rag-mcp-server

rag-mcp-server

by supu02
README.md
# rag-mcp-server

A TypeScript [MCP](https://modelcontextprotocol.io) server that puts an existing bilingual
(French/English) RAG assistant, [fr-en-rag-assistant](https://github.com/supu02/fr-en-rag-assistant),
behind the Model Context Protocol. Any MCP client (Claude Desktop, Cursor, MCP Inspector, a
company's own agent) can then search official French renting and work rules and do exact
deadline maths, with no new glue code.

> Status: all three parts built (MCP server, traced agent with eval gate, React run viewer). Measured numbers are added below as they come in.

## Measured so far

24 November 2026, commit `2b83c4c`, Python service in Docker on a MacBook (Apple Silicon), local network only.
The 90 answerable questions of the Python repo's eval set (45 French, 45 English), `method=auto`, `k=10`.

| Path | hit@5 FR | hit@5 EN | hit@5 all |
|---|---|---|---|
| MCP `search_documents` (stdio) | 45/45 | 31/45 | 76/90 |
| Direct HTTP `POST /search` | 45/45 | 31/45 | 76/90 |

- The top-10 page list was identical on both paths for all 90 questions, so the MCP layer changes no result.
  The figures match the Python repo's own retrieval eval (`auto`: 100% FR, 69% EN).
- Latency per `search_documents` call, measured in the client (n=90, warm): p50 63 ms, p95 118 ms.
  Direct HTTP in a separate pass: p50 67 ms, p95 131 ms. The passes ran one after the other, so the
  gap is run-to-run noise, not a speed-up; MCP over stdio adds no measurable overhead at this scale.
- Retrieval only: no LLM was called, so there is no answer accuracy or cost figure yet.

**The CI gate catches a regression.** Switching retrieval to keyword-only (`--method lexical`)
dropped hit@5 to 26/45 (FR) and 9/45 (EN) and the gate exited with code 1; the normal run passed again
right after (24 Nov 2026, commit `de8aa25`, same Mac).

**First agent run, local model (free).** `qwen3:8b` through Ollama on an Apple M4 Pro (24 GB), all
100 questions, commit `de8aa25`, 24 Nov 2026. A weak baseline that showed two agent bugs, fixed in the
next commit; it is kept here because the numbers are real:

| Check (code only, no judge) | Result |
|---|---|
| Gold page retrieved by the agent's own searches (answerable) | 63/90 |
| Cites a gold page (answerable) | 62/90 (FR 34/45, EN 28/45) |
| Answer contains every number of the reference | 24/60 |
| Answer in the question's language | 99/100 |
| Out-of-scope questions declined | 3/10 |
| Date questions where `add_to_date` was called | 3/16 |
| Latency per MCP tool call (n=101) | p50 106 ms, p95 204 ms |
| Latency per model call (n=201) | p50 8.95 s, p95 20.2 s |
| Cost | 0 (local model); 205,866 input and 71,015 output tokens |

What the traces showed: the model asked `search_documents` for only 1 or 2 results in 86 of 96
searches, so it often missed the page that the default 5 results contain (76/90 in the gate); and 5
answers cited pages that were never retrieved, two of them the example ids written in the prompt.
Fixes: the agent no longer lets the model set `k` or `method`, the prompt has no example ids, and the
eval now counts citations of pages that were not retrieved. These figures are from before the fixes.

**After the fixes, same model and machine** (commit `5388eac`, 24 Nov 2026). 3 of 100 questions hit
the 120 s model timeout (t21-fr, t22-fr, t28-en), so rates are over 97 answers (87 answerable):

| Check | Before fixes (100) | After fixes (97) |
|---|---|---|
| Gold page retrieved by the agent's searches (answerable) | 63/90 | 73/87 |
| Cites a gold page (answerable) | 62/90 | 66/87 |
| Cites a page it never retrieved | 5 answers (counted by hand) | 0/97 |
| Answer contains every number of the reference | 24/60 | 28/58 |
| Answerable question answered without a citation | 2/90 | 8/87 |
| Date questions where `add_to_date` was called | 3/16 | 2/16 |
| Latency per MCP tool call | p50 106 ms, p95 204 ms | p50 148 ms, p95 301 ms |

On the same 87 answerable questions, a gold page was cited 66 times after vs 59 before (17 gained,
10 lost): one run each, so a possible improvement, not a proven one. The small local model rarely
calls the date tool. The refusal checks ported from the Python repo match only some phrasings: by
reading the answers, 9 of 10 out-of-scope answers decline (the code counts 1) and 5 answerable
answers abstain (the code counts 0), so those two code checks are not reported here until they are fixed.
The model timeout is now 300 s (`OLLAMA_TIMEOUT_MS`).

**First Bedrock run** (`mistral.ministral-3-14b-instruct`, eu-west-1, commit `85addf4`, 24 Nov 2026).
All 100 questions, 0 errors. Citations re-scored with the fixed parser (grouped ids such as
`[F1168, F32360]`) by `src/eval/rescore.ts`, from the saved answers, with no new model call; raw
answers and both summaries are in [`results/bedrock-run1/`](results/bedrock-run1).

| Check | Result |
|---|---|
| Gold page retrieved by the agent's searches (answerable) | 87/90 |
| Cites a gold page (answerable) | 79/90 (FR 42/45, EN 37/45); 65/90 before the parser fix |
| Cites a page it never retrieved (bracketed ids) | 0/100 |
| Answer contains every number of the reference | 36/60 |
| Answer in the question's language | 94/100 |
| Date questions where `add_to_date` was called | 6/16 |
| Runs that hit the 6-step limit without an answer | 9/100 (4 answerable, 5 out of scope) |
| Out-of-scope questions declined | 5/10 (the other 5 hit the step limit) |
| Estimated cost, list price | 0.1708 USD in total, 0.0017 USD per question (698,815 input, 12,665 output tokens) |
| Latency per MCP tool call (n=191) | p50 61 ms, p95 77 ms |
| Latency per model call (n=282) | p50 501 ms, p95 1,175 ms |
| Whole answer (n=100) | p50 1.5 s, p95 3.5 s |

The 9 step-limit runs cost 0.0545 USD, 32% of the run. The next commit asks the model to answer on its
last allowed step; a second run measures that change.

**Second Bedrock run, current code** (commit `05abb55`, 24 Nov 2026). Same model, questions and Mac.
All 100 questions, 0 errors (raw answers in [`results/bedrock-run2/`](results/bedrock-run2)). These are the headline numbers. One run each, so differences of a few
questions between the runs are within noise.

| Check | Run 1 (re-scored) | Run 2 |
|---|---|---|
| Gold page retrieved by the agent's searches (answerable) | 87/90 | 85/90 |
| Cites a gold page (answerable) | 79/90 | 78/90 (FR 39/45, EN 39/45) |
| Cites a page id it never retrieved | 0/100 | 0/100 in brackets; 1 answer (t46-fr) links an unretrieved page |
| Answer contains every number of the reference | 36/60 | 37/60 |
| Answer in the question's language | 94/100 | 96/100 |
| Runs that hit the step limit without an answer | 9/100 | 2/100 |
| Out-of-scope questions declined | 5/10 | 10/10 |
| Answerable questions wrongly declined (code check) | 4/90 | 4/90 |
| Date questions where `add_to_date` was called | 6/16 | 7/16 |
| Date questions with the reference date (read by hand) | not counted | 11/16 (2 wrong, 3 without a date) |
| Estimated cost, list price | 0.1708 USD (0.0017 per question) | 0.1757 USD (0.0018 per question) |
| Latency per MCP tool call | p50 61 ms, p95 77 ms (n=191) | p50 60 ms, p95 75 ms (n=189) |
| Latency per model call | p50 501 ms, p95 1,175 ms | p50 487 ms, p95 1,203 ms |
| Whole answer | p50 1.5 s, p95 3.5 s | p50 1.5 s, p95 3.7 s |

Known weaknesses, from reading the answers: the model does date maths itself on 9 of 16 date questions
(2 of those dates are wrong); 2 runs still reach the step limit, calling a tool after being told to
stop; the citation check reads only bracketed ids, so a link to an unretrieved page (t46-fr) or an id
glued to a word (t04-en) is not caught. The refusal check ported from the Python repo matches the
Bedrock model's wording but missed many of `qwen3:8b`'s.

## Tools

| Tool | What it does | Where it runs |
|---|---|---|
| `search_documents` | Hybrid search (Qdrant dense + BM25) over 362 service-public.gouv.fr pages; returns passages with page title, section, URL and score | Python service, `POST /search` (no LLM call) |
| `add_to_date` | Exact calendar arithmetic (days, weeks, months, years; end-of-month rule) and the weekday | TypeScript, in process |
| `days_between` | Calendar days between two dates | TypeScript, in process |

Inputs are validated with Zod. A bad input or an unavailable service returns a tool error the
model can read (`isError: true`), never a crash.

## Architecture

```mermaid
flowchart LR
    C[MCP client<br/>Claude Desktop, Cursor, Inspector] -- stdio --> S[rag-mcp-server<br/>TypeScript]
    S -- HTTP POST /search --> P[fr-en-rag-assistant<br/>Python, FastAPI]
    P --> Q[(Qdrant + BM25<br/>8,652 chunks)]
    S --> D[Date maths<br/>in process]
```

## Agent, tracing and evaluation

`src/agent/` is a small tool-using agent: the model gets the MCP tools, searches (writing the query in
French itself), calls the date tool when needed and answers with page-id citations such as `[F1168]`.
It works with two models behind one interface:

| `LLM_PROVIDER` | Model | Cost |
|---|---|---|
| `ollama` (default) | any local model with tool calling (`OLLAMA_MODEL`, default `qwen3:8b`) | free |
| `bedrock` | `mistral.ministral-3-14b-instruct` on Amazon Bedrock, as in the Python app | billed to the AWS account (list price 0.24 USD per million tokens) |

Every run is one OpenTelemetry trace: an `agent.run` span with one `chat` span per model call and one
`execute_tool` span per MCP tool call, carrying tokens, estimated cost, arguments and results
(GenAI semantic conventions, `gen_ai.*`). Spans are written to `traces/spans.jsonl`, and also sent to
Langfuse over OTLP when `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set (`LANGFUSE_HOST`
defaults to Langfuse Cloud).

```bash
npm run build
RAG_API_URL=http://localhost:8000 npm run ask -- "How much notice must I give my landlord in a zone tendue?"
```

### Run viewer (React)

`viewer/` is a small React + TypeScript app (Vite) that reads `traces/spans.jsonl` and shows each run
step by step: every model call and tool call on a timeline, with its duration, tokens, estimated cost,
arguments and result. Tool errors are shown in red. No backend or database: the Vite dev server serves
the trace file at `/api/spans`, or you can load a `.jsonl` file from disk.

```bash
cd viewer && npm install
TRACES_FILE=../traces/spans.jsonl npm run dev    # http://localhost:5173
```

### Eval gate (CI, free)

`.github/workflows/eval-gate.yml` starts the Python service (pinned to a commit), runs the 90 answerable
questions through `search_documents` and fails if hit@5 drops below [`eval/thresholds.json`](eval/thresholds.json).
No LLM is called, so it costs nothing and needs no secrets. Locally:

```bash
npm run eval:gate -- --questions ../fr-en-rag-assistant/evaluation/questions.jsonl
```

### Answer evaluation (by hand)

Runs the agent on all 100 questions (90 answerable, 10 out of scope) and scores the answers with
code-only checks ported from the Python repo: cites a gold page, answers in the question's language,
contains the reference's numbers, declines out-of-scope questions, uses the date tool on date questions.
Also reports tokens, cost per question and p50/p95 latency per tool call. Free with Ollama; with Bedrock
it costs money, so it is not run in CI.

```bash
npm run eval:answers -- --questions ../fr-en-rag-assistant/evaluation/questions.jsonl
```

## Run it

Requirements: Node 20+, and the Python service running (locally with Docker is easiest; `/search` needs no AWS account).

```bash
# 1. Start the Python RAG service (in a checkout of fr-en-rag-assistant)
docker build -t fr-en-rag-assistant . && docker run -p 8000:8000 fr-en-rag-assistant

# 2. Build and try this server
npm install
npm run build
npm test                         # unit + protocol tests, no network
RAG_API_URL=http://localhost:8000 npx tsx scripts/smoke.ts   # end-to-end against the real service
npm run inspect                  # opens MCP Inspector in the browser
```

### Use it from Claude Desktop

Add this to `claude_desktop_config.json` (Settings > Developer > Edit Config), with the absolute path to this folder:

```json
{
  "mcpServers": {
    "french-rules": {
      "command": "node",
      "args": ["/absolute/path/to/rag-mcp-server/dist/index.js"],
      "env": { "RAG_API_URL": "http://localhost:8000" }
    }
  }
}
```

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `RAG_API_URL` | `http://localhost:8000` | Base URL of the Python service |
| `RAG_TIMEOUT_MS` | `15000` | Timeout for each search request |
| `LLM_PROVIDER` | `ollama` | `ollama` (free, local) or `bedrock` (paid) |
| `OLLAMA_MODEL`, `OLLAMA_URL` | `qwen3:8b`, `http://localhost:11434` | Local model |
| `ANSWER_MODEL`, `BEDROCK_REGION` | `mistral.ministral-3-14b-instruct`, `eu-west-1` | Bedrock model; credentials from `aws login` |
| `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_HOST` | unset | Optional trace export to Langfuse |

## Design decisions

See [DECISIONS.md](DECISIONS.md).

## How I built this

I built this project in November 2026 with Claude Code as my coding assistant, which is why it
appears as co-author on the commits. The evaluations ran on my laptop, against my own AWS account for
the Bedrock runs, and every design choice is explained in [DECISIONS.md](DECISIONS.md).

TDQS

A3.8/5.0

Scored across 3 tools

Disambiguation5/5

The three tools have clearly distinct purposes: one searches documents, one adds a duration to a date, and one computes the interval between two dates. There is no plausible overlap that would cause an agent to misselect among them.

Naming Consistency3/5

All names use snake_case, but the patterns are mixed: search_documents is verb_noun, add_to_date is verb_preposition_noun, and days_between is a noun phrase. The names remain readable, but the set does not follow a single predictable convention.

Tool Count5/5

Three tools is a well-scoped set for a focused RAG server with date-arithmetic support. Each tool has a clear role and there is no redundant or trivial tool.

Completeness3/5

The core search flow is covered, and basic date arithmetic is supported. However, there is no tool to retrieve a full document/page by URL or list available sources, and date handling lacks business-day or holiday-aware calculations, which are notable gaps for renting and work deadlines.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues