Bitdoze Logo

Context7 MCP: How to Build an AI Agent with Agno (2026)

Connect Agno to the Context7 MCP server and build an AI agent that fetches up-to-date library documentation and code snippets. Full step-by-step Python guide.

DragosDragos14 min read
Context7 MCP: How to Build an AI Agent with Agno (2026)

Most AI coding assistants give you answers from training data that’s months or years old. If you’ve ever gotten a hallucinated API call or a deprecated function name from ChatGPT, you know the problem. Context7 MCP fixes this by giving your AI agent live access to current library documentation and code snippets, and Agno is the agent framework that ties it all together.

MCP stands for Model Context Protocol, an open standard that lets AI agents call external tools through a uniform interface. Context7 is a service (by Upstash) that exposes documentation for thousands of libraries over MCP. Agno is a Python agent framework that handles the agent loop, tool orchestration, and streaming output.

This guide walks you through building a working AI agent in Python that fetches up-to-date library docs on demand. You’ll have a running interactive agent by the end.

Why use Context7 with Agno?

Context7 delivers up-to-date documentation and code examples optimized for LLMs. When paired with Agno, you get an agent that:

  • Dynamically fetches the latest API documentation for any library.
  • Retrieves relevant code snippets to demonstrate library usage.
  • Answers complex queries about library features, usage patterns, or troubleshooting.
  • Streamlines developer workflows by providing instant, context-aware assistance.

Here’s how it works: your Python script launches the Context7 MCP server as a local npx subprocess (stdio transport). Agno’s MCPTools class acts as the MCP client, connecting to that subprocess. When you ask the agent a question, it calls Context7’s tools (resolve-library-id, then query-docs) and returns the results as formatted Markdown.

Prerequisites

  • Python 3.12+ with uv installed
  • Node.js 18+ and npm (required by Context7’s npx command)
  • An OpenAI API key (for GPT-5.4-mini via the Responses API)
  • Optional: Context7 API key (free at context7.com/dashboard) for higher rate limits
  • Basic familiarity with Python and the command line

If you’re new to Agno, start with Getting Started with Agno Agents first. It covers installation, memory, and RAG basics.

Step 1: Set up your environment

Create a virtual environment and install the required packages:

uv venv --python 3.12
source .venv/bin/activate
uv pip install -U "agno[mcp]" openai

agno[mcp] is an extra, not a standalone package

The mcp extra on the agno package bundles the MCP client. Don’t install the standalone mcp Python package separately. That’s the MCP server SDK and can cause version conflicts with Agno’s bundled client.

Verify Node.js is available and recent enough:

node --version   # need 18+
npm --version

Set your API keys:

export OPENAI_API_KEY="sk-..."
# optional: higher Context7 rate limits
export CONTEXT7_API_KEY="ctx7_..."

Verify the install:

python -c "import agno; print(agno.__version__)"

You should see a 2.x version number. If you get ModuleNotFoundError, the virtual environment isn’t active or the install failed.

Step 2: Understand the Context7 MCP tools

The Context7 MCP server exposes two tools:

Tool Parameters Returns
resolve-library-id libraryName (required), query (required) A slash-prefixed library ID (e.g., /psf/requests)
query-docs libraryId (required), query (required) Documentation and code snippets for the library

Tool names changed in Context7 v4

If you’re following an older tutorial, the tools were renamed. The old get-library-docs is now query-docs. The old context7CompatibleLibraryID is now libraryId. The topic and tokens parameters are gone, replaced by query. These changes shipped with Context7 v4.0.0 (August 2026).

The flow is always two steps: resolve the library name to an ID, then query that ID for docs. The agent handles this automatically based on its instructions.

Context7 also offers a hosted MCP endpoint at https://mcp.context7.com/mcp if you’d rather not run the local npx subprocess. For this guide, we’ll use the local approach since it’s simpler to set up.

Step 3: Create the AI agent

Minimal agent (one-shot)

Start with the shortest possible working script to verify the integration:

import asyncio
from agno.agent import Agent
from agno.models.openai import OpenAIResponses
from agno.tools.mcp import MCPTools

async def main():
    mcp_tools = MCPTools(command="npx -y @upstash/context7-mcp@latest")
    await mcp_tools.connect()

    try:
        agent = Agent(
            model=OpenAIResponses(id="gpt-5.4-mini"),
            tools=[mcp_tools],
            markdown=True,
            show_tool_calls=True,
        )
        await agent.aprint_response(
            "How do I make a GET request with the requests library?", stream=True
        )
    finally:
        await mcp_tools.close()

asyncio.run(main())

