Metadata-Version: 2.5
Name: agentic-rag-mcp
Version: 0.1.0
Summary: Agentic RAG over your own documents, served as an MCP server, with a measured comparison against single-shot retrieval
Project-URL: Homepage, https://mqfarooqi1.github.io/agentic-rag-mcp/
Project-URL: Repository, https://github.com/mqfarooqi1/agentic-rag-mcp
Project-URL: Issues, https://github.com/mqfarooqi1/agentic-rag-mcp/issues
Author: Muhammad Farooqi
License: MIT License
        
        Copyright (c) 2026 Muhammad Farooqi
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: agentic-rag,claude,embeddings,faiss,mcp,model-context-protocol,multi-agent,rag,retrieval,semantic-search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Indexing
Requires-Python: >=3.11
Requires-Dist: faiss-cpu>=1.9
Requires-Dist: fastembed<1,>=0.9.1
Requires-Dist: mcp<3,>=2.3
Requires-Dist: numpy>=1.26
Requires-Dist: pydantic>=2.7
Provides-Extra: agents
Requires-Dist: anthropic<3,>=2.14; extra == 'agents'
Provides-Extra: dev
Requires-Dist: anthropic<3,>=2.14; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

<!-- mcp-name: io.github.mqfarooqi1/agentic-rag-mcp -->

# <img src="https://raw.githubusercontent.com/mqfarooqi1/agentic-rag-mcp/main/site/logo.svg" alt="" width="44" align="top"> agentic-rag-mcp

**Semantic search over your own documents, for agents that search more than once.**

