studyrag-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abubakar Idrees
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: studyrag-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server: search, read and fact-check your own study notes (StudyRAG) from Claude Code, Claude Desktop, Cursor or any MCP client.
5
+ Author: Abubakar Idrees
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server
8
+ Project-URL: Source, https://github.com/Abubakar-idrees-01/data-to-impact
9
+ Project-URL: Documentation, https://github.com/Abubakar-idrees-01/data-to-impact/blob/main/03-mcp-server/docs/SETUP.md
10
+ Keywords: mcp,model-context-protocol,rag,claude,study,notes
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: mcp<3,>=2.3
18
+ Requires-Dist: pydantic>=2
19
+ Requires-Dist: studyrag>=0.1.0
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # studyrag-mcp
25
+
26
+ An **MCP server** that lets Claude Code, Claude Desktop, Cursor or any MCP client search your own study notes
27
+ (indexed by [StudyRAG](https://pypi.org/project/studyrag/)), read them slide by slide, and **fact-check answers
28
+ against them**, with citations. Read-only, local, no API key.
29
+
30
+ ![A real tool session](https://raw.githubusercontent.com/Abubakar-idrees-01/data-to-impact/main/03-mcp-server/docs/images/demo.png)
31
+
32
+ ```bash
33
+ pip install studyrag-mcp
34
+ studyrag sync ~/my-lecture-notes # index your notes once (StudyRAG's CLI, installed alongside)
35
+ ```
36
+
37
+ Then add it to your assistant. For Claude Code, put this in `.mcp.json` at your workspace root:
38
+ ```json
39
+ {"mcpServers": {"studyrag": {"type": "stdio", "command": "studyrag-mcp"}}}
40
+ ```
41
+ (Use the full path to `studyrag-mcp` if it isn't on the PATH the assistant sees.)
42
+
43
+ **Tools:** `search_notes` (hybrid search with citations and an honest "not found"), `get_passage`,
44
+ `list_documents`, `document_outline`, `check_answer` (scores each sentence against the passages it cites),
45
+ plus evaluation-run tools when [evalkit](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/02-llm-evals) is installed. Prompts: *explain from my notes*,
46
+ *quiz me*, *revise a lecture*.
47
+
48
+ Docs, design notes and the from-scratch MCP implementation: [https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server)
@@ -0,0 +1,25 @@
1
+ # studyrag-mcp
2
+
3
+ An **MCP server** that lets Claude Code, Claude Desktop, Cursor or any MCP client search your own study notes
4
+ (indexed by [StudyRAG](https://pypi.org/project/studyrag/)), read them slide by slide, and **fact-check answers
5
+ against them**, with citations. Read-only, local, no API key.
6
+
7
+ ![A real tool session](https://raw.githubusercontent.com/Abubakar-idrees-01/data-to-impact/main/03-mcp-server/docs/images/demo.png)
8
+
9
+ ```bash
10
+ pip install studyrag-mcp
11
+ studyrag sync ~/my-lecture-notes # index your notes once (StudyRAG's CLI, installed alongside)
12
+ ```
13
+
14
+ Then add it to your assistant. For Claude Code, put this in `.mcp.json` at your workspace root:
15
+ ```json
16
+ {"mcpServers": {"studyrag": {"type": "stdio", "command": "studyrag-mcp"}}}
17
+ ```
18
+ (Use the full path to `studyrag-mcp` if it isn't on the PATH the assistant sees.)
19
+
20
+ **Tools:** `search_notes` (hybrid search with citations and an honest "not found"), `get_passage`,
21
+ `list_documents`, `document_outline`, `check_answer` (scores each sentence against the passages it cites),
22
+ plus evaluation-run tools when [evalkit](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/02-llm-evals) is installed. Prompts: *explain from my notes*,
23
+ *quiz me*, *revise a lecture*.
24
+
25
+ Docs, design notes and the from-scratch MCP implementation: [https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server)
@@ -0,0 +1,72 @@
1
+ # 🔌 studyrag-mcp: your study notes as tools for any AI assistant
2
+
3
+ An **MCP server** that lets Claude Code, Claude Desktop, Cursor or any MCP client search your own lecture slides
4
+ and notes, read them slide by slide, and **fact-check answers against them**, with citations. It also gives the
5
+ assistant read access to your evaluation results. It runs locally on a CPU, needs no API key, and only reads.
6
+
7
+ It connects two other projects in this portfolio: [StudyRAG](../01-rag-from-scratch) (project 1) provides the search, and
8
+ [evalkit](../02-llm-evals) (project 2) provides the evaluation runs.
9
+
10
+ ![A real tool session](docs/images/demo.png)
11
+
12
+ *A real session, on the public sample corpus. The assistant searches, drafts an answer, and checks it. The invented
13
+ last sentence (added on purpose) is caught and removed. Full transcript: [docs/DEMO.md](docs/DEMO.md).*
14
+ **PDFs:** [Overview](docs/pdf/studyrag-mcp-Overview.pdf) · [Timeline](docs/pdf/studyrag-mcp-Timeline.pdf) · [Setup](docs/pdf/studyrag-mcp-Setup-Guide.pdf) · [How it works](docs/pdf/studyrag-mcp-How-It-Works.pdf) · [Results](docs/pdf/studyrag-mcp-Results.pdf) · [Decisions](docs/pdf/studyrag-mcp-Design-Decisions.pdf) · [Concepts](docs/pdf/studyrag-mcp-Concepts-Handbook.pdf)
15
+
16
+ ## Tools
17
+ | | tool | what it does |
18
+ |---|---|---|
19
+ | 🔎 | `search_notes` | Hybrid search (BM25 + embeddings + reranker) over your notes; numbered passages with citations, and `found: false` when nothing is relevant enough |
20
+ | 📄 | `get_passage` · `list_documents` · `document_outline` | Read a slide/page, list your library, outline a lecture |
21
+ | ✅ | `check_answer` | Scores each sentence of an answer against the passages it cites and lists unsupported ones |
22
+ | 📊 | `list_eval_runs` · `eval_run_summary` · `compare_eval_runs` | Read evalkit runs; "is v2 really better?" with paired significance tests |
23
+
24
+ Also **resources** (`notes://documents`, `notes://documents/{name}` for a whole lecture's text) and **prompts**
25
+ (*explain from my notes*, *quiz me*, *revise a lecture*).
26
+
27
+ ## Highlights
28
+ - **Built twice:** on the official MCP SDK for real use, and **from scratch** (JSON-RPC over stdio in ≈ 250 lines of
29
+ standard library). The official client connecting to the scratch version is a conformance test.
30
+ - **The server does no generation:** the assistant is the model. The server adds private search and claim checking.
31
+ - **Safe to call:** every tool is read-only, inputs are bounded, file access is confined (path traversal is refused
32
+ and tested), and expected errors tell the model how to fix its call.
33
+ - **Measured:** 15 tests, including the installed server over real stdio with real models. Search takes 0.94 s;
34
+ the first call takes 14 s to load models ([results](docs/RESULTS.md)).
35
+ - **Never stale:** when you sync new files in StudyRAG, the next tool call sees them.
36
+
37
+ ## Quickstart
38
+ ```bash
39
+ cd 03-mcp-server
40
+ python3 -m venv .venv && source .venv/bin/activate
41
+ pip install -r requirements.txt && pip install --no-deps -e .
42
+ ```
43
+ Then add it to your assistant: for Claude Code, put this in `.mcp.json` at your workspace root and reload.
44
+ ```json
45
+ {"mcpServers": {"studyrag": {"type": "stdio",
46
+ "command": "/ABSOLUTE/PATH/TO/03-mcp-server/.venv/bin/python", "args": ["-m", "studyrag_mcp"]}}}
47
+ ```
48
+ You need a StudyRAG index first (project 1). Full guide, plus Claude Desktop and HTTP setup: **[docs/SETUP.md](docs/SETUP.md)**.
49
+
50
+ ## Documentation
51
+ | | |
52
+ |---|---|
53
+ | [How it works](docs/HOW_IT_WORKS.md) | Architecture and one question end to end |
54
+ | [Results](docs/RESULTS.md) | Tests, latency, behaviour on real notes, problems found |
55
+ | [Design decisions](docs/DECISIONS.md) | Why each choice |
56
+ | Concepts | 1. [What MCP is](docs/concepts/01-what-is-mcp.md) · 2. [MCP on the wire](docs/concepts/02-mcp-on-the-wire.md) · 3. [Designing tools for an LLM](docs/concepts/03-designing-tools-for-an-llm.md) · 4. [Security and privacy](docs/concepts/04-security-and-privacy.md) |
57
+
58
+ ## Privacy
59
+ The server runs locally and makes no network calls. Passages it returns are shown to your assistant, which means
60
+ they're sent to that assistant's provider, like text you paste into a chat.
61
+
62
+ ## Layout
63
+ ```
64
+ src/studyrag_mcp/ server.py (official SDK) · notes.py · evals.py · scratch.py (protocol from scratch)
65
+ tests/ scratch protocol + conformance, server in-process, stdio end to end
66
+ scripts/ benchmark.py
67
+ examples/ client config template
68
+ docs/ setup, architecture, concepts, decisions, results
69
+ ```
70
+
71
+ ## License
72
+ MIT.
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "studyrag-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server: search, read and fact-check your own study notes (StudyRAG) from Claude Code, Claude Desktop, Cursor or any MCP client."
9
+ readme = "PYPI.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Abubakar Idrees" }]
14
+ keywords = ["mcp", "model-context-protocol", "rag", "claude", "study", "notes"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Intended Audience :: Education",
18
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
19
+ ]
20
+ dependencies = ["mcp>=2.3,<3", "pydantic>=2", "studyrag>=0.1.0"]
21
+
22
+ [project.optional-dependencies]
23
+ dev = ["pytest"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server"
27
+ Source = "https://github.com/Abubakar-idrees-01/data-to-impact"
28
+ Documentation = "https://github.com/Abubakar-idrees-01/data-to-impact/blob/main/03-mcp-server/docs/SETUP.md"
29
+
30
+ [project.scripts]
31
+ studyrag-mcp = "studyrag_mcp.server:main"
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """StudyRAG MCP server: your study notes (project 1) and evaluation runs (project 2) as tools for AI assistants."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .server import main
2
+
3
+ main()
@@ -0,0 +1,66 @@
1
+ """Read-only access to evalkit runs (project 2): list them, summarize one, compare two.
2
+
3
+ Paths are always resolved inside one results directory: a tool argument like "../../.ssh/id_rsa" is
4
+ rejected, so an AI client can never use these tools to read arbitrary files.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from pathlib import Path
11
+
12
+ DEFAULT_RESULTS = Path(__file__).resolve().parents[3] / "02-llm-evals" / "results"
13
+
14
+
15
+ class EvalsError(ValueError):
16
+ pass
17
+
18
+
19
+ class Evals:
20
+ def __init__(self, results_dir: str | Path | None = None):
21
+ self.root = Path(results_dir or os.environ.get("STUDYRAG_MCP_EVAL_RESULTS") or DEFAULT_RESULTS).resolve()
22
+
23
+ def _path(self, run: str) -> Path:
24
+ name = run.strip().removesuffix(".json")
25
+ if not name:
26
+ raise EvalsError("run is empty; use list_eval_runs to see the available runs")
27
+ p = (self.root / f"{name}.json").resolve()
28
+ if self.root not in p.parents:
29
+ raise EvalsError("run must be a name like 'suite/run' inside the results directory")
30
+ if not p.exists():
31
+ raise EvalsError(f"no run {name!r}; use list_eval_runs to see the available runs")
32
+ return p
33
+
34
+ def list_runs(self) -> dict:
35
+ if not self.root.exists():
36
+ return {"results_dir": None, "runs": [],
37
+ "note": "no evalkit results directory found; set STUDYRAG_MCP_EVAL_RESULTS to one"}
38
+ runs = sorted(str(p.relative_to(self.root).with_suffix("")) for p in self.root.glob("*/*.json")
39
+ if p.name != "selected.json")
40
+ return {"results_dir": str(self.root), "count": len(runs), "runs": runs}
41
+
42
+ @staticmethod
43
+ def _evalkit():
44
+ try:
45
+ import evalkit.compare
46
+ import evalkit.runs
47
+ return evalkit
48
+ except ImportError:
49
+ raise EvalsError("evaluation tools need evalkit (project 2): pip install -e path/to/02-llm-evals") from None
50
+
51
+ def summary(self, run: str) -> dict:
52
+ Run = self._evalkit().runs.Run
53
+ r = Run.load(self._path(run))
54
+ return {"run": f"{r.suite}/{r.name}", "items": len(r.items), "created": r.created,
55
+ "config": r.config, "metrics": r.metrics, "table": r.summary_table()}
56
+
57
+ def compare(self, base: str, new: str, metrics: list[str] | None = None) -> dict:
58
+ ek = self._evalkit()
59
+ compare, Run = ek.compare.compare, ek.runs.Run
60
+ c = compare(Run.load(self._path(base)), Run.load(self._path(new)), metrics or None)
61
+ if not c.diffs:
62
+ raise EvalsError("the two runs share no metrics/items to compare")
63
+ return {"base": c.base, "new": c.new, "markdown": c.to_markdown(),
64
+ "metrics": [{"metric": d.metric, "n": d.n, "base": d.base, "new": d.new, "delta": d.delta,
65
+ "ci": [d.ci_low, d.ci_high], "p": d.p, "test": d.test, "significant": d.significant,
66
+ "improved": d.improved[:20], "regressed": d.regressed[:20]} for d in c.diffs]}
@@ -0,0 +1,163 @@
1
+ """The study-notes service: what the MCP tools do, as plain Python (no MCP, so it's easy to test).
2
+
3
+ It wraps StudyRAG (project 1): its persistent library (your indexed slides, PDFs and notes) and its hybrid
4
+ retriever (BM25 + vectors + RRF + cross-encoder). Everything here is read-only and needs no LLM: the AI
5
+ client that calls these tools *is* the language model. It searches, reads the passages, writes the answer,
6
+ and can ask `check_answer` whether each sentence is backed by the passages it cites.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import threading
12
+ from pathlib import Path
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ MAX_TOP_K = 10
17
+ MAX_ANSWER_CHARS = 8000
18
+
19
+
20
+ class NotesError(ValueError):
21
+ """A problem with the request (unknown document, bad location...): shown to the model as a tool error."""
22
+
23
+
24
+ @dataclass
25
+ class Backend:
26
+ """The StudyRAG pieces the tools need. Built from a real StudyRAG, or from fakes in tests."""
27
+ library: Any
28
+ retriever: Any
29
+ embedder: Any
30
+ settings: Any
31
+
32
+
33
+ def load_backend() -> Backend:
34
+ """Load StudyRAG with its default settings (index in 01-rag-from-scratch/storage, models in its models/)."""
35
+ from studyrag.core import StudyRAG
36
+ rag = StudyRAG()
37
+ return Backend(rag.library, rag.retriever, rag.embedder, rag.settings)
38
+
39
+
40
+ class Notes:
41
+ def __init__(self, backend: Backend | None = None):
42
+ self._backend = backend
43
+ self._lock = threading.Lock()
44
+ self._index_mtime = self._manifest_mtime() if backend else None
45
+
46
+ def _manifest_mtime(self) -> float | None:
47
+ try:
48
+ return (Path(self._backend.settings.storage_dir) / "manifest.json").stat().st_mtime
49
+ except (OSError, AttributeError, TypeError):
50
+ return None
51
+
52
+ @property
53
+ def b(self) -> Backend:
54
+ # Lazy: loading the embedding + reranker models takes seconds, and the MCP handshake must be instant.
55
+ if self._backend is None:
56
+ with self._lock:
57
+ if self._backend is None:
58
+ self._backend = load_backend()
59
+ self._index_mtime = self._manifest_mtime()
60
+ # The index is shared with the StudyRAG app and CLI: when they sync new files, reload it (cheap: the
61
+ # models stay loaded, only the chunks and vectors are read again). A long-running server never goes stale.
62
+ mtime = self._manifest_mtime()
63
+ if mtime is not None and mtime != self._index_mtime:
64
+ with self._lock:
65
+ if mtime != self._index_mtime:
66
+ self._reload_library()
67
+ self._index_mtime = mtime
68
+ return self._backend
69
+
70
+ def _reload_library(self) -> None:
71
+ from studyrag.library import Library
72
+ from studyrag.retrieval import Retriever
73
+ b = self._backend
74
+ lib = Library(b.settings, b.embedder)
75
+ self._backend = Backend(lib, Retriever(lib, b.embedder, b.retriever.reranker, b.settings), b.embedder,
76
+ b.settings)
77
+
78
+ # ------------------------------------------------------------------ helpers
79
+ def _doc(self, name: str):
80
+ d = self.b.library.find_doc(name.strip())
81
+ if d is None:
82
+ titles = ", ".join(sorted(x.title for x in self.b.library.docs.values())[:12]) or "none indexed"
83
+ raise NotesError(f"no document matches {name!r}. Available: {titles}")
84
+ return d
85
+
86
+ @staticmethod
87
+ def _passage(chunk, n: int | None = None, relevance: float | None = None) -> dict:
88
+ p = {"citation": chunk.header, "document": chunk.doc_title, "location": chunk.location,
89
+ "chunk_id": chunk.chunk_id, "text": chunk.text}
90
+ if n is not None:
91
+ p = {"n": n, **p}
92
+ if relevance is not None:
93
+ p["relevance"] = round(float(relevance), 3)
94
+ return p
95
+
96
+ # ------------------------------------------------------------------ tools
97
+ def search(self, query: str, top_k: int = 4, document: str | None = None) -> dict:
98
+ query = query.strip()
99
+ if not query:
100
+ raise NotesError("query is empty")
101
+ if not 1 <= top_k <= MAX_TOP_K:
102
+ raise NotesError(f"top_k must be between 1 and {MAX_TOP_K}")
103
+ doc_ids = [self._doc(document).doc_id] if document else None
104
+ res = self.b.retriever.retrieve(query, top_k=top_k, doc_ids=doc_ids)
105
+ threshold = self.b.settings.refusal_threshold
106
+ found = bool(res.hits) and res.top_relevance >= threshold
107
+ passages = [self._passage(h.chunk, n, h.rerank_score) for n, h in enumerate(res.hits, 1)]
108
+ note = ("Cite passages as [n] with their citation. Answer only from them."
109
+ if found else
110
+ "Nothing relevant enough was found (best relevance below the calibrated threshold "
111
+ f"{threshold}). Say the notes don't cover this rather than answering from general knowledge.")
112
+ return {"query": query, "found": found, "best_relevance": round(float(res.top_relevance), 3),
113
+ "passages": passages, "guidance": note}
114
+
115
+ def list_documents(self) -> dict:
116
+ docs = sorted(self.b.library.docs.values(), key=lambda d: d.title.lower())
117
+ return {"count": len(docs), "documents": [
118
+ {"title": d.title, "doc_id": d.doc_id, "type": d.doc_type, "chunks": d.n_chunks, "words": d.n_words,
119
+ "ocr_pages": d.n_ocr} for d in docs]}
120
+
121
+ def outline(self, document: str) -> dict:
122
+ from studyrag.study.summarize import outline
123
+ d = self._doc(document)
124
+ return {"document": d.title, "outline": outline(self.b.library.chunks_of(d.doc_id))}
125
+
126
+ def get_passage(self, document: str, location: int) -> dict:
127
+ """The passage(s) covering slide/page `location` of a document (the unit citations point to)."""
128
+ d = self._doc(document)
129
+ chunks = [c for c in self.b.library.chunks_of(d.doc_id) if c.loc_start <= location <= c.loc_end]
130
+ if not chunks:
131
+ rng = [c.loc_start for c in self.b.library.chunks_of(d.doc_id)]
132
+ span = f"{min(rng)}–{max(c.loc_end for c in self.b.library.chunks_of(d.doc_id))}" if rng else "none"
133
+ raise NotesError(f"{d.title} has no passage at location {location} (available: {span})")
134
+ return {"document": d.title, "passages": [self._passage(c) for c in chunks]}
135
+
136
+ def check_answer(self, answer: str, chunk_ids: list[str]) -> dict:
137
+ """Check each sentence of an answer against the passages it cites ([n] = chunk_ids[n-1])."""
138
+ from studyrag.verify import verify_answer
139
+ answer = answer.strip()
140
+ if not answer:
141
+ raise NotesError("answer is empty")
142
+ if len(answer) > MAX_ANSWER_CHARS:
143
+ raise NotesError(f"answer is longer than {MAX_ANSWER_CHARS} characters")
144
+ if not chunk_ids:
145
+ raise NotesError("give the chunk_ids of the passages the answer cites, in [n] order")
146
+ by_id = {c.chunk_id: c for c in self.b.library.chunks}
147
+ missing = [i for i in chunk_ids if i not in by_id]
148
+ if missing:
149
+ raise NotesError(f"unknown chunk_id(s): {', '.join(missing[:5])} (use ids returned by search_notes)")
150
+ sources = [by_id[i] for i in chunk_ids]
151
+ ver = verify_answer(answer, sources, self.b.embedder, self.b.settings.support_threshold)
152
+ checks = [{"sentence": c.sentence, "cited": c.cited, "supported": c.supported,
153
+ "support": round(float(c.support), 3), "best_source": c.best_source} for c in ver.checks]
154
+ return {"supported_ratio": round(ver.supported_ratio, 3), "sentences": checks,
155
+ "unsupported": [c["sentence"] for c in checks if not c["supported"]],
156
+ "method": "word overlap + embedding similarity (StudyRAG's verifier; a heuristic, not entailment)"}
157
+
158
+ def document_text(self, document: str, max_chars: int = 20000) -> str:
159
+ d = self._doc(document)
160
+ parts = [f"## {c.location}\n{c.text}" for c in self.b.library.chunks_of(d.doc_id)]
161
+ text = f"# {d.title}\n\n" + "\n\n".join(parts)
162
+ return text if len(text) <= max_chars else text[:max_chars] + "\n\n[... truncated]"
163
+
@@ -0,0 +1,269 @@
1
+ """MCP from scratch: the Model Context Protocol in ~250 lines of standard library.
2
+
3
+ This is the "how it works underneath" version. The real server (server.py) uses the official SDK;
4
+ this one exists to show, and test, what actually goes over the wire. It speaks enough MCP for real
5
+ clients (including the official SDK's client: see tests/test_scratch.py) to connect, list and call tools,
6
+ read resources and get prompts.
7
+
8
+ The wire format (stdio transport):
9
+ - one JSON-RPC 2.0 message per line on stdin/stdout, UTF-8, no embedded newlines;
10
+ - stdout is ONLY for protocol messages; logs go to stderr (a stray print() corrupts the stream).
11
+
12
+ The lifecycle:
13
+ client -> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":..., "capabilities":{},
14
+ "clientInfo":{...}}}
15
+ server -> {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":..., "capabilities":{"tools":{},...},
16
+ "serverInfo":{...}}}
17
+ client -> {"jsonrpc":"2.0","method":"notifications/initialized"} (a notification: no id, no reply)
18
+ client -> tools/list, tools/call, resources/list, resources/read, prompts/list, prompts/get, ping ...
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import sys
25
+ import traceback
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Callable, TextIO
28
+
29
+ # Protocol versions this implementation understands, newest first. If the client asks for one of these we
30
+ # answer with the same; otherwise we answer with our newest and the client decides whether to continue.
31
+ SUPPORTED_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
32
+
33
+ # JSON-RPC 2.0 error codes
34
+ PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR = -32700, -32600, -32601, -32602, -32603
35
+
36
+ _JSON_TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "object": dict, "array": list}
37
+
38
+
39
+ class RPCError(Exception):
40
+ def __init__(self, code: int, message: str, data: Any = None):
41
+ super().__init__(message)
42
+ self.code, self.message, self.data = code, message, data
43
+
44
+
45
+ @dataclass
46
+ class Tool:
47
+ name: str
48
+ description: str
49
+ input_schema: dict
50
+ fn: Callable[..., Any]
51
+
52
+
53
+ @dataclass
54
+ class Resource:
55
+ uri: str
56
+ name: str
57
+ description: str
58
+ mime_type: str
59
+ read: Callable[[], str]
60
+
61
+
62
+ @dataclass
63
+ class Prompt:
64
+ name: str
65
+ description: str
66
+ arguments: list[dict] # [{"name", "description", "required"}]
67
+ render: Callable[..., str]
68
+
69
+
70
+ def validate(args: dict, schema: dict) -> None:
71
+ """A deliberately small subset of JSON Schema: required keys, basic types, enums, numeric bounds.
72
+ Enough to reject bad tool calls with a clear message before any work is done."""
73
+ if not isinstance(args, dict):
74
+ raise RPCError(INVALID_PARAMS, "arguments must be an object")
75
+ props = schema.get("properties", {})
76
+ missing = [k for k in schema.get("required", []) if k not in args]
77
+ if missing:
78
+ raise RPCError(INVALID_PARAMS, f"missing required argument(s): {', '.join(missing)}")
79
+ if schema.get("additionalProperties") is False:
80
+ unknown = sorted(set(args) - set(props))
81
+ if unknown:
82
+ raise RPCError(INVALID_PARAMS, f"unknown argument(s): {', '.join(unknown)}")
83
+ for key, value in args.items():
84
+ spec = props.get(key, {})
85
+ expected = _JSON_TYPES.get(spec.get("type"))
86
+ is_bool = isinstance(value, bool)
87
+ if expected and (not isinstance(value, expected) or (is_bool and spec.get("type") in ("integer", "number"))):
88
+ raise RPCError(INVALID_PARAMS, f"'{key}' must be of type {spec['type']}")
89
+ if "enum" in spec and value not in spec["enum"]:
90
+ raise RPCError(INVALID_PARAMS, f"'{key}' must be one of {spec['enum']}")
91
+ if "minimum" in spec and value < spec["minimum"] or "maximum" in spec and value > spec["maximum"]:
92
+ raise RPCError(INVALID_PARAMS, f"'{key}' must be between {spec.get('minimum')} and {spec.get('maximum')}")
93
+ if spec.get("type") == "string" and "minLength" in spec and len(value.strip()) < spec["minLength"]:
94
+ raise RPCError(INVALID_PARAMS, f"'{key}' must not be empty")
95
+
96
+
97
+ @dataclass
98
+ class ScratchServer:
99
+ name: str
100
+ version: str = "0.1.0"
101
+ instructions: str | None = None
102
+ tools: dict[str, Tool] = field(default_factory=dict)
103
+ resources: dict[str, Resource] = field(default_factory=dict)
104
+ prompts: dict[str, Prompt] = field(default_factory=dict)
105
+ initialized: bool = False
106
+
107
+ # ------------------------------------------------------------------ registration (decorators)
108
+ def tool(self, name: str, description: str, input_schema: dict):
109
+ def deco(fn):
110
+ self.tools[name] = Tool(name, description, input_schema, fn)
111
+ return fn
112
+ return deco
113
+
114
+ def resource(self, uri: str, name: str, description: str, mime_type: str = "text/plain"):
115
+ def deco(fn):
116
+ self.resources[uri] = Resource(uri, name, description, mime_type, fn)
117
+ return fn
118
+ return deco
119
+
120
+ def prompt(self, name: str, description: str, arguments: list[dict]):
121
+ def deco(fn):
122
+ self.prompts[name] = Prompt(name, description, arguments, fn)
123
+ return fn
124
+ return deco
125
+
126
+ # ------------------------------------------------------------------ method handlers
127
+ def _initialize(self, params: dict) -> dict:
128
+ requested = params.get("protocolVersion")
129
+ version = requested if requested in SUPPORTED_VERSIONS else SUPPORTED_VERSIONS[0]
130
+ caps = {}
131
+ if self.tools:
132
+ caps["tools"] = {"listChanged": False}
133
+ if self.resources:
134
+ caps["resources"] = {"listChanged": False, "subscribe": False}
135
+ if self.prompts:
136
+ caps["prompts"] = {"listChanged": False}
137
+ result = {"protocolVersion": version, "capabilities": caps,
138
+ "serverInfo": {"name": self.name, "version": self.version}}
139
+ if self.instructions:
140
+ result["instructions"] = self.instructions
141
+ return result
142
+
143
+ def _tools_list(self, params: dict) -> dict:
144
+ return {"tools": [{"name": t.name, "description": t.description, "inputSchema": t.input_schema}
145
+ for t in self.tools.values()]}
146
+
147
+ def _tools_call(self, params: dict) -> dict:
148
+ name = params.get("name")
149
+ if name not in self.tools:
150
+ raise RPCError(INVALID_PARAMS, f"unknown tool: {name}")
151
+ tool, args = self.tools[name], params.get("arguments") or {}
152
+ validate(args, tool.input_schema)
153
+ try:
154
+ value = tool.fn(**args)
155
+ except Exception as e: # a failing tool is a RESULT with isError, so the model can react
156
+ return {"content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}], "isError": True}
157
+ if isinstance(value, (dict, list)):
158
+ return {"content": [{"type": "text", "text": json.dumps(value, ensure_ascii=False, indent=1)}],
159
+ "structuredContent": value if isinstance(value, dict) else {"result": value}, "isError": False}
160
+ return {"content": [{"type": "text", "text": str(value)}], "isError": False}
161
+
162
+ def _resources_list(self, params: dict) -> dict:
163
+ return {"resources": [{"uri": r.uri, "name": r.name, "description": r.description, "mimeType": r.mime_type}
164
+ for r in self.resources.values()]}
165
+
166
+ def _resources_read(self, params: dict) -> dict:
167
+ uri = params.get("uri")
168
+ if uri not in self.resources:
169
+ raise RPCError(-32002, f"resource not found: {uri}") # MCP's "resource not found" code
170
+ r = self.resources[uri]
171
+ return {"contents": [{"uri": uri, "mimeType": r.mime_type, "text": r.read()}]}
172
+
173
+ def _prompts_list(self, params: dict) -> dict:
174
+ return {"prompts": [{"name": p.name, "description": p.description, "arguments": p.arguments}
175
+ for p in self.prompts.values()]}
176
+
177
+ def _prompts_get(self, params: dict) -> dict:
178
+ name = params.get("name")
179
+ if name not in self.prompts:
180
+ raise RPCError(INVALID_PARAMS, f"unknown prompt: {name}")
181
+ p, args = self.prompts[name], params.get("arguments") or {}
182
+ missing = [a["name"] for a in p.arguments if a.get("required") and a["name"] not in args]
183
+ if missing:
184
+ raise RPCError(INVALID_PARAMS, f"missing prompt argument(s): {', '.join(missing)}")
185
+ return {"description": p.description,
186
+ "messages": [{"role": "user", "content": {"type": "text", "text": p.render(**args)}}]}
187
+
188
+ # ------------------------------------------------------------------ dispatch
189
+ def handle(self, message: dict) -> dict | None:
190
+ """Process one JSON-RPC message; return the response, or None for notifications."""
191
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or "method" not in message:
192
+ return _error(message.get("id") if isinstance(message, dict) else None, INVALID_REQUEST,
193
+ "not a JSON-RPC 2.0 request")
194
+ method, params, msg_id = message["method"], message.get("params") or {}, message.get("id")
195
+ is_notification = "id" not in message
196
+ if is_notification:
197
+ if method == "notifications/initialized":
198
+ self.initialized = True
199
+ return None # notifications never get a reply
200
+ handlers = {"initialize": self._initialize, "ping": lambda p: {},
201
+ "tools/list": self._tools_list, "tools/call": self._tools_call,
202
+ "resources/list": self._resources_list, "resources/read": self._resources_read,
203
+ "resources/templates/list": lambda p: {"resourceTemplates": []},
204
+ "prompts/list": self._prompts_list, "prompts/get": self._prompts_get}
205
+ if method not in handlers:
206
+ return _error(msg_id, METHOD_NOT_FOUND, f"method not found: {method}")
207
+ try:
208
+ return {"jsonrpc": "2.0", "id": msg_id, "result": handlers[method](params)}
209
+ except RPCError as e:
210
+ return _error(msg_id, e.code, e.message, e.data)
211
+ except Exception as e: # a bug in the server, not the client's fault
212
+ traceback.print_exc(file=sys.stderr)
213
+ return _error(msg_id, INTERNAL_ERROR, f"internal error: {e}")
214
+
215
+ def serve(self, stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout) -> None:
216
+ """The stdio transport: read a line, handle it, write the reply as one line. Ends at EOF."""
217
+ for line in stdin:
218
+ if not line.strip():
219
+ continue
220
+ try:
221
+ message = json.loads(line)
222
+ except json.JSONDecodeError as e:
223
+ reply = _error(None, PARSE_ERROR, f"parse error: {e}")
224
+ else:
225
+ reply = self.handle(message)
226
+ if reply is not None:
227
+ stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
228
+ stdout.flush()
229
+
230
+
231
+ def _error(msg_id, code: int, message: str, data: Any = None) -> dict:
232
+ err = {"code": code, "message": message}
233
+ if data is not None:
234
+ err["data"] = data
235
+ return {"jsonrpc": "2.0", "id": msg_id, "error": err}
236
+
237
+
238
+ def demo_server() -> ScratchServer:
239
+ """A tiny server for tests and for reading along in docs/concepts: two tools, one resource, one prompt."""
240
+ s = ScratchServer("scratch-demo", instructions="A from-scratch MCP server for learning.")
241
+
242
+ @s.tool("add", "Add two integers.", {"type": "object", "additionalProperties": False, "required": ["a", "b"],
243
+ "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}})
244
+ def add(a: int, b: int) -> dict:
245
+ return {"sum": a + b}
246
+
247
+ @s.tool("word_count", "Count the words in a text.",
248
+ {"type": "object", "required": ["text"], "properties": {"text": {"type": "string", "minLength": 1}}})
249
+ def word_count(text: str) -> str:
250
+ return f"{len(text.split())} words"
251
+
252
+ @s.tool("divide", "Divide a by b.", {"type": "object", "required": ["a", "b"],
253
+ "properties": {"a": {"type": "number"}, "b": {"type": "number"}}})
254
+ def divide(a: float, b: float) -> dict:
255
+ return {"result": a / b} # b = 0 -> a tool error result, not a crash
256
+
257
+ @s.resource("demo://readme", "readme", "What this server is", "text/markdown")
258
+ def readme() -> str:
259
+ return "# scratch-demo\nAn MCP server in ~250 lines of standard-library Python."
260
+
261
+ @s.prompt("explain", "Ask for a beginner explanation.", [{"name": "topic", "required": True}])
262
+ def explain(topic: str) -> str:
263
+ return f"Explain {topic} to a beginner in three sentences."
264
+
265
+ return s
266
+
267
+
268
+ if __name__ == "__main__": # python -m studyrag_mcp.scratch
269
+ demo_server().serve()
@@ -0,0 +1,191 @@
1
+ """The StudyRAG MCP server (official SDK): your study notes and evaluation results as tools for any AI assistant.
2
+
3
+ studyrag-mcp # stdio (what Claude Code, Claude Desktop, Cursor... launch)
4
+ studyrag-mcp --http --port 8765 # Streamable HTTP, for clients that connect over the network
5
+
6
+ Tools never write anything and never call an LLM: the assistant is the language model. Passages a tool returns
7
+ are sent to that assistant (and its provider), exactly like text pasted into a chat.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import functools
14
+ import logging
15
+ import sys
16
+ from typing import Annotated, Any, Callable
17
+
18
+ from mcp.server.mcpserver import MCPServer
19
+ from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError
20
+ from mcp_types import ToolAnnotations
21
+ from pydantic import Field
22
+
23
+ from . import __version__
24
+ from .evals import Evals, EvalsError
25
+ from .notes import MAX_TOP_K, Notes, NotesError
26
+
27
+ log = logging.getLogger("studyrag_mcp")
28
+
29
+ INSTRUCTIONS = """Tools over the user's own study material (lecture slides, PDFs, notes indexed by StudyRAG) and
30
+ their evaluation results.
31
+ - To answer a question about the user's material: call search_notes, answer ONLY from the returned passages,
32
+ cite them as [n] with their citation (e.g. "Lec 2 — Slide 14"), and if `found` is false say the notes don't
33
+ cover it instead of using general knowledge.
34
+ - To double-check an answer you wrote: call check_answer with the chunk_ids you cited, in [n] order.
35
+ - list_documents / document_outline / get_passage browse the library; eval tools read evaluation runs."""
36
+
37
+ READ_ONLY = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
38
+
39
+
40
+ def as_tool_errors(fn: Callable) -> Callable:
41
+ """Expected failures (unknown document, bad location...) become ToolError: the model sees the message and
42
+ can correct its call. Anything else is a bug: the SDK hides the details and logs the traceback."""
43
+ @functools.wraps(fn)
44
+ def wrapper(*args, **kwargs):
45
+ try:
46
+ return fn(*args, **kwargs)
47
+ except (NotesError, EvalsError) as e:
48
+ raise ToolError(str(e)) from e
49
+ return wrapper
50
+
51
+
52
+ def build_server(notes: Notes | None = None, evals: Evals | None = None) -> MCPServer:
53
+ notes = notes or Notes()
54
+ evals = evals or Evals()
55
+ mcp = MCPServer(name="studyrag", title="StudyRAG notes", version=__version__, instructions=INSTRUCTIONS,
56
+ description="Search, read and fact-check your own study material; read evaluation runs.")
57
+
58
+ # ------------------------------------------------------------------ study-notes tools
59
+ @mcp.tool(title="Search my notes", annotations=READ_ONLY)
60
+ @as_tool_errors
61
+ def search_notes(
62
+ query: Annotated[str, Field(min_length=1, max_length=500,
63
+ description="What to look for, in natural language or keywords")],
64
+ top_k: Annotated[int, Field(ge=1, le=MAX_TOP_K, description="How many passages to return")] = 4,
65
+ document: Annotated[str | None, Field(description="Limit to one document (title or part of it)")] = None,
66
+ ) -> dict[str, Any]:
67
+ """Hybrid search (keywords + meaning, then a cross-encoder reranker) over the user's indexed study
68
+ material. Returns numbered passages with citations and relevance, and `found`: false when nothing
69
+ is relevant enough to answer from."""
70
+ return notes.search(query, top_k, document)
71
+
72
+ @mcp.tool(title="List my documents", annotations=READ_ONLY)
73
+ @as_tool_errors
74
+ def list_documents() -> dict[str, Any]:
75
+ """All indexed documents with their size (chunks, words) and how many pages needed OCR."""
76
+ return notes.list_documents()
77
+
78
+ @mcp.tool(title="Outline a document", annotations=READ_ONLY)
79
+ @as_tool_errors
80
+ def document_outline(
81
+ document: Annotated[str, Field(min_length=1, description="Document title (or part of it) or doc_id")],
82
+ ) -> dict[str, Any]:
83
+ """The slide titles / section headings of one document, in order, with their locations."""
84
+ return notes.outline(document)
85
+
86
+ @mcp.tool(title="Read a slide or page", annotations=READ_ONLY)
87
+ @as_tool_errors
88
+ def get_passage(
89
+ document: Annotated[str, Field(min_length=1, description="Document title (or part of it) or doc_id")],
90
+ location: Annotated[int, Field(ge=1, description="Slide or page number")],
91
+ ) -> dict[str, Any]:
92
+ """The full text of the passage at a slide/page number, e.g. to read around a search hit."""
93
+ return notes.get_passage(document, location)
94
+
95
+ @mcp.tool(title="Check an answer against its sources", annotations=READ_ONLY)
96
+ @as_tool_errors
97
+ def check_answer(
98
+ answer: Annotated[str, Field(min_length=1, max_length=8000,
99
+ description="The answer to check, with [n] citations")],
100
+ chunk_ids: Annotated[list[str], Field(min_length=1, max_length=MAX_TOP_K,
101
+ description="chunk_id of source [1], [2], ... in order")],
102
+ ) -> dict[str, Any]:
103
+ """Score every sentence of an answer against the passages it cites (StudyRAG's verifier: word overlap
104
+ plus embedding similarity). Lists unsupported sentences so they can be fixed or removed."""
105
+ return notes.check_answer(answer, chunk_ids)
106
+
107
+ # ------------------------------------------------------------------ evaluation tools
108
+ @mcp.tool(title="List evaluation runs", annotations=READ_ONLY)
109
+ @as_tool_errors
110
+ def list_eval_runs() -> dict[str, Any]:
111
+ """Saved evalkit runs (project 2), named 'suite/run'."""
112
+ return evals.list_runs()
113
+
114
+ @mcp.tool(title="Summarize an evaluation run", annotations=READ_ONLY)
115
+ @as_tool_errors
116
+ def eval_run_summary(
117
+ run: Annotated[str, Field(min_length=1, description="Run name 'suite/run' from list_eval_runs")],
118
+ ) -> dict[str, Any]:
119
+ """Metrics of one run with 95% confidence intervals, its configuration and size."""
120
+ return evals.summary(run)
121
+
122
+ @mcp.tool(title="Compare two evaluation runs", annotations=READ_ONLY)
123
+ @as_tool_errors
124
+ def compare_eval_runs(
125
+ base: Annotated[str, Field(min_length=1, description="Baseline run 'suite/run'")],
126
+ new: Annotated[str, Field(min_length=1, description="New run 'suite/run'")],
127
+ metrics: Annotated[list[str] | None, Field(description="Only these metrics (default: all shared)")] = None,
128
+ ) -> dict[str, Any]:
129
+ """Paired comparison of two runs item by item: change per metric, 95% CI, p-value (McNemar or paired
130
+ bootstrap), and which items got better or worse. Says whether a difference is real or noise."""
131
+ return evals.compare(base, new, metrics)
132
+
133
+ # ------------------------------------------------------------------ resources
134
+ @mcp.resource("notes://documents", name="documents", mime_type="application/json",
135
+ description="The indexed documents")
136
+ def documents_resource() -> dict[str, Any]:
137
+ return notes.list_documents()
138
+
139
+ @mcp.resource("notes://documents/{document}", name="document-text", mime_type="text/markdown",
140
+ description="Full text of one document (title or doc_id), slide by slide")
141
+ def document_resource(document: str) -> str:
142
+ try:
143
+ return notes.document_text(document)
144
+ except NotesError as e:
145
+ raise ResourceNotFoundError(str(e)) from e
146
+
147
+ # ------------------------------------------------------------------ prompts
148
+ @mcp.prompt(title="Explain a topic from my notes")
149
+ def explain_from_notes(topic: str) -> str:
150
+ """Explain a topic using only the user's own material, with citations."""
151
+ return (f"Explain \"{topic}\" to me as a student, using ONLY my study notes. First call search_notes "
152
+ f"with a good query (try a second query if the first finds little). Write a clear explanation with "
153
+ f"[n] citations to the passages, then call check_answer and fix any unsupported sentence. If my "
154
+ f"notes don't cover it, say so.")
155
+
156
+ @mcp.prompt(title="Quiz me")
157
+ def quiz_me(topic: str, questions: str = "5") -> str:
158
+ """Generate practice questions from the user's notes, one at a time, and grade the answers."""
159
+ return (f"Quiz me on \"{topic}\" from my study notes. Use search_notes (and get_passage to read more) to "
160
+ f"find the material, then ask me {questions} questions ONE AT A TIME, mixing multiple-choice and "
161
+ f"short-answer. After each answer, grade it, explain using the passage, and cite it. Only use "
162
+ f"facts from my notes.")
163
+
164
+ @mcp.prompt(title="Revise a lecture")
165
+ def revise_document(document: str) -> str:
166
+ """A structured revision sheet for one lecture/document."""
167
+ return (f"Make a revision sheet for \"{document}\". Call document_outline, then search_notes or get_passage "
168
+ f"for each main heading. Give: key definitions, the main points per section, and 5 likely exam "
169
+ f"questions, all with citations to the slides.")
170
+
171
+ return mcp
172
+
173
+
174
+ def main(argv: list[str] | None = None) -> None:
175
+ p = argparse.ArgumentParser(prog="studyrag-mcp", description=__doc__.split("\n")[0])
176
+ p.add_argument("--http", action="store_true", help="serve Streamable HTTP instead of stdio")
177
+ p.add_argument("--host", default="127.0.0.1")
178
+ p.add_argument("--port", type=int, default=8765)
179
+ p.add_argument("--version", action="version", version=f"studyrag-mcp {__version__}")
180
+ a = p.parse_args(argv)
181
+ # stdout belongs to the protocol on stdio: every log line goes to stderr
182
+ logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
183
+ server = build_server()
184
+ if a.http:
185
+ server.run("streamable-http", host=a.host, port=a.port)
186
+ else:
187
+ server.run()
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: studyrag-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server: search, read and fact-check your own study notes (StudyRAG) from Claude Code, Claude Desktop, Cursor or any MCP client.
5
+ Author: Abubakar Idrees
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server
8
+ Project-URL: Source, https://github.com/Abubakar-idrees-01/data-to-impact
9
+ Project-URL: Documentation, https://github.com/Abubakar-idrees-01/data-to-impact/blob/main/03-mcp-server/docs/SETUP.md
10
+ Keywords: mcp,model-context-protocol,rag,claude,study,notes
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: mcp<3,>=2.3
18
+ Requires-Dist: pydantic>=2
19
+ Requires-Dist: studyrag>=0.1.0
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # studyrag-mcp
25
+
26
+ An **MCP server** that lets Claude Code, Claude Desktop, Cursor or any MCP client search your own study notes
27
+ (indexed by [StudyRAG](https://pypi.org/project/studyrag/)), read them slide by slide, and **fact-check answers
28
+ against them**, with citations. Read-only, local, no API key.
29
+
30
+ ![A real tool session](https://raw.githubusercontent.com/Abubakar-idrees-01/data-to-impact/main/03-mcp-server/docs/images/demo.png)
31
+
32
+ ```bash
33
+ pip install studyrag-mcp
34
+ studyrag sync ~/my-lecture-notes # index your notes once (StudyRAG's CLI, installed alongside)
35
+ ```
36
+
37
+ Then add it to your assistant. For Claude Code, put this in `.mcp.json` at your workspace root:
38
+ ```json
39
+ {"mcpServers": {"studyrag": {"type": "stdio", "command": "studyrag-mcp"}}}
40
+ ```
41
+ (Use the full path to `studyrag-mcp` if it isn't on the PATH the assistant sees.)
42
+
43
+ **Tools:** `search_notes` (hybrid search with citations and an honest "not found"), `get_passage`,
44
+ `list_documents`, `document_outline`, `check_answer` (scores each sentence against the passages it cites),
45
+ plus evaluation-run tools when [evalkit](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/02-llm-evals) is installed. Prompts: *explain from my notes*,
46
+ *quiz me*, *revise a lecture*.
47
+
48
+ Docs, design notes and the from-scratch MCP implementation: [https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/03-mcp-server)
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ PYPI.md
3
+ README.md
4
+ pyproject.toml
5
+ src/studyrag_mcp/__init__.py
6
+ src/studyrag_mcp/__main__.py
7
+ src/studyrag_mcp/evals.py
8
+ src/studyrag_mcp/notes.py
9
+ src/studyrag_mcp/scratch.py
10
+ src/studyrag_mcp/server.py
11
+ src/studyrag_mcp.egg-info/PKG-INFO
12
+ src/studyrag_mcp.egg-info/SOURCES.txt
13
+ src/studyrag_mcp.egg-info/dependency_links.txt
14
+ src/studyrag_mcp.egg-info/entry_points.txt
15
+ src/studyrag_mcp.egg-info/requires.txt
16
+ src/studyrag_mcp.egg-info/top_level.txt
17
+ tests/test_scratch.py
18
+ tests/test_server.py
19
+ tests/test_stdio_e2e.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ studyrag-mcp = studyrag_mcp.server:main
@@ -0,0 +1,6 @@
1
+ mcp<3,>=2.3
2
+ pydantic>=2
3
+ studyrag>=0.1.0
4
+
5
+ [dev]
6
+ pytest
@@ -0,0 +1 @@
1
+ studyrag_mcp
@@ -0,0 +1,94 @@
1
+ """The from-scratch MCP server: raw JSON-RPC behaviour, and conformance with the official SDK's client."""
2
+
3
+ import asyncio
4
+ import io
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ from mcp import Client, StdioServerParameters
10
+
11
+ from studyrag_mcp.scratch import INVALID_PARAMS, METHOD_NOT_FOUND, PARSE_ERROR, SUPPORTED_VERSIONS, demo_server
12
+
13
+
14
+ def rpc(server, method, params=None, msg_id=1):
15
+ msg = {"jsonrpc": "2.0", "id": msg_id, "method": method}
16
+ if params is not None:
17
+ msg["params"] = params
18
+ return server.handle(msg)
19
+
20
+
21
+ def test_handshake_negotiates_version_and_capabilities():
22
+ s = demo_server()
23
+ r = rpc(s, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
24
+ "clientInfo": {"name": "t", "version": "1"}})["result"]
25
+ assert r["protocolVersion"] == "2025-06-18"
26
+ assert set(r["capabilities"]) == {"tools", "resources", "prompts"} and r["serverInfo"]["name"] == "scratch-demo"
27
+ unknown = rpc(s, "initialize", {"protocolVersion": "1999-01-01"})["result"]
28
+ assert unknown["protocolVersion"] == SUPPORTED_VERSIONS[0] # counter-offer our newest
29
+ assert s.handle({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None and s.initialized
30
+
31
+
32
+ def test_tools_list_and_call():
33
+ s = demo_server()
34
+ names = [t["name"] for t in rpc(s, "tools/list")["result"]["tools"]]
35
+ assert names == ["add", "word_count", "divide"]
36
+ r = rpc(s, "tools/call", {"name": "add", "arguments": {"a": 2, "b": 3}})["result"]
37
+ assert r["structuredContent"] == {"sum": 5} and not r["isError"] and json.loads(r["content"][0]["text"]) == {"sum": 5}
38
+
39
+
40
+ def test_validation_errors_are_protocol_errors_but_tool_failures_are_results():
41
+ s = demo_server()
42
+ err = rpc(s, "tools/call", {"name": "add", "arguments": {"a": 2}})["error"]
43
+ assert err["code"] == INVALID_PARAMS and "missing required" in err["message"]
44
+ assert "must be of type integer" in rpc(s, "tools/call", {"name": "add", "arguments": {"a": "2", "b": 1}})["error"]["message"]
45
+ assert "must be of type integer" in rpc(s, "tools/call", {"name": "add", "arguments": {"a": True, "b": 1}})["error"]["message"]
46
+ assert "unknown argument" in rpc(s, "tools/call", {"name": "add", "arguments": {"a": 1, "b": 1, "c": 1}})["error"]["message"]
47
+ assert rpc(s, "tools/call", {"name": "nope", "arguments": {}})["error"]["code"] == INVALID_PARAMS
48
+ # the tool ran and failed: the MODEL should see this and react, so it is a result with isError
49
+ r = rpc(s, "tools/call", {"name": "divide", "arguments": {"a": 1, "b": 0}})["result"]
50
+ assert r["isError"] and "ZeroDivisionError" in r["content"][0]["text"]
51
+
52
+
53
+ def test_resources_prompts_ping_and_unknown_methods():
54
+ s = demo_server()
55
+ assert rpc(s, "resources/list")["result"]["resources"][0]["uri"] == "demo://readme"
56
+ assert "scratch-demo" in rpc(s, "resources/read", {"uri": "demo://readme"})["result"]["contents"][0]["text"]
57
+ assert rpc(s, "resources/read", {"uri": "demo://nope"})["error"]["code"] == -32002
58
+ msg = rpc(s, "prompts/get", {"name": "explain", "arguments": {"topic": "MCP"}})["result"]["messages"][0]
59
+ assert msg["role"] == "user" and "MCP" in msg["content"]["text"]
60
+ assert rpc(s, "prompts/get", {"name": "explain", "arguments": {}})["error"]["code"] == INVALID_PARAMS
61
+ assert rpc(s, "ping")["result"] == {}
62
+ assert rpc(s, "server/discover")["error"]["code"] == METHOD_NOT_FOUND
63
+
64
+
65
+ def test_stdio_framing_one_message_per_line():
66
+ s = demo_server()
67
+ stdin = io.StringIO('{"jsonrpc":"2.0","id":1,"method":"ping"}\n\nnot json\n'
68
+ '{"jsonrpc":"2.0","method":"notifications/initialized"}\n')
69
+ stdout = io.StringIO()
70
+ s.serve(stdin, stdout)
71
+ lines = stdout.getvalue().splitlines()
72
+ assert len(lines) == 2 # ping reply + parse error; notification: no reply
73
+ assert json.loads(lines[0]) == {"jsonrpc": "2.0", "id": 1, "result": {}}
74
+ assert json.loads(lines[1])["error"]["code"] == PARSE_ERROR
75
+
76
+
77
+ def test_official_sdk_client_talks_to_the_scratch_server():
78
+ """Conformance: the official MCP client, over a real stdio subprocess, against our hand-written server."""
79
+ async def run():
80
+ params = StdioServerParameters(command=sys.executable, args=["-m", "studyrag_mcp.scratch"],
81
+ env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)})
82
+ async with Client(params) as c:
83
+ tools = await c.list_tools()
84
+ added = await c.call_tool("add", {"a": 20, "b": 22})
85
+ failed = await c.call_tool("divide", {"a": 1, "b": 0})
86
+ res = await c.read_resource("demo://readme")
87
+ prompt = await c.get_prompt("explain", {"topic": "JSON-RPC"})
88
+ return tools, added, failed, res, prompt
89
+ tools, added, failed, res, prompt = asyncio.run(run())
90
+ assert [t.name for t in tools.tools] == ["add", "word_count", "divide"]
91
+ assert added.structured_content == {"sum": 42} and not added.is_error
92
+ assert failed.is_error
93
+ assert "scratch-demo" in res.contents[0].text
94
+ assert "JSON-RPC" in prompt.messages[0].content.text
@@ -0,0 +1,124 @@
1
+ """The real server (official SDK), driven by the official client in-process, with fake models."""
2
+
3
+ import asyncio
4
+ import json
5
+
6
+ from mcp import Client
7
+
8
+ from studyrag_mcp.server import build_server
9
+
10
+
11
+ def call(server, tool, args=None):
12
+ async def run():
13
+ async with Client(server) as c:
14
+ return await c.call_tool(tool, args or {})
15
+ return asyncio.run(run())
16
+
17
+
18
+ def test_lists_tools_with_read_only_annotations(notes, evals):
19
+ async def run():
20
+ async with Client(build_server(notes, evals)) as c:
21
+ return (await c.list_tools()).tools
22
+ tools = {t.name: t for t in asyncio.run(run())}
23
+ assert set(tools) == {"search_notes", "list_documents", "document_outline", "get_passage", "check_answer",
24
+ "list_eval_runs", "eval_run_summary", "compare_eval_runs"}
25
+ assert all(t.annotations.read_only_hint for t in tools.values())
26
+ schema = tools["search_notes"].input_schema
27
+ assert schema["required"] == ["query"] and schema["properties"]["top_k"]["maximum"] == 10
28
+
29
+
30
+ def test_search_returns_cited_passages(notes, evals):
31
+ r = call(build_server(notes, evals), "search_notes", {"query": "what are backlinks", "top_k": 2})
32
+ s = r.structured_content
33
+ assert not r.is_error and s["found"] and len(s["passages"]) == 2
34
+ top = s["passages"][0]
35
+ assert top["n"] == 1 and "Backlinks" in top["citation"] and "votes of trust" in top["text"] and top["chunk_id"]
36
+
37
+
38
+ def test_search_in_one_document_and_bad_arguments(notes, evals):
39
+ server = build_server(notes, evals)
40
+ s = call(server, "search_notes", {"query": "metrics", "document": "email"}).structured_content
41
+ assert {p["document"] for p in s["passages"]} == {"email"}
42
+ bad = call(server, "search_notes", {"query": "x", "document": "no such lecture"})
43
+ assert bad.is_error and "no document matches" in bad.content[0].text and "Available" in bad.content[0].text
44
+ assert call(server, "search_notes", {"query": "", "top_k": 2}).is_error
45
+ assert call(server, "search_notes", {"query": "seo", "top_k": 99}).is_error
46
+
47
+
48
+ def test_browse_documents(notes, evals):
49
+ server = build_server(notes, evals)
50
+ docs = call(server, "list_documents").structured_content
51
+ assert docs["count"] == 2 and {d["title"] for d in docs["documents"]} == {"seo", "email"}
52
+ outline = call(server, "document_outline", {"document": "seo"}).structured_content["outline"]
53
+ assert any("Backlinks" in line for line in outline)
54
+ missing = call(server, "get_passage", {"document": "seo", "location": 99})
55
+ assert missing.is_error and "no passage at location 99" in missing.content[0].text
56
+
57
+
58
+ def test_check_answer_flags_unsupported_sentences(notes, evals):
59
+ server = build_server(notes, evals)
60
+ passages = call(server, "search_notes", {"query": "backlinks votes of trust", "top_k": 2}).structured_content["passages"]
61
+ ids = [p["chunk_id"] for p in passages]
62
+ answer = ("Search engines treat quality backlinks from other websites as votes of trust [1]. "
63
+ "Backlinks were invented by Napoleon in the year 1850 [1].")
64
+ r = call(server, "check_answer", {"answer": answer, "chunk_ids": ids}).structured_content
65
+ assert r["sentences"][0]["supported"] and not r["sentences"][1]["supported"]
66
+ assert r["unsupported"] == ["Backlinks were invented by Napoleon in the year 1850."]
67
+ bad = call(server, "check_answer", {"answer": "x y z", "chunk_ids": ["nope"]})
68
+ assert bad.is_error and "unknown chunk_id" in bad.content[0].text
69
+
70
+
71
+ def test_eval_tools_and_path_safety(notes, evals):
72
+ server = build_server(notes, evals)
73
+ assert call(server, "list_eval_runs").structured_content["runs"] == ["demo/v1", "demo/v2"]
74
+ summary = call(server, "eval_run_summary", {"run": "demo/v1"}).structured_content
75
+ assert summary["items"] == 30 and "correct" in summary["metrics"]
76
+ cmp = call(server, "compare_eval_runs", {"base": "demo/v1", "new": "demo/v2"}).structured_content
77
+ d = cmp["metrics"][0]
78
+ assert d["metric"] == "correct" and d["test"] == "McNemar" and d["significant"] and len(d["improved"]) == 10
79
+ for sneaky in ("../secret", "../../etc/passwd", "/etc/passwd"):
80
+ r = call(server, "eval_run_summary", {"run": sneaky})
81
+ assert r.is_error and "password" not in r.content[0].text
82
+
83
+
84
+ def test_resources_and_prompts(notes, evals):
85
+ async def run():
86
+ async with Client(build_server(notes, evals)) as c:
87
+ listing = await c.read_resource("notes://documents")
88
+ text = await c.read_resource("notes://documents/seo")
89
+ prompts = await c.list_prompts()
90
+ quiz = await c.get_prompt("quiz_me", {"topic": "SEO", "questions": "3"})
91
+ return listing, text, prompts, quiz
92
+ listing, text, prompts, quiz = asyncio.run(run())
93
+ assert json.loads(listing.contents[0].text)["count"] == 2
94
+ assert "votes of trust" in text.contents[0].text and text.contents[0].text.startswith("# seo")
95
+ assert {p.name for p in prompts.prompts} == {"explain_from_notes", "quiz_me", "revise_document"}
96
+ assert "3 questions ONE AT A TIME" in quiz.messages[0].content.text
97
+
98
+
99
+ def test_server_picks_up_files_synced_after_it_started(notes, evals, tmp_path):
100
+ server = build_server(notes, evals)
101
+ assert call(server, "list_documents").structured_content["count"] == 2
102
+ new = tmp_path / "docs" / "ppc.md"
103
+ new.write_text("# Pay per click\nPay-per-click advertising charges the advertiser each time an ad is clicked.\n")
104
+ # another process (the StudyRAG app or CLI) syncs the folder: same storage dir, separate Library object
105
+ from studyrag.library import Library
106
+ import os, time
107
+ other = Library(notes.b.settings, notes.b.embedder)
108
+ other.sync_folder(tmp_path / "docs")
109
+ manifest = tmp_path / "storage" / "manifest.json"
110
+ os.utime(manifest, (time.time() + 5, time.time() + 5)) # make the change visible on coarse-mtime filesystems
111
+ assert call(server, "list_documents").structured_content["count"] == 3
112
+ assert "Pay per click" in call(server, "search_notes", {"query": "pay per click ads"}).structured_content["passages"][0]["citation"]
113
+
114
+
115
+ def test_eval_tools_explain_when_evalkit_is_missing(notes, evals, monkeypatch):
116
+ import builtins
117
+ real_import = builtins.__import__
118
+ def no_evalkit(name, *args, **kwargs):
119
+ if name.startswith("evalkit"):
120
+ raise ImportError(name)
121
+ return real_import(name, *args, **kwargs)
122
+ monkeypatch.setattr(builtins, "__import__", no_evalkit)
123
+ r = call(build_server(notes, evals), "eval_run_summary", {"run": "demo/v1"})
124
+ assert r.is_error and "need evalkit" in r.content[0].text
@@ -0,0 +1,37 @@
1
+ """End to end: launch the real server the way Claude Code does (a subprocess over stdio), on the PUBLIC sample
2
+ index built by project 1's evaluation (Wikipedia articles), with the real embedding and reranker models.
3
+
4
+ Skipped when that index or the models aren't present (e.g. in CI)."""
5
+
6
+ import asyncio
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+ from mcp import Client, StdioServerParameters
13
+
14
+ RAG = Path(__file__).resolve().parents[2] / "01-rag-from-scratch"
15
+ SAMPLE_INDEX = RAG / "eval" / ".cache" / "sample-structure"
16
+ MODELS = RAG / "models" / "fastembed"
17
+
18
+ pytestmark = pytest.mark.skipif(not (SAMPLE_INDEX / "manifest.json").exists() or not MODELS.exists(),
19
+ reason="needs project 1's sample index and downloaded models")
20
+
21
+
22
+ def test_real_server_over_stdio():
23
+ async def run():
24
+ # No PYTHONPATH: the server must start the way a real client launches it (the package must be installed;
25
+ # an earlier version of this test passed sys.path along and hid exactly that bug).
26
+ env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"} | {"STUDYRAG_STORAGE_DIR": str(SAMPLE_INDEX)}
27
+ params = StdioServerParameters(command=sys.executable, args=["-m", "studyrag_mcp"], env=env)
28
+ async with Client(params, read_timeout_seconds=180) as c:
29
+ init_tools = await c.list_tools()
30
+ hit = await c.call_tool("search_notes", {"query": "How are affiliates paid?", "top_k": 3})
31
+ off = await c.call_tool("search_notes", {"query": "What is the boiling point of mercury?"})
32
+ return init_tools, hit, off
33
+ tools, hit, off = asyncio.run(run())
34
+ assert len(tools.tools) == 8
35
+ s = hit.structured_content
36
+ assert s["found"] and s["best_relevance"] > 0.5 and "Affiliate" in s["passages"][0]["citation"]
37
+ assert off.structured_content["found"] is False # calibrated refusal threshold, from project 1