Save this as main.py and run it:

python main.py

OpenAIResponses vs OpenAIChat

Agno’s OpenAIResponses class uses OpenAI’s Responses API (the successor to Chat Completions). The older OpenAIChat class still works but targets the legacy Chat Completions API. GPT-4.1-mini and GPT-4.1 were retired from ChatGPT in February 2026. gpt-5.4-mini is the current fast/cheap model. Use gpt-5.4 for harder queries.

If this runs and you see tool calls followed by documentation output, the integration works. Move on to the full interactive script.

Full interactive script

Here’s the complete script with an interactive loop, error handling, and clean connection lifecycle:

import os
import asyncio
from agno.agent import Agent
from agno.models.openai import OpenAIResponses
from agno.tools.mcp import MCPTools

if "OPENAI_API_KEY" not in os.environ:
    raise ValueError("OPENAI_API_KEY environment variable is not set.")

INSTRUCTIONS = '''
You help users find up-to-date library documentation and code snippets via Context7.

When a user asks about a library:
1. Call `resolve-library-id` with `libraryName` set to the library name
   and `query` set to the user's full question.
2. Take the Context7 library ID it returns (slash-prefixed) and call
   `query-docs` with `libraryId` set to that ID and `query` set to the
   user's question/topic.
3. Return the documentation and code snippets in clear, concise Markdown.
Always explain which tools you called and show the results.
'''

async def main():
    mcp_tools = MCPTools(command="npx -y @upstash/context7-mcp@latest")
    await mcp_tools.connect()

    try:
        agent = Agent(
            name="Agno Context7 Doc Agent",
            role="An AI assistant that fetches up-to-date docs and code snippets using Context7 MCP.",
            model=OpenAIResponses(id="gpt-5.4-mini"),
            tools=[mcp_tools],
            instructions=INSTRUCTIONS,
            show_tool_calls=True,
            add_state_in_messages=True,
            markdown=True,
        )
        print("Agno Context7 Documentation Agent\n---------------------------------")
        print("Ask about a library. Type 'exit' or 'quit' to stop.\n")
        while True:
            user_input = input("\nYou: ").strip()
            if user_input.lower() in {"exit", "quit"}:
                print("Goodbye!")
                break
            try:
                await agent.aprint_response(user_input, stream=True)
            except Exception as e:
                print(f"\nError: {e}")
    finally:
        await mcp_tools.close()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nInterrupted. Exiting.")

A few things to note about this script:

  • try/finally ensures mcp_tools.close() runs even if the script is interrupted. Without this, the npx subprocess can leak.
  • Instructions are tool-agnostic. They reference the tool names but don’t hardcode parameter schemas. If Context7 renames a parameter in a future version, the agent will still work because it reads the tool descriptions from the MCP server.
  • add_state_in_messages=True lets the agent maintain conversation context across turns.

Passing a Context7 API key

If you have a Context7 API key (free at context7.com/dashboard), pass it to the MCP server via the env parameter:

mcp_tools = MCPTools(
    command="npx -y @upstash/context7-mcp@latest",
    env={"CONTEXT7_API_KEY": os.getenv("CONTEXT7_API_KEY")},
)

This gives you higher rate limits on the free tier.

Step 4: Verify it works

After running the full script, test with a few queries:

You: requests how to make a GET request

You should see:

  1. The agent calls resolve-library-id with libraryName="requests" and query="how to make a GET request".
  2. It receives a slash-prefixed library ID (something like /psf/requests, the exact ID depends on Context7’s index).
  3. It calls query-docs with that library ID and the query.
  4. It streams back formatted documentation and code snippets.

Working correctly

If you see tool calls listed (with show_tool_calls=True) followed by documentation output in Markdown, the agent is working. Try a few more queries: numpy array operations, fastapi dependency injection, react useEffect cleanup.

If the agent responds without calling any tools, check that tools=[mcp_tools] is set and that mcp_tools.connect() completed without errors.

Troubleshooting and costs

npx: command not found

Node.js isn’t installed or isn’t in your PATH. Install Node 18+ via nvm:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
nvm install 22

Verify with node --version.

ModuleNotFoundError: agno

You didn’t install the agno[mcp] extra, or the virtual environment isn’t active. Run:

source .venv/bin/activate
uv pip install -U "agno[mcp]" openai
Rate limit / HTTP 429 errors

You’ve hit Context7’s free tier limit (1,000 API calls/month). Get a free API key at context7.com/dashboard and pass it via the env parameter as shown in Step 3. The key raises your rate limits. If you need more, the Pro plan is $10/seat/month with 5,000 calls/seat included.

