# How to Ground AI Coding Agents in Versioned Documentation with Context7

*A hands-on engineering walkthrough of Context7 MCP, CLI + Skills, and Search API v3 with dual-field token accounting, version-mismatch auditing, and an end-to-end Python tool loop.*

> **Disclosure:** This tutorial was sponsored by [Upstash](https://upstash.com/?utm_source=abhishek-banerjee). All 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`.

---

## Why Do AI Coding Agents Hallucinate Outdated Library APIs?

AI coding agents hallucinate outdated APIs because their parametric model weights are frozen at a static training cutoff while open-source libraries ship breaking changes every month.

Consider a common task in a modern Python backend repository: asking an AI coding agent to add a pre-validation normalizer to a FastAPI request model using Pydantic v2 (`2.14.4`, released in November 2026).

Without live documentation grounding, a coding agent frequently falls back on high-frequency patterns from older training data and emits Pydantic v1 syntax:

```python
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 this code against modern Pydantic v2 triggers a deprecation warning at best, or breaks outright when combined with v2 configuration options and strict validation modes:

```text
PydanticDeprecatedSince20: Pydantic V1 style `@validator` validators are deprecated.
You should migrate to Pydantic V2 style `@field_validator` validators, see the
migration guide for more details. Deprecated in Pydantic V2.0 to be removed in V3.0.

```

Even when an agent knows `@field_validator` exists, it often forgets `@classmethod` or misorders `mode="before"`, producing a `PydanticUserError` at import time.

This happens because **parametric model weights are static snapshots**, while open-source libraries ship breaking changes, new decorator signatures, and revised configuration schemas every month. Upgrading to a larger foundation model does not solve knowledge cutoff drift; fixing the **context layer** between the LLM and official library documentation does.

---

## Why Do Generic Web Search and Prompt Stuffing Fail for Coding Agents?

When engineering teams try to fix documentation drift, they usually reach for one of two patterns both of which introduce new failure modes:

1. **Generic Web Search Scrapers:** Querying general search engines returns a mix of outdated Stack Overflow threads, third-party blog posts written for older major versions, and unranked HTML boilerplate. Feeding 8,000–12,000 tokens of raw scraped web pages into an agent’s context window inflates latency, increases cost, and can introduce conflicting syntax examples.
2. **Unfiltered Prompt Stuffing (**`llms.txt` **or Full Docs Dumps):** Dumping entire documentation indexes into the system prompt consumes thousands of tokens on unrelated modules, degrading attention on the specific function signature the agent actually needs.

Furthermore, teams often confuse **retrieval context budget** (the tokens occupied by the retrieved documentation snippets themselves) with **total LLM request tokens** (which also include snippet titles, source URLs, markdown code fences, system instructions, tool schemas, user prompts, and prior conversation turns). Reliable agent pipelines measure and budget both separately.

---

## How Does Context7 Ingest, Rank, and Filter Library Documentation?

[Context7](https://upstash.com/?utm_source=abhishek-banerjee) by [Upstash](https://upstash.com/?utm_source=abhishek-banerjee) acts as a dedicated documentation grounding layer built specifically for coding agents. Rather than returning raw HTML pages, Context7 parses, structures, ranks, and token-counts library documentation before it reaches your model.

```text
+-------------------------------------------------------------------------+
|                        DEVELOPER / AGENT WORKFLOW                       |
|  [ IDE via MCP ]       [ Terminal via CLI + Skills ]    [ Python Agent ]|
+---------+-----------------------+-----------------------------+---------+
          |                       |                             |
          v                       v                             v
+-------------------------------------------------------------------------+
|                    CONTEXT7 RETRIEVAL & GROUNDING LAYER                 |
|  * Source Ecosystem: Git repos, official docs, llms.txt, OpenAPI specs  |
|  * Pre-Indexing Screening: Prompt-injection & malware pattern filtering |
|  * Ranking & Metadata: codeTokens, contentTokens, version & source IDs  |
+------------------------------------+------------------------------------+
                                     |
                                     v
+-------------------------------------------------------------------------+
|                 APPLICATION VERIFICATION & EXECUTION LOOP               |
|  1. Version Audit (requestedVersion vs. servedVersion / verified flag)  |
|  2. Retrieval Context Budget Packing (codeTokens + contentTokens)       |
|  3. Documentation-Grounded Code Generation -> Automated Test Execution  |
+-------------------------------------------------------------------------+

```

### Source Ecosystem and Security Posture

Understanding how [Context7](https://upstash.com/?utm_source=abhishek-banerjee) ingests and filters documentation helps you design safer agent guardrails:

- **Curated Multi-Format Ingestion:** [Context7](https://upstash.com/?utm_source=abhishek-banerjee) indexes documentation from Git repositories, official documentation websites, `llms.txt` files, and OpenAPI specifications, structuring them into discrete code snippets (`codeSnippets`) and prose explanations (`infoSnippets`).
- **Pre-Indexing Security Screening:** Documentation chunks are analyzed before indexing to exclude content flagged for prompt-injection or malware-related patterns.
- **Source Provenance and Rules:** Every returned snippet includes source identifiers (`codeId`, `pageId`, and `libraryId`) alongside library-specific or teamspace rules when configured, allowing your application to trace exactly where an example originated.
- **Defense-in-Depth Still Applies:** Pre-indexing screening reduces the risk of poisoned documentation, but no static filter guarantees complete immunity against indirect prompt injection. Production coding agents still require sandboxed execution, restricted tool permissions, and human approval before running destructive commands.

---

## How Do You Connect Context7 to Cursor, Claude Code, or VS Code via MCP?

### Interactive IDE Grounding Through MCP

For interactive coding 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`.

### Automated Setup (OAuth or API Key)

The fastest way to configure MCP is via the official CLI (`npx ctx7 setup --mcp`):

```bash
npx ctx7 setup --mcp

```

Notice an important distinction in authentication workflows: **interactive MCP installation supports browser-based OAuth login** (eliminating manual key copying for local IDE usage), whereas **programmatic REST API calls use a** `Bearer` **API key**.

### Manual MCP Configuration (Remote HTTP and Windows Fallback)

If you manage MCP configurations manually or work on Windows where local `npx` child processes occasionally hit `ENOENT` path issues connect directly to Context7’s remote Streamable HTTP endpoint:

```json
{
  "mcpServers": {
    "context7": {
      "url": "https://mcp.context7.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_CONTEXT7_API_KEY"
      }
    }
  }
}

```

*(If you prefer running the local stdio MCP server on Windows, invoke it through* `cmd` *with* `"command": "cmd"` *and* `"args": ["/c", "npx", "-y", "@upstash/context7-mcp", "--api-key", "YOUR_CONTEXT7_API_KEY"]`*.)*

---

## How Does Context7 CLI + Skills Retrieve Docs Without a Persistent MCP Server?

### On-Demand Documentation Retrieval Through 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 retrieval without a persistent MCP server**, Context7 provides a CLI + Skills mode (`npx ctx7 setup --cli`, requiring Node.js 22.13 or later):

```bash
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’s directory. Through progressive disclosure, your agent loads the skill instructions only when documentation is needed and runs `ctx7 library` and `ctx7 docs` directly in the shell:

```bash
npx ctx7 library pydantic
npx ctx7 docs /pydantic/pydantic "field_validator mode before"

```

---

## How Do You Enforce Automatic Documentation Grounding in .cursorrules or [CLAUDE.md](http://CLAUDE.md)?

### Project-Level Documentation Grounding Rules

Relying on developers to remember to append `"use context7"` to every prompt leads to inconsistent usage. Adding a repository-level grounding policy in `.cursorrules` or `CLAUDE.md` instructs the agent to retrieve documentation before writing framework-dependent code:

```markdown
## 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.

```

---

## What Does Context7 Search API v3 Provide for Custom Python Agents?

## Context7 Search API v3 Architecture and Advanced Retrieval

When you are building custom autonomous agents, CI code-review bots, or internal developer tools in Python, the [Context7 Search API v3](https://context7.com/docs/search-api?utm_source=abhishek-banerjee) (`GET [https://context7.com/api/v3/search](https://context7.com/api/v3/search)`) collapses library resolution, multi-library querying, and snippet reranking into a single HTTP request.

Key capabilities in Search API v3 include:

- **Single-Call Cross-Library Retrieval:** Pass up to four `library` hints (for example, `library=fastapi` and `library=pydantic`), and Context7 resolves relevant indexes in parallel and reranks the combined evidence.
- **Dual-Field Token Accounting:** Structured JSON responses (`type=json`) report exact token counts using two distinct fields depending on snippet type:
- `codeTokens` for executable code entries inside `codeSnippets`.
- `contentTokens` for prose documentation entries inside `infoSnippets`.
- **Version Preferences and Metadata:** Supplying `version=2.14.4` acts as a version preference, while the response exposes `libraryId` and version metadata so your code can inspect what version was actually served.
- **Standard Retrieval vs.** `context=broad`**:** By default, Search v3 returns concise, high-rank snippets optimized for targeted API lookups. Passing `context=broad` instructs Context7 to append roughly 3,500 additional tokens of surrounding documentation sections useful when an engineering task spans multiple interconnected concepts (such as combining FastAPI dependency injection, custom exception handlers, and Pydantic validators in one pass).

---

## How Do You Build a Token-Budgeted, Version-Auditing Retriever in Python?

### Building a Token-Aware, Version-Auditing Python Retriever

Many tutorials stop at printing raw JSON from `curl`. In a production Python agent, your retriever should handle four separate engineering responsibilities:

1. **Dual-Field Token Accounting:** Read `codeTokens` for `codeSnippets` and `contentTokens` for `infoSnippets` against a `retrieval_context_budget`, while measuring total formatted prompt tokens separately.
2. **Version-Mismatch Auditing:** Compare the requested `version` (e.g., `"2.14.4"`) against the served `libraryId` and verification metadata. Retrieving documentation and verifying that the index matches your target dependency version are two distinct checks.
3. **Complete Context Delivery:** Return a short `preview` for terminal inspection, but pass the **entire** `selected_context` list to the LLM formatter so high-rank snippets are not accidentally dropped.
4. **Multi-Language and Prose Preservation:** Format `codeSnippets` using their actual `codeLanguage` identifier and preserve `infoSnippets` prose instead of wrapping every chunk in \`\`\`\`python\` fences.

Save the following implementation as `context7_grounding_v2.py`:

```python
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"),
            }

    version_mismatch = 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,
            "version_mismatch_detected": version_mismatch,
            "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"]["version_mismatch_detected"]:
        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"indexes ({served}) with verified=False (Latest index rather than a pinned "
            f"tag). Pydantic 2.14.4 is covered under the current Latest index; verify "
            f"specific patch details only 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))

