Your documentation assistant says to retry an order request with a new idempotency key. It includes a link to the orders page. The link looks plausible, but the actual retry section says to reuse the same key.
A useful citation should let you recover the exact passage behind an answer. That starts with the retrieval interface. In this tutorial, you’ll build a local documentation server using the Model Context Protocol (MCP). It exposes search and fetch, and a separate Python client verifies an evidence reference before rendering its link. The order API and its documentation are fictional, so you can run the example without credentials or access to a real service.
Give the client two tools
Search answers “where should I look?” Fetch answers “what does that section actually say?” Keeping them separate lets the client examine several short candidates before loading the full text of one section. It also gives each citation a precise source: the document section returned by fetch.
Redis described this distinction in its documentation MCP engineering write-up. Its server offers search, fetch, and a separate answer synthesis operation. We’ll implement the first two and leave answer generation to the client. That keeps the example small enough to inspect and lets us test the evidence path without an API key. Redis Docs MCP engineering write-up
MCP supplies the protocol for discovering and calling the tools. The server defines the meaning of a document ID, the ranking method, and the shape of each result. The host decides whether to call a tool and how to use its response. In this tutorial a Python client plays the host’s role with a fixed sequence of calls, so it’s easy to see which guarantees come from code. MCP tools specification
Download the tutorial files (server.py, check.py, and requirements.txt).
Set up the local server
Use Python 3.12 and a virtual environment. The example pins version 1.26.0 of the official Python SDK to reproduce the calls shown here. The package name is mcp and the FastMCP import below comes from that package. The shell commands use macOS or Linux syntax. On Windows, activate the environment with the appropriate script for your shell. Python SDK 1.26.0 documentation
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install "mcp==1.26.0"
Save this as server.py. Both records are invented for the tutorial. The example URLs serve as display metadata, and running the code requires no network access after installation. Each record represents a section rather than a whole page. That makes the returned text short and gives the client a section-level anchor to show readers.
import re
from hashlib import sha256
from typing import Any
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("docs-demo")
DOCS = {
"orders:v1:retry": (
"Order retries (v1)",
"https://docs.example.com/v1/orders#retry",
"Retry a timed-out order request with the same idempotency key.",
),
"orders:v1:status": (
"Order status (v1)",
"https://docs.example.com/v1/orders#status",
"Read order status using the order ID returned at creation.",
),
}
def tokens(value: str) -> set[str]:
return set(re.findall(r"[a-z0-9]+", value.lower()))
@mcp.tool()
def search(query: str) -> dict[str, Any]:
"""Find candidate documentation sections and return their IDs."""
terms = tokens(query[:500])
matches = []
for doc_id, (title, _, text) in DOCS.items():
score = len(terms & tokens(f"{title} {text}"))
if score:
matches.append((score, doc_id, title, text[:80]))
matches.sort(key=lambda row: (-row[0], row[1]))
return {"results": [
{"id": doc_id, "title": title, "snippet": snippet}
for _, doc_id, title, snippet in matches[:5]
]}
@mcp.tool()
def fetch(id: str) -> dict[str, Any]:
"""Read the text and source metadata for an exact search result ID."""
if id not in DOCS:
raise ValueError("Unknown documentation ID. Search again.")
title, url, text = DOCS[id]
return {
"id": id, "title": title, "url": url, "text": text,
"sha256": sha256(text.encode("utf-8")).hexdigest(),
}
if __name__ == "__main__":
mcp.run(transport="stdio")
Search ranks a section by how many distinct query tokens appear in its title and text. It returns at most five results and breaks ties by ID. A blank or unmatched query yields an empty list. This is intentionally easy to read. It has no stemming, so searching for “retried” may miss text that only says “retry.” Use test queries from your own documentation before deciding whether the ranking is adequate.
Fetch accepts an ID that was assigned by the server. It looks up the ID in a dictionary and rejects unknown values. That distinction matters once a corpus moves to disk or object storage. Treat an ID as a lookup key in your catalog, and resolve it to a storage location you control. Passing user-supplied strings straight to a file reader would turn a retrieval operation into a broader file access interface.
The server uses stdio. A client launches it as a subprocess and exchanges MCP messages over its input and output streams. Keep debugging output on stderr so it stays out of the protocol stream. If you run python server.py on its own, it waits for a client. The next script starts it for you.
Verify citations where the answer is assembled
For this design, the model would propose an ID and an exact quote. The host checks them against the documents fetched for the current answer. Then the host attaches the URL from the source record. A string that looks like a link has no role in deciding where the citation points.
Save this as check.py beside the server. The example hardcodes a citation candidate so you can verify the retrieval path separately from model behavior.
import asyncio
import sys
from hashlib import sha256
from pathlib import Path
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
def verify_citation(citation: dict, fetched: dict) -> str:
source = fetched.get(citation["id"])
if source is None:
raise ValueError("Citation ID was never fetched")
quote = citation["quote"]
if not quote.strip() or quote not in source["text"]:
raise ValueError("Quote is missing from fetched text")
return source["url"]
async def main():
server = Path(__file__).with_name("server.py").resolve()
params = StdioServerParameters(command=sys.executable, args=[str(server)])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
names = {tool.name for tool in (await session.list_tools()).tools}
assert {"search", "fetch"} <= names
search = await session.call_tool("search", {"query": "idempotency key"})
assert not search.isError
doc_id = search.structuredContent["results"][0]["id"]
fetched = await session.call_tool("fetch", {"id": doc_id})
assert not fetched.isError
source = fetched.structuredContent
assert source["id"] == doc_id
assert sha256(source["text"].encode()).hexdigest() == source["sha256"]
citation = {
"id": doc_id,
"quote": "with the same idempotency key",
}
evidence = {doc_id: source}
url = verify_citation(citation, evidence)
print(f"Verified {doc_id} -> {url}")
for invalid in [
{"id": "orders:v2:retry", "quote": citation["quote"]},
{"id": doc_id, "quote": "with a new idempotency key"},
]:
try:
verify_citation(invalid, evidence)
except ValueError:
pass
else:
raise AssertionError("Accepted invalid citation")
missing = await session.call_tool("fetch", {"id": "../private"})
assert missing.isError
if __name__ == "__main__":
asyncio.run(main())
Run python check.py. The successful line is:
Verified orders:v1:retry -> https://docs.example.com/v1/orders#retry
The client discovers the tools, searches for “idempotency key,” and fetches the first matching section. It checks the text hash and accepts the exact phrase “with the same idempotency key.” It also checks that an ID absent from the evidence set, an altered quote, and a path-like fetch ID are rejected. SDK logs may appear on stderr alongside the successful line. If you swap in a search query with no matches, handle the empty result before indexing it. The script assumes a known fixture and deliberately fails when it can’t find it.
The check establishes a specific relationship between the citation and the fetched content. It confirms that the quote exists in that text and that the link comes from the associated record. A valid quote can still be used to support a wrong conclusion. An answer could quote the retry rule accurately while claiming it applies to a different endpoint. Checking that the passage supports the claim is a separate evaluation step.
The hash also has a narrow job. It identifies the exact UTF-8 text bytes returned by this server. Recomputing it checks consistency with the advertised digest. If you need to establish that the text matches a trusted release, compare it with a digest from a trusted manifest or signed publishing pipeline.
Keep the evidence useful after the docs change
In a real documentation pipeline, decide what happens when someone edits a section. The toy ID orders:v1:retry separates a product version and section, but it doesn’t prevent an editor from changing the v1 page tomorrow. Store the document revision separately, such as a Git commit or immutable build ID, and capture it alongside the fetched section and digest.
One way to avoid a race between search and fetch is to include the revision in the returned lookup key or keep the client on a consistent index snapshot. Otherwise the search preview can describe one revision while the fetched section comes from another. Consider what the reader sees too. A canonical link might point to a newer page by the time they click it. If exact historical reproduction matters, render a permalink to the cited revision when your documentation site supports one.
Keep one evidence set per answer. Persist the source identifiers and revision with the answer if you need to audit it later, subject to your data retention rules. For private documentation, apply authorization at both search and fetch. Even a title or snippet can reveal material that a caller cannot access. Recheck permissions when reusing cached evidence across requests.
Add complexity when you can measure what it fixes
For a larger corpus, move the same interface over an indexed store. Start by checking whether common queries retrieve the right section, including exact command names, error messages, and questions that specify a version. Compare a lexical index with semantic or hybrid retrieval if your evaluation shows users describe concepts in different words than the docs use.
Include queries with no relevant result. A good test case is a request about a feature that only exists in another release. Record the expected section or expected abstention before running the evaluation. Evaluate retrieval and citation separately so you can tell whether a failure came from a missing source, a bad ranking, an invalid reference, or a claim the evidence doesn’t support.
Also test conflicting evidence. If two pages disagree, have the host present the applicable release or ask which version the user runs. Treat text retrieved from docs as source data even when it contains commands or instructions aimed at a model. The host still controls its tools and permissions.
Start with a few real questions and their expected passages. Confirm that search finds the right candidates, fetch can reproduce them, and the client renders the links from its evidence records. Those checks stay useful as you change the index, switch models, or add more documentation.
