Disclosure: This tutorial was sponsored by Upstash. All MCP/CLI configurations, Python scripts, Search API v3 queries, version-audit payloads, and FastAPI validation checks shown below were written and executed independently by me against the live Context7 v3 API and Pydantic 2.14.4.
AI coding agents inside Cursor, Claude Code, VS Code, and Windsurf still hallucinate deprecated library APIs—not because the underlying models are weak, but because their parametric weights are frozen at a static training cutoff while open-source frameworks ship breaking changes every month.
Ask an agent to add a pre-validation normalizer to a FastAPI request model using Pydantic v2 (2.14.4), and without live documentation grounding it frequently falls back on high-frequency Pydantic v1 patterns from older training data:
from pydantic import BaseModel, validator
class ArticleCreate(BaseModel):
title: str
tags: list[str]
@validator("tags", pre=True)
def split_tags(cls, v):
if isinstance(v, str):
return [item.strip() for item in v.split(",") if item.strip()]
return v
Running that code against modern Pydantic v2 triggers a PydanticDeprecatedSince20 warning at best, or fails outright with a PydanticUserError when @classmethod is omitted or mode="before" is misordered.
You do not need a bigger model to fix knowledge-cutoff drift—you need a live, version-aware documentation layer wired directly into your IDE, terminal, and Python agent loops. In this hands-on walkthrough, we configure Context7 by Upstash across MCP, CLI + Skills, and .cursorrules / CLAUDE.md, then build a token-budgeted, version-auditing Python retriever on top of Context7 Search API v3.
Configuring Context7 in Your IDE via MCP (npx ctx7 setup --mcp)
For interactive development inside Cursor, Claude Code, VS Code, or Windsurf, Context7 exposes a Model Context Protocol (MCP) server with two core tools: resolve-library-id and query-docs.
1. Automated Setup (Browser OAuth or API Key)
The fastest way to register the MCP server is through the official Context7 CLI:
npx ctx7 setup --mcp
Notice an important workflow distinction: interactive MCP setup supports browser-based OAuth login (eliminating manual API key copying for local IDE usage), whereas programmatic REST API calls authenticate with a Bearer API key.
2. Manual Remote HTTP Configuration (and Windows npx Fix)
If you manage .cursor/mcp.json or claude_desktop_config.json manually—or work on Windows where local npx child processes occasionally hit ENOENT path issues—connect directly to Context7's remote Streamable HTTP endpoint:
{
"mcpServers": {
"context7": {
"url": "[https://mcp.context7.com/mcp](https://mcp.context7.com/mcp)",
"headers": {
"Authorization": "Bearer YOUR_CONTEXT7_API_KEY"
}
}
}
}
If you prefer running the local stdio MCP server on Windows instead of remote HTTP, wrap npx via cmd so Windows resolves the executable path cleanly:
{
"mcpServers": {
"context7": {
"command": "cmd",
"args": [
"/c",
"npx",
"-y",
"@upstash/context7-mcp",
"--api-key",
"YOUR_CONTEXT7_API_KEY"
]
}
}
}
On-Demand Terminal Grounding With Context7 CLI + Skills
Running a persistent MCP server registers tool schemas in your agent's baseline context on every turn. When you want on-demand documentation lookups without keeping a persistent MCP server loaded, Context7 provides a CLI + Skills mode (npx ctx7 setup --cli, requiring Node.js 22.13 or later):
npx ctx7 setup --cli
Instead of registering an MCP server, ctx7 setup --cli installs a lightweight find-docs skill and rule file into your agent directory. Through progressive disclosure, your coding agent loads the skill instructions only when documentation is needed and invokes ctx7 library and ctx7 docs directly in the terminal:
npx ctx7 library pydantic
npx ctx7 docs /pydantic/pydantic "field_validator mode before"
Enforcing Automatic Grounding in .cursorrules or CLAUDE.md
Relying on developers to remember to append "use context7" to every prompt leads to inconsistent usage. Adding a short repository-level policy in .cursorrules or CLAUDE.md instructs your agent to fetch official documentation before writing framework-dependent code:
## Documentation Grounding Policy
Before writing or refactoring code that depends on external libraries or SDKs,
fetch current official documentation via Context7 (`resolve-library-id` +
`query-docs`, or `ctx7 library` + `ctx7 docs`) first.
If you already know the exact Context7 library ID (e.g., `/pydantic/pydantic`),
query it directly to skip library resolution.
Do not rely solely on training memory for decorator signatures, configuration
schemas, or version-specific imports.
Check served library versions against `pyproject.toml` or `package.json` before
finalizing generated code.
How Context7 Ingests, Screens, and Structures Library Docs
Why does Context7 outperform generic web search scrapers and raw llms.txt prompt stuffing?
-
Curated Multi-Source Ingestion: Context7 parses official documentation websites, Git repositories,
llms.txtindexes, and OpenAPI specifications into discrete executable code blocks (codeSnippets) and prose explanations (infoSnippets). - Pre-Indexing Security Screening: Documentation chunks are screened before indexing to exclude content flagged for prompt-injection or malware-related patterns.
-
Provenance & Token Metadata: Every snippet carries source identifiers (
codeId,pageId, andlibraryId) alongside separate token counts (codeTokensandcontentTokens), so your application can audit provenance and enforce strict token budgets.
(Defense-in-depth still applies: pre-indexing screening lowers the risk of poisoned documentation, but production coding agents still require sandboxed execution and gated shell permissions.)
Extending Grounding to Custom Python Agents With Search API v3
When you move from interactive IDE coding to autonomous Python agents, CI code-review bots, or internal developer tools, the Context7 Search API v3 (GET https://context7.com/api/v3/search) collapses library resolution, multi-library querying (up to four library hints per request), and snippet reranking into a single HTTP call.
In a production Python pipeline, your retriever should handle four distinct responsibilities:
-
Dual-Field Token Accounting: Track
codeTokens(forcodeSnippets) andcontentTokens(forinfoSnippets) against aretrieval_context_budget, while measuring total formatted prompt tokens separately with a model tokenizer. -
Version Provenance Auditing: Compare the requested version (
"2.14.4") against the servedlibraryIdandverifiedflag so your agent knows whether Context7 matched a pinned tag or served its rollingLatestindex. -
Complete Context Delivery: Return a short
previewslice for terminal inspection while passing the fullselected_contextlist into the LLM formatter so high-rank snippets are not dropped. -
Language-Aware Formatting: Render
codeSnippetswith their actualcodeLanguageidentifier and keepinfoSnippetsas prose rather than wrapping everything in Python fences.
Save the following implementation as context7_grounding_v2.py:
import os
import json
import httpx
API_KEY = os.environ["CONTEXT7_API_KEY"]
BASE_URL = "[https://context7.com/api/v3/search](https://context7.com/api/v3/search)"
def estimate_model_tokens(text: str, model: str = "gpt-4o-mini") -> int:
"""
Calculates total formatted prompt tokens separately from the retrieval
context budget (which measures raw snippet token counts).
"""
try:
import tiktoken
enc = tiktoken.encoding_for_model(model)
return len(enc.encode(text))
except Exception:
return max(1, len(text) // 4)
def ground_agent_query(
query: str,
libraries: list[str] | None = None,
version: str | None = None,
language: str = "Python",
context_mode: str = "standard", # "standard" or "broad"
retrieval_context_budget: int = 2200,
) -> dict:
"""
Queries Context7 Search v3, accounts for codeTokens vs. contentTokens within a
retrieval context budget, and audits requested vs. served version metadata.
"""
params: list[tuple[str, str]] = [
("query", query),
("language", language),
("type", "json"),
]
if libraries:
for lib in libraries:
params.append(("library", lib))
if version:
params.append(("version", version))
if context_mode == "broad":
params.append(("context", "broad"))
headers = {"Authorization": f"Bearer {API_KEY}"}
with httpx.Client(timeout=20.0) as client:
response = client.get(BASE_URL, params=params, headers=headers)
response.raise_for_status()
data = response.json()
tagged_snippets = []
for item in data.get("codeSnippets", []):
tagged_snippets.append({**item, "_kind": "code"})
for item in data.get("infoSnippets", []):
tagged_snippets.append({**item, "_kind": "info"})
all_snippets = sorted(tagged_snippets, key=lambda s: s.get("rank", 999))
selected_context = []
retrieval_tokens_used = 0
for snippet in all_snippets:
if snippet["_kind"] == "code":
token_count = snippet.get("codeTokens")
else:
token_count = snippet.get("contentTokens")
if token_count is None:
token_count = max(1, len(str(snippet)) // 4)
if retrieval_tokens_used + token_count > retrieval_context_budget:
continue
selected_context.append({**snippet, "_countedTokens": token_count})
retrieval_tokens_used += token_count
served_libraries = {}
for s in selected_context:
lib_id = s.get("libraryId", "unknown")
if lib_id not in served_libraries:
inferred_ver = (
s.get("servedVersion")
or s.get("version")
or lib_id.split("/")[-1]
)
is_verified = s.get("verified")
if is_verified is None:
is_verified = bool(version and version in lib_id)
served_libraries[lib_id] = {
"libraryId": lib_id,
"requestedVersion": version,
"servedVersion": inferred_ver,
"verified": is_verified,
"generationDate": s.get("generationDate"),
}
unpinned_index_served = bool(
version
and not any(
(info["verified"] or (version in info["libraryId"]))
for info in served_libraries.values()
)
)
return {
"query": query,
"context_mode": context_mode,
"snippets_returned": len(all_snippets),
"snippets_selected": len(selected_context),
"retrieval_tokens_used": retrieval_tokens_used,
"retrieval_context_budget": retrieval_context_budget,
"version_audit": {
"requested_version": version,
"unpinned_latest_served": unpinned_index_served,
"libraries_served": list(served_libraries.values()),
},
"selected_context": selected_context,
"preview": selected_context[:2],
}
def format_grounded_context_for_llm(grounded: dict) -> str:
"""
Formats all selected_context snippets (not just preview[:2]), preserving
each snippet's actual codeLanguage and prose documentation content.
"""
sections = []
if grounded["version_audit"]["unpinned_latest_served"]:
req = grounded["version_audit"]["requested_version"]
served = [
lib["libraryId"]
for lib in grounded["version_audit"]["libraries_served"]
]
sections.append(
f"[VERSION PROVENANCE NOTE] Requested version '{req}'. Context7 served "
f"rolling Latest indexes ({served}) rather than a pinned '{req}' tag. "
f"Verify patch-level compatibility if pinning an older release."
)
for idx, item in enumerate(grounded["selected_context"], start=1):
source = item.get("codeId") or item.get("pageId") or item.get("libraryId")
lib_id = item.get("libraryId", "unknown")
if item["_kind"] == "code":
title = item.get("codeTitle") or "Code Reference"
desc = item.get("codeDescription") or ""
lang = (item.get("codeLanguage") or "text").lower()
code_samples = "\n".join(
c.get("code", "") for c in item.get("codeList", [])
)
sections.append(
f"### [{idx}] {title} ({lib_id})\n"
f"Source: {source}\n"
f"{desc}\n"
f"```
{lang}\n{code_samples}\n
```"
)
else:
title = item.get("pageTitle") or "Documentation Section"
content = item.get("content") or item.get("text") or ""
sections.append(
f"### [{idx}] {title} ({lib_id})\n"
f"Source: {source}\n"
f"{content}"
)
return "\n\n".join(sections)
if __name__ == "__main__":
res = ground_agent_query(
query="How do I define a Pydantic v2 field_validator with mode='before'?",
libraries=["pydantic"],
version="2.14.4",
language="Python",
context_mode="standard",
retrieval_context_budget=2000,
)
formatted_payload = format_grounded_context_for_llm(res)
summary = {
**{k: v for k, v in res.items() if k != "selected_context"},
"formatted_context_total_tokens": estimate_model_tokens(formatted_payload),
}
print(json.dumps(summary, indent=2))
Live Telemetry Run: Understanding Pydantic 2.14.4 and Token Budgets
Running python context7_grounding_v2.py against the live Context7 v3 API returns structured telemetry:
{
"query": "How do I define a Pydantic v2 field_validator with mode='before'?",
"context_mode": "standard",
"snippets_returned": 25,
"snippets_selected": 8,
"retrieval_tokens_used": 1989,
"retrieval_context_budget": 2000,
"version_audit": {
"requested_version": "2.14.4",
"unpinned_latest_served": true,
"libraries_served": [
{
"libraryId": "/pydantic/pydantic",
"requestedVersion": "2.14.4",
"servedVersion": "pydantic",
"verified": false,
"generationDate": "2026-09-13T22:25:08.136Z"
},
{
"libraryId": "/llmstxt/pydantic_dev_ai_llms-full_txt",
"requestedVersion": "2.14.4",
"servedVersion": "pydantic_dev_ai_llms-full_txt",
"verified": false,
"generationDate": null
},
{
"libraryId": "/websites/pydantic_dev_validation",
"requestedVersion": "2.14.4",
"servedVersion": "pydantic_dev_validation",
"verified": false,
"generationDate": "2026-11-17T03:20:17.701Z"
},
{
"libraryId": "/llmstxt/pydantic_dev_llms_txt",
"requestedVersion": "2.14.4",
"servedVersion": "pydantic_dev_llms_txt",
"verified": false,
"generationDate": "2026-11-06T08:21:53.184Z"
}
]
},
"preview": [
{
"codeTitle": "Define before validator using @field_validator decorator",
"codeLanguage": "python",
"codeTokens": 216,
"codeId": "[https://github.com/pydantic/pydantic/blob/main/docs/concepts/validators.md](https://github.com/pydantic/pydantic/blob/main/docs/concepts/validators.md)",
"libraryId": "/pydantic/pydantic",
"rank": 1,
"_kind": "code",
"_countedTokens": 216
}
],
"formatted_context_total_tokens": 2442
}
Three Takeaways From This Payload
-
How
Latestvs."unverified"Works for Pydantic2.14.4: When requestingversion="2.14.4", Context7 returned/pydantic/pydanticand/websites/pydantic_dev_validationwithverified: false("unverified"). That label does not mean the documentation is older. Pydantic2.14.4is the newest release, and Context7'sLatestindex for/pydantic/pydanticalready covers the2.14line (including updates such as theMISSINGsentinel graduating from experimental status inv2.14). When a library does not publish a separate pinned tag for a requested patch version, Search v3 serves the currentLatestdocs and marks the version as"unverified"simply to indicate the source came fromLatestrather than a pinned tag—meaning the agent still received current2.14documentation. -
Snippet Budget vs. Serialized Prompt Overhead: Packing 8 ranked snippets consumed
1,989retrieval tokens—staying inside the2,000-token retrieval context budget—while adding markdown headers, source URLs, and code fences broughtformatted_context_total_tokensto2,442tokens (+453formatting tokens). Budgeting both layers prevents silent context-window creep. -
Multi-Library Expansion With
context="broad": Queryinglibraries=["fastapi", "pydantic"]withcontext_mode="broad"andretrieval_context_budget=6000returned 8 cross-library snippets totaling2,427retrieval tokens across/websites/fastapi_tiangolo_reference,/websites/fastapi_tiangolo,/pydantic/pydantic, and/llmstxt/pydantic_dev_llms_txtin one call.
Wiring Retrieval Into a Two-Turn Tool Loop With FastAPI Verification
ground_agent_query() and format_grounded_context_for_llm() wrap cleanly as tools in OpenAI Agents, Anthropic, LangGraph, or Google ADK. Below is a two-turn tool-calling loop using google-genai (gemini-3.6-flash), followed by an in-process FastAPI TestClient execution check (agent_loop_demo.py):
import os
from google import genai
from google.genai import types
from fastapi import FastAPI
from fastapi.testclient import TestClient
from context7_grounding_v2 import (
ground_agent_query,
format_grounded_context_for_llm,
)
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
def search_official_docs(
query: str,
libraries: list[str],
version: str = "2.14.4",
context_mode: str = "standard",
) -> str:
"""Retrieve version-audited official documentation and code snippets from Context7."""
grounded = ground_agent_query(
query=query,
libraries=libraries[:4],
version=version,
language="Python",
context_mode=context_mode,
retrieval_context_budget=2200,
)
return format_grounded_context_for_llm(grounded)
def run_grounded_coding_agent(task: str) -> str:
system_instruction = (
"You are a senior Python engineer. Call `search_official_docs` first to "
"inspect current framework documentation and version metadata before writing "
"code. Return a complete FastAPI script inside one python block."
)
user_msg = types.Content(
role="user",
parts=[types.Part.from_text(text=task)],
)
config = types.GenerateContentConfig(
system_instruction=system_instruction,
tools=[search_official_docs],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True),
)
# Turn 1: Model requests documentation via tool call
turn_1 = client.models.generate_content(
model="gemini-3.6-flash",
contents=[user_msg],
config=config,
)
conversation = [user_msg, turn_1.candidates[0].content]
if turn_1.function_calls:
for fc in turn_1.function_calls:
tool_result = search_official_docs(**dict(fc.args))
conversation.append(
types.Content(
role="user",
parts=[
types.Part.from_function_response(
response={"result": tool_result},
name=fc.name,
)
],
)
)
# Turn 2: Model synthesizes grounded implementation from full selected_context
turn_2 = client.models.generate_content(
model="gemini-3.6-flash",
contents=conversation,
config=config,
)
return turn_2.text or ""
Grounded on /pydantic/pydantic (@field_validator(..., mode="before") + @classmethod) and /websites/fastapi_tiangolo, the agent outputs clean Pydantic v2 code that passes an automated TestClient verification check (HTTP 200, tags == ["python", "fastapi", "pydantic"]):
from typing import Any
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, field_validator
app = FastAPI()
class ArticleCreate(BaseModel):
title: str
tags: list[str]
@field_validator("tags", mode="before")
@classmethod
def normalize_tags(cls, value: Any) -> Any:
if isinstance(value, str):
return [tag.strip() for tag in value.split(",") if tag.strip()]
return value
@app.post("/articles", response_model=ArticleCreate)
def create_article(article: ArticleCreate) -> ArticleCreate:
return article
if __name__ == "__main__":
with TestClient(app) as client:
response = client.post(
"/articles",
json={"title": "Grounding Agents", "tags": "python, fastapi, pydantic"},
)
assert response.status_code == 200
assert response.json()["tags"] == ["python", "fastapi", "pydantic"]
print("Verified response:", response.json())
Side-by-Side Comparison: Retrieval Strategies & Integration Surfaces
Retrieval Footprint on the Same FastAPI + Pydantic Task
| Strategy | Retrieval Tokens | Formatted Context Tokens | Provenance & Version Audit | Typical Outcome |
|---|---|---|---|---|
| A. Model Baseline (No Retrieval) | 0 |
Prompt only | None (static training cutoff) | Lowest token cost, but higher risk of deprecated Pydantic v1 @validator syntax or missing @classmethod. |
| B. Unfiltered Web / Index Dump (Illustrative) | ~8,000–12,000+ |
~8,500–12,500+ |
None (mixed forum/doc versions) | High latency and token burn, unranked prose, and conflicting v1/v2 syntax examples. |
| C. Context7 Search API v3 + Budgeting |
1,989 (standard) / 2,427 (broad) |
2,442 (standard) |
Explicit libraryId, codeId/pageId, and Latest vs. tag metadata |
Compact, rank-ordered code + prose snippets that pass TestClient execution on the first pass. |
Choosing Between MCP, CLI + Skills, and Search API v3
| Integration Pattern | Setup Command / Endpoint | Auth Mechanism | Baseline Context Cost | Best Fit |
|---|---|---|---|---|
| IDE MCP Server |
npx ctx7 setup --mcp (https://mcp.context7.com/mcp) |
Browser OAuth (interactive) or Bearer API key | Registers MCP tool definitions | Interactive coding inside Cursor, Claude Code, VS Code, or Windsurf. |
| CLI + Skills |
npx ctx7 setup --cli (ctx7 library, ctx7 docs) |
OAuth or CONTEXT7_API_KEY env var |
Minimal (find-docs skill loaded on demand) |
Shell-capable agents wanting on-demand lookups without a persistent MCP server. |
| Search API v3 (Python) | GET https://context7.com/api/v3/search |
Authorization: Bearer API key |
Full programmatic control (codeTokens + contentTokens) |
Custom autonomous agents, CI review bots, multi-library grounding, and strict token budgets. |
Four Operational Guardrails for Production Agents
- Treat Retrieved Docs as Untrusted Input: Context7 screens chunks before indexing to filter out prompt-injection and malware patterns, but agent runtimes should still isolate tool outputs from system instructions and gate shell or filesystem writes.
-
Log Source Provenance: Persist
libraryId,codeId/pageId, andversion_audittelemetry on every tool call so generated code remains auditable. -
Separate Snippet Budgets From Total Prompt Limits: Cap raw
codeTokensandcontentTokensfirst, then run your target model's tokenizer over the serialized prompt (including headers, tool schemas, and chat history) before calling the LLM. -
Keep API Keys Out of Version Control: Store
CONTEXT7_API_KEYand model provider keys in environment variables or secret managers rather than committed.cursor/mcp.jsonfiles.
Suggested Companion Repository Structure
context7-grounding-demo/
├── README.md # Setup instructions (MCP, CLI + Skills, and Search API v3)
├── .cursorrules # Project-level automatic documentation grounding policy
├── context7_grounding_v2.py # Search v3 retriever, dual token accounting & version audit
├── agent_loop_demo.py # Two-turn LLM tool loop + FastAPI TestClient verification
└── requirements.txt # httpx, google-genai, fastapi, pydantic>=2.14.4
Explore Context7 & Further Resources
- Context7 Setup & Library Index — Browse indexed libraries, generate an API key, or configure OAuth for MCP.
- Context7 MCP Installation Guide — Client setup instructions for Cursor, Claude Code, VS Code, Windsurf, and remote HTTP MCP.
-
Context7 Search API Reference — Parameter reference for
GET /api/v3/search, version preferences,context=broad, and token fields. - Context7 Quality and Safety — Details on pre-indexing screening for prompt-injection and malware patterns.
- Upstash Box & Upstash Redis — Pair grounded code generation with isolated cloud sandboxes and serverless agent memory.
Built with Context7 by Upstash. Abhishek Banerjee is an independent technical writer and AI engineering content strategist focused on agentic architectures, context engineering, and developer infrastructure.
💡 Need High-Impact Technical Content for Your Engineering Team?
I partner with developer-tooling startups, SaaS platforms, and engineering teams to translate complex infrastructure, agentic systems, and backend architecture into publication-grade technical writing.
📩 Email: abhishekninja2018@gmail.com
💼 LinkedIn: linkedin.com/in/abhishekninja
🐦 X (Twitter): @AvishekBanzzov
✍️ Hashnode: https://deeper-in-tech.hashnode.dev/
💻 Dev.to: dev.to/abhishekninja_writer
🛠️ Capabilities: Long-form Technical Essays | Hands-On Tutorials | Developer Tooling Deep-Dives | Technical Counter-Narratives
Top comments (0)