```

---

## What Does Live Context7 Search v3 Telemetry Look Like in Practice?

### Inspecting Retrieved Documentation and Version Provenance

Running `python context7_grounding_v2.py` against the live Context7 v3 endpoint produces the following structured telemetry (truncated to the first preview snippet for readability):

```json
{
  "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",
    "version_mismatch_detected": 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 Practical Engineering Takeaways From This Payload

1. **Version Mismatch Detection Caught an Unpinned Index:** We requested `version="2.14.4"`, and Context7 returned its primary `/pydantic/pydantic` and `/websites/pydantic_dev_validation` indexes (`verified: false`) rather than a dedicated `/pydantic/pydantic/v2.14.4` tag. Because `version_mismatch_detected` flagged `true`, our formatter injects a `[VERSION AUDIT WARNING]` directly into the prompt so the agent knows to verify patch-level release notes rather than blindly assuming an exact tag match.
2. **Retrieval Budget vs. Full Formatted Tokens:** The 8 selected snippets consumed `1,989` retrieval tokens (staying inside the `2,000`\-token retrieval context budget), while adding titles, source URLs, and markdown fences brought `formatted_context_total_tokens` to `2,442` tokens.
3. `context="broad"` **Multi-Library Expansion:** When we queried `libraries=["fastapi", "pydantic"]` with `context_mode="broad"` and `retrieval_context_budget=6000` for a combined FastAPI + Pydantic validation task, Context7 returned 8 cross-library snippets totaling `2,427` retrieval tokens across `/websites/fastapi_tiangolo_reference`, `/websites/fastapi_tiangolo`, `/pydantic/pydantic`, and `/llmstxt/pydantic_dev_llms_txt`.

```markdown
### Clarifying Pydantic `2.14.4`, `Latest`, and `"unverified"` Status

When querying Context7 for Pydantic with `version="2.14.4"`, receiving an `"unverified"` (`verified: false`) status or a `Latest` index match does **not** mean the documentation is older or pulled from a legacy release. Pydantic `2.14.4` is the latest release, and Context7's `Latest` index already covers the `2.14` release line—including updates such as the `MISSING` sentinel graduating from experimental status in `v2.14`. When a library does not publish a separate version-pinned tag for a specific patch release, Context7 serves the current `Latest` docs and marks `verified: false` simply to indicate that the match came from `Latest` rather than a pinned patch tag—meaning the agent still receives current `2.14` documentation.
```

![Live execution of context7_grounding_v2.py showing retrieval token accounting (1,989 tokens) and automated version-mismatch detection when requesting Pydantic 2.14.4.](https://cdn.hashnode.com/uploads/covers/6aaebe5d85113f9f5e54dbec/362678cb-dbfc-4a59-b756-03eaa8a74f4f.jpg align="center")

![Returned libraryId provenance, index generation timestamps, and rank-1 snippet metadata from Context7 Search API v3.](https://cdn.hashnode.com/uploads/covers/6aaebe5d85113f9f5e54dbec/e7082a2d-2f34-40b2-9c5e-0de86ee65dc8.jpg align="center")

![Comparing per-snippet codeTokens against total serialized prompt tokens (formatted_context_total_tokens: 2442).](https://cdn.hashnode.com/uploads/covers/6aaebe5d85113f9f5e54dbec/5046017d-5fef-46fb-a9b2-8e53d99a88a4.jpg align="center")

![Multi-library retrieval across FastAPI and Pydantic using context="broad" (2,427 retrieval tokens across 8 ranked snippets).](https://cdn.hashnode.com/uploads/covers/6aaebe5d85113f9f5e54dbec/e9f7d1ff-30d7-479c-be51-e218b06fbbb5.jpg align="center")

---

## How Do You Wire Context7 Retrieval Into a Two-Turn LLM Tool Loop?

### Wiring Retrieval Into an Actual LLM Agent Loop

`ground_agent_query()` and `format_grounded_context_for_llm()` are framework-independent Python functions that can be wrapped as tools in OpenAI Agents, Anthropic, LangGraph, or Google ADK. Below is a concrete two-turn tool-calling integration using the official `google-genai` SDK (`gemini-3.6-flash`), followed by an in-process FastAPI `TestClient` execution check:

```text
Developer Request
       |
       v
   LLM Agent (Turn 1: Tool Call)
       |
       v
 search_official_docs()
       |
       v
 Context7 Search API v3 (FastAPI + Pydantic)
       |
       v
 Version Audit & Full selected_context Formatting
       |
       v
   LLM Agent (Turn 2: Grounded Generation)
       |
       v
 FastAPI TestClient Execution Check

```

```python
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(
                            name=fc.name,
                            response={"result": tool_result},
                        )
                    ],
                )
            )

    # 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 Output Verified Against FastAPI and Pydantic `2.14.4`

When grounded on the retrieved `/pydantic/pydantic` (`@field_validator(..., mode="before")` + `@classmethod`) and `/websites/fastapi_tiangolo` snippets, the agent produces clean, idiomatic Pydantic v2 code that passes an in-process `TestClient` check (`HTTP 200`, `tags == ["python", "fastapi", "pydantic"]`):

```python
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())

```

---

## How Does Context7 Search v3 Compare Against Unfiltered Web Dumps and No Retrieval?

### Evaluating Context Strategies Side-by-Side

To evaluate how retrieval choices affect token overhead and code reliability on the exact same task (*implementing a FastAPI* `POST /articles` *endpoint with a Pydantic v2* `field_validator` *normalizing comma-separated tags*), compare three retrieval strategies.

*Note on measurements:* [*Context7*](https://upstash.com/?utm_source=abhishek-banerjee) *retrieval token counts below (*`1,989` *retrieval tokens /* `2,442` *formatted tokens in standard mode;* `2,427` *retrieval tokens in* `broad` *mode) come directly from our live Search v3 API runs; generic web/index dump sizes and runtime outcomes represent typical observed ranges across unbudgeted retrieval pipelines and vary by model and prompt wrapper.*

| Strategy | Retrieval Tokens | Total Formatted Context | Version Verification | Signal-to-Noise & Typical Outcome |
| --- | --- | --- | --- | --- |
| **A. Model Baseline (No Retrieval)** | `0` | Prompt only | None (static training cutoff) | Low token cost, but higher risk of Pydantic v1 `@validator` syntax or missing `@classmethod` on newer APIs. |
| **B. Unfiltered Web / Index Dump** | `~8,000–12,000+` (illustrative) | `~8,500–12,500+` | None (mixed forum/doc versions) | High token overhead, unranked prose, and potential conflicts between v1 and v2 examples. |
| **C. Context7 Search v3 + Audit** | `1,989` (standard) / `2,427` (`broad`) | `2,442` (standard) | Explicit (`requestedVersion` vs. `servedVersion`) | Compact, rank-ordered code + prose snippets with source IDs and version-mismatch warnings; runs cleanly on first pass. |

---

## When Should You Choose Context7 MCP, CLI + Skills, or Search API v3?

### Architectural Decision Matrix

Each [Context7](https://upstash.com/?utm_source=abhishek-banerjee) integration surface fits a distinct engineering workflow. Choose based on where your agent runs and how tightly you need to control token budgets and version checks (actual latency and token counts vary by query complexity and budget settings):

| Integration Pattern | Setup Command / Endpoint | Auth Mechanism | Baseline Context Cost | Best Fit |
| --- | --- | --- | --- | --- |
| [**IDE MCP Server**](https://context7.com/docs?utm_source=abhishek-banerjee) | `npx ctx7 setup --mcp` (`[https://mcp.context7.com/mcp](https://mcp.context7.com/mcp)`) | OAuth (interactive) or `Bearer` API key | Registers MCP tool definitions | Interactive coding in Cursor, Claude Code, VS Code, or Windsurf. |
| [**Context7 CLI + Skills**](https://context7.com/?utm_source=abhishek-banerjee) | `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. |
| [**Context7 Search API v3 (Python)**](https://context7.com/docs/search-api?utm_source=abhishek-banerjee) | `GET [https://context7.com/api/v3/search](https://context7.com/api/v3/search)` | `Authorization: Bearer` API key | Full programmatic control (`codeTokens` + `contentTokens`) | Custom AI agents, CI review bots, multi-library grounding, and strict version auditing. |

---

## What Security and Operational Guardrails Do Grounded Coding Agents Need?

### Production Guardrails and Security Considerations

Before deploying a documentation-grounded coding agent into CI or production repositories, enforce four operational guardrails:

1. **Treat Retrieved Documentation as Untrusted Input:** Context7’s pre-indexing screening filters out known prompt-injection and malware patterns before indexing, which lowers risk but your agent runtime should still isolate tool outputs from system instructions and avoid granting unrestricted shell or filesystem write permissions without review.
2. **Audit Source Provenance and Index Status:** Log `libraryId`, `codeId` / `pageId`, and `version_audit` telemetry on every tool call. Remember that `verified: false` with a `Latest` index indicates an unpinned `Latest` match rather than stale documentation current releases like Pydantic `2.14.4` are already reflected in the `Latest` index, so treat version audit logs as provenance context rather than an automatic error.
3. **Separate Retrieval Budgets From Model Context Limits:** Cap raw snippet tokens via `codeTokens` and `contentTokens` first, then measure the serialized prompt (including headers, tool schemas, and chat history) with your target model’s tokenizer before calling the LLM.
4. **Rotate Keys and Scrub Terminal Logs:** Keep `CONTEXT7_API_KEY` and model provider keys in environment variables or secret managers rather than committed `.cursor/mcp.json` files, and clear terminal history before sharing debugging screenshots.

---

## What Makes a Documentation-Grounded Coding Agent Reliable in Production?

### Engineering Conclusions

Grounding an AI coding agent in live documentation transforms how it handles fast-moving frameworks moving it from guessing decorator signatures out of stale training weights to synthesizing code from ranked, source-attributed documentation snippets.

Yet **documentation retrieval is only one part of a reliable coding-agent architecture**. Pairing [Context7 Search v3](https://context7.com/docs/search-api?utm_source=abhishek-banerjee) with explicit version-mismatch verification, dual-field `codeTokens` / `contentTokens` budgeting, source provenance logging, and automated `TestClient` execution completes the engineering loop so generated code is both current and verified before it reaches production.

### Suggested Companion Repository Layout

To make this implementation easy for your team to clone and test locally, organize the files as follows:

```text
context7-grounding-demo/
├── README.md                    # Setup instructions (MCP, CLI + Skills, and Python 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

```

### Try Context7 & Explore Further

If you want to wire Context7 into your own IDE, CLI workflow, or Python agent pipeline, start with the official setup portals and engineering deep dives below:

#### Documentation, Setup & SDKs

- [**Context7 Setup & Library Index**](https://context7.com?utm_source=abhishek-banerjee) - Browse indexed libraries, grab an API key, or configure interactive OAuth for MCP.
- [**Context7 Search API Reference**](https://context7.com/docs/search-api?utm_source=abhishek-banerjee) - Full parameter reference for `GET /api/v3/search`, version preferences, `context=broad`, and token fields.
- [**Context7 SDK for Agents**](https://upstash.com/blog/context7-sdk-for-agents?utm_source=abhishek-banerjee) - Official TypeScript SDK patterns for integrating documentation retrieval directly into agentic runtimes.
- [**Context7 MCP Architecture**](https://upstash.com/blog/context7-mcp?utm_source=abhishek-banerjee) - How `resolve-library-id` and `query-docs` expose versioned documentation over the Model Context Protocol.

#### Search Benchmarks & Underlying Infrastructure

- [**Context7 Search: Grounding Coding Agents on WebCode**](https://upstash.com/blog/context7-search-webcode?utm_source=abhishek-banerjee) - Engineering breakdown of how Search API v3 ranks code and prose snippets for coding tasks.
- [**Context7 vs. Web Search Benchmarks**](https://upstash.com/blog/context7-vs-web-search-benchmark?utm_source=abhishek-banerjee) - Empirical comparison of token efficiency and answer accuracy against general search tools.
- [**Context7 vs. Exa 3.0 on WebCode**](https://upstash.com/blog/context7-vs-exa?utm_source=abhishek-banerjee) - Side-by-side retrieval quality and context-window footprint evaluation.
- [**How Redis Search Powers Context7**](https://upstash.com/blog/how-redis-search-powers-context7?utm_source=abhishek-banerjee) - Under-the-hood look at how Upstash indexes and queries documentation chunks at low latency.

#### Security, Authentication & Enterprise Deployment

- [**Context7 Quality and Safety**](https://upstash.com/blog/context7-quality-and-safety?utm_source=abhishek-banerjee) - Details on pre-indexing screening for prompt-injection and malware patterns across indexed sources.
- [**What Your Search Tool Sends Your Coding Agent**](https://upstash.com/blog/what-search-hands-your-agent?utm_source=abhishek-banerjee) - Analysis of unsafe passages and context noise across different agent search backends.
- [**MCP OAuth Implementation Guide**](https://upstash.com/blog/mcp-oauth-implementation?utm_source=abhishek-banerjee) - How browser-based OAuth authentication works for interactive MCP clients.
- [**Context7 Enterprise & Private Documentation**](https://upstash.com/blog/context7-enterprise?utm_source=abhishek-banerjee) - Options for indexing private repositories, teamspace rules, and air-gapped workflows.
  - [**Local Feel, Cloud Isolation: Running Coding Agents on Upstash Box Without the Latency Tax**](https://dev.to/abhishekninja_writer/local-feel-cloud-isolation-running-coding-agents-on-upstash-box-without-the-latency-tax-55m2) - Extends Section 13 by showing how to isolate and execute agent-generated code inside low-latency cloud sandboxes.
  - [**Zero-Hop Agent Memory: Architecting Shared State Across Distributed Agents with Upstash Redis**](https://dev.to/abhishekninja_writer/zero-hop-agent-memory-architecting-shared-state-across-distributed-agents-with-upstash-redis-2o2o) - Complements Section 10 by demonstrating how to persist tool telemetry, session context, and cross-agent state in serverless Redis.
  - [**Context7: Engineering Real-Time Truth for AI Code Generation (Medium)**](https://medium.com/@abhishekninja2018/context7-engineering-real-time-truth-for-ai-code-generation-4d0c8abb9742) - A conceptual overview of real-time documentation grounding for readers looking for a higher-level introduction alongside this Search API v3 implementation guide.

---

*Built with* [*Context7*](https://context7.com?utm_source=abhishek-banerjee) *by* [*Upstash*](https://upstash.com?utm_source=abhishek-banerjee)*. Abhishek Banerjee is an independent technical writer and AI engineering content strategist focused on agentic architectures, context engineering, and developer infrastructure.*

---