[![PyPI](https://img.shields.io/pypi/v/agentic-rag-mcp.svg)](https://pypi.org/project/agentic-rag-mcp/)
[![CI](https://github.com/mqfarooqi1/agentic-rag-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/mqfarooqi1/agentic-rag-mcp/actions/workflows/ci.yml)
![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)
![MCP 2.3](https://img.shields.io/badge/MCP-2.3-7C3AED.svg)
![MIT licence](https://img.shields.io/badge/License-MIT-blue.svg)

[Website](https://mqfarooqi1.github.io/agentic-rag-mcp/) ·
[The measurement](#measured-not-asserted) ·
[Changelog](CHANGELOG.md)

This began as a weekend build to get three buzzwords straight in my own head by
actually wiring them up: **agentic RAG**, **MCP**, and a small **multi-agent**
pipeline, all over the same tiny document set. It is still small and readable
on purpose, but it now installs in one line, runs on your own documents, and
measures the claim it was built to illustrate: that one search is often not
enough.

```bash
uvx agentic-rag-mcp serve --docs ~/notes
```

## Quick start

Add it to **Claude Code**:

```bash
claude mcp add notes -- uvx agentic-rag-mcp serve --docs /absolute/path/to/notes
```

Or to **Claude Desktop**, in `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "notes": {
      "command": "uvx",
      "args": ["agentic-rag-mcp", "serve", "--docs", "/absolute/path/to/notes"]
    }
  }
}
```

It indexes every `.md`, `.markdown`, `.txt` and `.rst` file under the folder,
skipping hidden folders and `node_modules`. Leave out `--docs` and it serves the
bundled demo documents, so you can try it before pointing it at anything of
yours.

The first search downloads a 90 MB embedding model once. To do that, and build
the index, before a client is waiting on it:

```bash
uvx agentic-rag-mcp index --docs ~/notes
```

Prefer pip? `pip install agentic-rag-mcp`, then `agentic-rag-mcp serve --docs ~/notes`.
From source: `pip install git+https://github.com/mqfarooqi1/agentic-rag-mcp`.

## What runs without an API key, and what needs one

| Piece | What it is | API key? |
|---|---|---|
| `knowledge_base.py` | chunk → embed (MiniLM) → FAISS search. The retrieval backend everything else uses. | no |
| `server.py` | the MCP server: `kb_search`, `kb_fetch`, `kb_sources` | no |
| `evaluation.py` | how often one search finds every fact a question needs | no (`--agent` yes) |
| `agentic.py` | an agent that drives its own retrieval through a search tool | yes |
| `multi_agent.py` | retriever → synthesizer → verifier, with a revise loop | yes (offline: stub roles) |
| `llm.py` | the hand-written tool-use loop the agents share | — |

Through MCP the client is the agent: Claude does the searching, so the server
itself never needs a key. The built-in agents are there to run without a
client, and to read.

## How it works

### Retrieval

Fixed-size character chunks with overlap, MiniLM embeddings, a FAISS flat
inner-product index, so a score is a cosine similarity. No reranker, no hybrid
BM25, no semantic chunking. Those are the obvious quality upgrades, and the
measurement below shows one question they would fix, but this project is about
the orchestration on top, so the retriever is intentionally the simple part.

Embeddings run through [fastembed](https://github.com/qdrant/fastembed) on ONNX
Runtime rather than sentence-transformers: the same model with identical
vectors (cosine similarity 1.000000 on the same sentences), but no PyTorch. A
fresh install is 308 MB, where PyTorch and transformers alone took 644 MB.

Vectors are cached on disk under a hash of the model and every chunk, so an
unchanged folder loads instantly and an edited one is re-embedded rather than
served stale. Indexing and search run locally; no document is uploaded to build
the index. (The chunks an agent reads do become part of its conversation, and so
reach whichever model provider the client uses.)

### Agentic RAG

Naive RAG retrieves once and answers. That breaks on questions like *"how do I
authenticate SqlSource after 3.0, and is the old way still supported?"*: the
answer is split across the migration guide and the changelog, and a single top-k
search usually grabs one and misses the other.

Agentic RAG hands the model a `kb_search` tool and lets it decide: search, read
the results, notice that the second half of the question isn't covered, search
again, then answer with citations. Same FAISS backend; the model just does the
multi-hop lookups itself.

The trade-off is real and worth stating: the agent costs several model
round-trips and can occasionally wander or over-search. For single-fact
questions naive RAG is cheaper and just as good. The agent earns its cost only
when one lookup genuinely isn't enough, and `ask --naive` gives the fair
baseline to check that: one search, then the same model under the same rules.

### MCP

The agents could just `import knowledge_base`. MCP is about *not* doing that.
[Model Context Protocol](https://modelcontextprotocol.io) is a standard way for
a server to advertise tools and for any client - Claude Code, Claude Desktop, an
IDE, your own agent - to discover and call them without custom glue. Run one
retrieval server, point many clients at it.

| Tool | Returns |
|---|---|
| `kb_search(query, k=4)` | the closest chunks, each with a cosine score, its source and a `chunk_id` to cite |
| `kb_fetch(chunk_id)` | the full text of one chunk |
| `kb_sources()` | the indexed documents and the size of the index |

All three are annotated read-only and publish output schemas, so clients get
validated structured results. Mistakes an agent can fix, such as an empty query
or an unknown chunk id, come back with an explanation it can act on rather than
a bare "error executing tool". `examples/mcp_client_demo.py` drives the server
from a script, exactly as a client does:

```bash
python examples/mcp_client_demo.py              # the demo documents
python examples/mcp_client_demo.py ~/notes      # your own folder
```

### Multi-agent

Same task, decomposed into three focused roles, orchestrated in plain Python:

```
question -> RETRIEVER (has the search tool) -> evidence
         -> SYNTHESIZER (no tools)          -> draft answer
         -> VERIFIER (structured output)    -> supported? / issues
              supported -> return
              not       -> feed issues back to the synthesizer, retry (<= N)
```

That's two standard patterns: orchestrator/workers and evaluator/optimizer (the
verify-and-revise loop). The flow is ordinary code; I'm deliberately **not**
letting agents spawn each other freely. For a task this well-shaped, a fixed
workflow is more predictable, cheaper, and far easier to debug than an
autonomous swarm, and you can read exactly what happened. Autonomous multi-agent
is worth it when the task genuinely can't be scripted up front. This one can, so
it's a workflow with LLM steps, and I think that's the honest default for most
"agent" problems.

The roles are just functions, so the model-backed version and an offline stub
version share the same `orchestrate()` loop.

### The agent loop

The loop in `llm.py` is one short function, written by hand rather than with
the SDK's tool runner so the control flow can be read. Every request uses Claude Opus 5.5
(override with `AGENTIC_RAG_MODEL`) with adaptive thinking and an explicit
effort level, caches the growing conversation, and enables server-side refusal
fallbacks where the model supports them. It stops loudly: a refusal, running out
of output tokens, or the turn limit raises `AgentStopped`, rather than returning
a placeholder that the next stage would treat as an answer.

## Measured, not asserted

Does one search actually miss things? Nine questions over the demo documents,
each listing the facts a complete answer needs. A fact counts as retrieved if
its phrase appears in a retrieved chunk from the right document, so the scores
survive changes to the chunk size. Whether a question needs more than one chunk
is computed from the real chunking, not declared: four of the nine do.

`agentic-rag-mcp eval -k 2` (2 chunks per search, 10-chunk index):

| Strategy | Recall | 2+ chunk questions | 1 chunk questions | Complete | Chunks read |
|---|---:|---:|---:|---:|---:|
| One search | 79.6% | 79.2% | 80.0% | 5/9 | 2.0 |
| One search, twice the chunks | 85.2% | 79.2% | 90.0% | 6/9 | 4.0 |
| Question split at commas | 79.6% | 79.2% | 80.0% | 5/9 | 3.0 |
| **Planned sub-queries** | **88.9%** | **87.5%** | **90.0%** | **7/9** | **2.8** |

What it shows:

- **Better queries beat more chunks on multi-hop questions.** Planned
  sub-queries reach 87.5% where doubling the budget of a single search stays at
  79.2%, while reading fewer chunks.
- **Splitting the question mechanically does not help.** Query planning needs
  understanding, which is the model's job.
- **Some facts no query found.** "The defaults are 5 and 30" lives in a code
  signature, `connect(dsn, *, pool_size=5, timeout=30)`, which a purely semantic
  embedding matches poorly. That is where hybrid keyword search would help.

These are small numbers: nine questions over ten chunks show the method, not a
benchmark. At four chunks per search, one query already reads 40% of the corpus
and the strategies stop being distinguishable. CI reruns the measurement on every
push and posts the table to the run summary, and `--agent` adds a real agent's
own searches (it makes API calls, one agent run per question).

## Command line

```bash
agentic-rag-mcp serve  [--docs DIR]          # MCP server on stdio
agentic-rag-mcp index  [--docs DIR]          # build the cache, list what is indexed
agentic-rag-mcp search "query" [--docs DIR] [-k 4] [--json]
agentic-rag-mcp ask "question" [--docs DIR] [--naive | --pipeline]
agentic-rag-mcp eval [-k 4] [--agent] [--json]
```

`ask` needs `pip install "agentic-rag-mcp[agents]"` and Anthropic credentials.
Without credentials it shows what a single search retrieves (or, with
`--pipeline`, runs the stub roles) so you can still watch the control flow.

| Variable | Default | Purpose |
|---|---|---|
| `AGENTIC_RAG_DOCS` | bundled demo docs | the folder to index, when `--docs` is not given |
| `AGENTIC_RAG_CACHE_DIR` | per-user cache folder | where embeddings and the model are kept |
| `FASTEMBED_CACHE_PATH` | inside the cache folder | override for the model alone |
| `AGENTIC_RAG_MODEL` | `claude-opus-5-5` | the model the built-in agents use |
| `AGENTIC_RAG_EFFORT` | `medium` | effort level; empty leaves it to the model |
| `ANTHROPIC_API_KEY` | - | or any credential the SDK reads, including `ant auth login` |

## Development

```bash
pip install -e ".[dev]"
pytest                         # 86 tests; the first run downloads the model
pytest -m "not integration"    # offline only, in a few seconds
ruff check src tests examples
```

Most tests use a deterministic word-hashing embedder, so they need no model. The
`integration` tests use the real model and drive the real server over stdio.
The agent tests run the real Anthropic SDK against scripted HTTP responses, so
they check the exact requests the loop sends, with no key and no cost.

## What I said I'd do for real work, and where it stands

The first version of this README ended with a list of what I'd do differently
for real work. Here it is again, honestly scored.

| Then | Now |
|---|---|
| It's five toy docs; retrieval quality would matter more on a real corpus. | **Partly done.** It indexes any folder of your own. Chunking and ranking are still the simple versions. |
| I never measured anything. | **Partly done.** Retrieval recall is measured, above. Answer quality is not, which needs a graded eval set. |
| The verifier is an LLM judge; it can be wrong and tends to be lenient. | **Open.** It still needs calibrating against human-checked answers. |
| The agent loop has no budget cap beyond `max_turns`. | **Partly done.** Limits now raise instead of passing on placeholders, and `ask` reports tokens used, but there is no token budget or cost ceiling yet. |
| The agents would call the KB *through* the MCP server. | **Done the other way round.** Through MCP the client is now the agent, which is the main way to use it. The built-in agents still call the KB directly, for legibility. |

Two more that the measurement points at: hybrid keyword search, for facts that
live in code and identifiers, and incremental re-embedding, since any edit
re-embeds the whole folder today.

---

MIT licence · [Muhammad Farooqi](https://github.com/mqfarooqi1)