Tool call errors / schema mismatch

Context7 upgraded to v4.0.0 in August 2026 with new tool schemas. If you’re pinning @upstash/[email protected] but your instructions reference v4 tool names (or vice versa), tool calls will fail. The fix: use @latest or pin to @4.0.3, and keep instructions tool-agnostic as shown in Step 3.

MCP server unreachable

The npx subprocess crashed or Node is too old. Agno v2.7.3+ surfaces a clear error message. Check that node --version shows 18+ and that you have an active internet connection (the first npx run downloads the package).

Stale subprocess / connection leak

If you don’t call mcp_tools.close(), the stdio subprocess may hang around. Always use the try/finally pattern shown in Step 3. The async with MCPTools(command) as mcp_tools: context manager is a valid alternative that handles this automatically.

Context7 pricing

Plan API calls/month Price
Free 1,000 (public repos only) $0
Pro 5,000/seat + $10/1,000 additional $10/seat/month

The free tier was reduced in early 2026. An API key is strongly recommended even on the free plan. It gives you higher rate limits. Get one at context7.com/dashboard.

Model costs

GPT-5.4-mini costs roughly $0.75 per million input tokens and $4.50 per million output tokens. A typical doc-query round-trip (2-3 tool calls plus the final response) costs fractions of a cent. For complex multi-library reasoning, gpt-5.4 is available but more expensive.

Pinning vs @latest

Using @latest means a Context7 major version bump can change tool schemas under you. This already happened with v4.0.0. For reproducible setups, pin a version:

npx -y @upstash/[email protected]

Trade-off: pinned is stable but won’t auto-fix bugs; @latest is current but may break on major releases.

@latest can break on major bumps

Context7 v4.0.0 changed tool names and parameter schemas. If you pin @3.x and your agent instructions reference v4 tools, nothing will work. Keep your instructions generic (as shown in Step 3) so they survive schema changes.

Best practices and optimization

  • Tool-agnostic instructions. Don’t hardcode MCP tool parameter names in agent instructions. They change across Context7 versions. The instructions in Step 3 are deliberately generic.
  • Cache library IDs. If you query the same library repeatedly, cache the ID returned by resolve-library-id to skip a round-trip.
  • Error handling. Wrap aprint_response in try/except. Log errors for debugging.
  • Model selection. gpt-5.4-mini for most queries (fast, cheap). gpt-5.4 for complex multi-library reasoning.
  • Security. Validate user inputs. Don’t pass raw user text into shell commands.
  • Telemetry. Set AGNO_TELEMETRY=false to disable Agno’s telemetry if you prefer.
  • Connection lifecycle. Always close() MCP tools in a finally block to avoid subprocess leaks.

If you’re deciding between MCP tools and Agno’s built-in tools, see MCP vs native tools for a comparison of when each approach makes sense.

Other MCP servers and Agno toolkit

The MCP ecosystem has grown significantly. Hundreds of servers are now available through the official MCP registry. You can connect Agno to any of them using the same MCPTools pattern. A few examples:

  • BrightData MCP for web scraping: Access web data at scale through an MCP interface. Bright Data provides the web data platform behind it.
  • Supabase MCP: Query and manage your Supabase databases.
  • Airtable MCP: Interact with Airtable bases programmatically.

Agno also has its own toolkit with built-in tools (web search, file operations, etc.) that don’t require MCP. See the Agno tools documentation for the full list.

Note: MultiMCPTools (for connecting multiple MCP servers) is deprecated. Use multiple MCPTools instances instead, each with its own connect()/close() lifecycle.

Final thoughts

Agno plus Context7 MCP gives you an AI agent with access to current library documentation — no stale training data, no hallucinated API calls. The agent resolves library names to IDs, queries live docs, and streams back formatted results.

A few ways to extend this:

  • Multiple MCP servers. Add more MCPTools instances for different documentation sources.
  • Specialized agents. Build domain-specific agents for web development, data science, or DevOps. See AI Research Squad with Agno for a multi-agent approach.
  • Agno Workflows. Chain this agent into a larger pipeline with Agno Workflows.
  • Hosted endpoint. Skip local Node.js entirely by using Context7’s hosted MCP endpoint at https://mcp.context7.com/mcp.
  • CLI alternative. Try the ctx7 CLI (npx ctx7 setup) for a no-MCP setup.
  • Discord bot. Wrap this agent in a Discord bot — see build a Discord AI bot with Agno.

If you’re exploring other agent frameworks, you can also build an AI agent with Mastra (TypeScript-based).

Getting Started with Agno Agents