Using MCP Servers

Now that we have a general understanding of how MCP works, let’s learn how to use it.

We’ll get up and running with Claude Desktop as an MCP client and connect to the Context7 MCP server, and then explain how to integrate with MCP as a developer using Python.

This Lesson Will Cover
  • 🖥️ Connecting Claude Desktop to the Context7 MCP Server
  • 🔍 Inspecting and testing tools with MCP Inspector
  • 🐍 Calling Context7 from Python using the mcp library
  • 🤖 Using Context7 in agent workflows with LangGraph

Prerequisites

This lesson is going to be hands-on! (it’s optional, but highly recommended)

We’ll start by installing the following:

Tool Version / Notes
Claude Desktop Or you can use any MCP Host of your choosing, e.g. Cursor, Continue (VS Code plugin), etc…
Node.js + npx npx comes bundled with Node.js. We’ll need npx to install and run Context7.

Installing Claude Desktop

Download and install the app from claude.ai/download

Installing Node.js and npx

Check if Node.js and npx are available by running these commands:

node --version   # ideally >= v20.x.x (at least >= v18.0.0)
npx --version

Ensure these are installed before continuing.[1]

Connecting Claude Desktop to Context7

Now let’s configure Claude Desktop to use Context7.

What is Context7?

Context7 is an MCP server for code documentation. Once you connect it, you can ask something like:

Create a basic FastAPI api that serves data from a postgres database. use context7

Note the ending of the prompt: use context7, which will guide the AI tool to use Context7 MCP.

Configure MCP for Claude Desktop

Generally speaking, MCP servers are setup using JSON configuration files.

For Claude Desktop, this file is named claude_desktop_config.json

On MacOS, you should be able to find it in ~/Library/Application\ Support/Claude/claude_desktop_config.json

  1. Open Claude Desktop → Settings → Developer → Edit Config
    This should bring you to the location of claude_desktop_config.json. Open that file.

  2. Locate (or add) the "mcpServers" section
    If it doesn’t exist, create it at the top level.

  3. Insert the Context7 entry

    {
      // other config fields ...
      "mcpServers": {
        "Context7": {
          "command": "npx",
          "args": ["-y", "@upstash/context7-mcp"]
        }
      }
    }
    

    - "Context7" is the identifier Claude will show under Integrations.
    - "command": "npx" tells Claude to invoke npx. If your shell cannot find npx, replace "npx" with the full path, which you can find by running which npx in the terminal (e.g. "/Users/you/.npm-global/bin/npx").
    - ["-y", "@upstash/context7-mcp"] ensures npx pulls and runs the Context7 MCP package while skipping the manual installation steps.

  4. Save the file and Restart Claude Desktop.

  5. Verify in Claude’s UI → Settings → Developer
    You should see “Context7” listed.

The MCP Inspector

The MCP Inspector is an important tool for working with MCP servers. It’s really useful and simple to use.

Testing Context7 with the MCP Inspector

Here’s how to run the MCP Inspector with the Context7 server:

  1. Launch Context7 via Inspector

    npx @modelcontextprotocol/inspector npx -y @upstash/context7-mcp
    
    • The first npx @modelcontextprotocol/inspector runs the Inspector.
    • The remainder (npx -y @upstash/context7-mcp) is the command to run the MCP server. It’s effectively an argument that is passed to the inspector.
  2. Open the Inspector App

    • When the inspector is running properly, we’ll see output similar to this in the terminal:
    Starting MCP inspector...
    ⚙️  Proxy server listening on port 6277
    🔍 MCP Inspector is up and running at http://127.0.0.1:6274 🚀
    
    • Open up the web app in a browser at http://127.0.0.1:6274

    • You should see the Transport Type set to STDIO, the Command as npx and the Arguments as -y @upstash/context7-mcp

    • Click “Connect” to start the MCP server

  3. Inspect and Available Tools

    • When the inspector has properly connected to your MCP server, it will log the following:
    Context7 Documentation MCP Server running on stdio
    
    • Switch to the Tools tab and click “List Tools”, it will display the following:
    resolve-library-id
    Resolves a package/product name to a Context7-compatible library ID and returns ...
    
    get-library-docs
    Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first ...
    
  4. Run Context7 Tools

    • Click on the resolve-library-id tool and test it out. Here’s the result for “pandas”
    Available Libraries (top matches):
    
    Each result includes:
    - Library ID: Context7-compatible identifier (format: /org/project)
    - Name: Library or package name
    - Description: Short summary
    - Code Snippets: Number of available code examples
    - Trust Score: Authority indicator
    - Versions: List of versions if available. Use one of those versions if and only if the user explicitly provides a version in their query.
    
    For best results, select libraries based on name match, trust score, snippet coverage, and relevance to your use case.
    
    ----------
    
    - Title: Pandas
    - Context7-compatible library ID: /pandas-dev/pandas
    - Description: Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
    - Code Snippets: 3653
    - Trust Score: 9.2
    ----------
    - Title: Pandas TA
    - Context7-compatible library ID: /freqtrade/pandas-ta
    - Description: Technical Analysis Indicators - Pandas TA is an easy to use Python 3 Pandas Extension with 150+ Indicators
    - Code Snippets: 47
    - Trust Score: 8.3
    ----------
    - Title: PandasAI
    - Context7-compatible library ID: /sinaptik-ai/pandas-ai
    - Description: Chat with your database or your datalake (SQL, CSV, parquet). PandasAI makes data analysis conversational using LLMs and RAG.
    - Code Snippets: 239
    
    ... (many more results)
    
    • Let’s use the get-library-docs tool to get docs for the “/sinaptik-ai/pandas-ai” library on the topic of “visualizations”:
    "TITLE: Generate Chart from DataFrame - Python
    DESCRIPTION: Shows how to use the `chat` method to request a data visualization (histogram) based on the DataFrame content using natural language.
    SOURCE: https://github.com/sinaptik-ai/pandas-ai/blob/main/README.md#_snippet_5
    
    LANGUAGE: python
    CODE:
    df.chat(
        "Plot the histogram of countries showing for each one the gd. Use different colors for each bar",
    )
    
    ----------------------------------------
    
    TITLE: Saving Chart Responses in PandasAI
    DESCRIPTION: Demonstrates how to save a chart visualization generated by PandasAI's `.chat()` method to a file using the `.save()` method available on chart response objects.
    SOURCE: https://github.com/sinaptik-ai/pandas-ai/blob/main/docs/v3/chat-and-output.mdx#_snippet_5
    
    LANGUAGE: python
    CODE:
    chart_response = df.chat("Create a scatter plot of age vs salary")
    chart_response.save("scatter_plot.png")  # Saves the chart as PNG
    
    ----------------------------------------
    
    TITLE: Using Streamlit Response Parser in PandasAI
    DESCRIPTION: This example illustrates how to configure PandasAI's `SmartDatalake` to use the `StreamlitResponse` parser. This parser is designed to handle responses, particularly visualizations, in a way suitable for a Streamlit application. The custom parser is provided in the configuration when initializing the `SmartDatalake` agent.
    SOURCE: https://github.com/sinaptik-ai/pandas-ai/blob/main/docs/v2/custom-response.mdx#_snippet_1
    
    LANGUAGE: python
    CODE:
    import os
    import pandas as pd
    from pandasai import SmartDatalake
    from pandasai.responses.streamlit_response import StreamlitResponse
    
    employees_df = pd.DataFrame(
        {
            "EmployeeID": [1, 2, 3, 4, 5],
            "Name": ["John", "Emma", "Liam", "Olivia", "William"],
            "Department": ["HR", "Sales", "IT", "Marketing", "Finance"]
        }
    )
    
    ... (many more results)
    
  5. Inspect Resources, Prompts, Sampling and Roots

    • The MCP Inspector also allows us to view the other MCP features that we discussed in the previous lesson.[2]

Connecting to MCP Servers Programmatically

By connecting our AI applications to MCP servers, we can create richer, more useful AI experiences for users.

Below is an example of how to spin up an MCP server and communicate with it using Python.

This is effectively an MCP client implementation.

MCP Python Integration Example

The following script does the following:

  • Spins up the Context7 MCP server locally and communicates with it over stdio
  • Fetches a list of the available tools
  • Calls the resolve-library-id and get-library-docs tools in order to fetch documentation
  • Prints out a sample of the fetched documentation for “numpy” with topic “tensors”
import asyncio
import sys
import re
from typing import Optional
from contextlib import AsyncExitStack

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

LIBRARY_NAME = "numpy"
TOPIC = "tensors"


class Context7Client:
   def __init__(self):
       # Initialize session and client objects
       self.session: Optional[ClientSession] = None
       self.exit_stack = AsyncExitStack()

   async def connect_to_server(self):
       """Connect to Context7 MCP server via npx"""
       server_params = StdioServerParameters(
           command="npx",
           args=["-y", "@upstash/context7-mcp"],
           env=None
       )

       stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
       self.stdio, self.write = stdio_transport
       self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))

       await self.session.initialize()
       print("✅ Connected to Context7 MCP server")

       # List available tools
       response = await self.session.list_tools()
       tools = response.tools
       print("🔧 Available tools:", [tool.name for tool in tools])

   async def resolve_library_id(self, library_name: str) -> str:
       """Resolve library name to Context7-compatible ID"""
       print(f"🔍 Resolving library ID for '{library_name}'...")
       resolve_resp = await self.session.call_tool(
           "resolve-library-id", {"libraryName": library_name}
       )

       if hasattr(resolve_resp, 'content'):
           # Handle the response content properly
           library_id_response = resolve_resp.content[0].text if resolve_resp.content else str(resolve_resp)
       else:
           library_id_response = resolve_resp.get("context7CompatibleLibraryID", str(resolve_resp))

       # Extract the actual library ID from the text using regex
       library_id_match = re.search(r'Context7-compatible library ID:\s*(\/[\w\-]+\/[\w\.\-]+)', str(library_id_response))
       if library_id_match:
           library_id = library_id_match.group(1)
           print(f"🔗 Extracted library ID for '{library_name}':", library_id)
           return library_id
       else:
           print(library_id_response)
           raise Exception("Could not extract library ID from response (see full output above)")

   async def get_docs(self, library_id: str, topic: str) -> str:
       """Fetch documentation for a library on a specific topic"""
       print(f"📚 Fetching docs for topic '{topic}'...")
       docs_resp = await self.session.call_tool(
           "get-library-docs",
           {"context7CompatibleLibraryID": library_id, "topic": topic, "tokens": 15000},
       )

       if hasattr(docs_resp, 'content'):
           docs_content = docs_resp.content[0].text if docs_resp.content else str(docs_resp)
       else:
           docs_content = docs_resp.get("docs", str(docs_resp))

       return docs_content

   async def cleanup(self):
       """Clean up resources"""
       await self.exit_stack.aclose()
       print("🧹 Resources cleaned up")


async def main(library_name: str = LIBRARY_NAME, topic: str = TOPIC):
   """Main function to run the Context7 client"""
   client = Context7Client()
   try:
       await client.connect_to_server()

       # Resolve library ID
       library_id = await client.resolve_library_id(library_name)

       # Get documentation
       docs_content = await client.get_docs(library_id, topic)

       # Print documentation
       print(f"📖 Documentation for {library_name} on {topic}:")
       print("-" * 50)
       print(docs_content[:1000])
       print("-" * 50)
       print(f"Above is only the first 1000 characters of the {len(docs_content)} characters of docs returned by the Context7 MCP server.")

   except Exception as e:
       print(f"💥 Fatal error: {str(e)}")
       sys.exit(1)
   finally:
       await client.cleanup()


if __name__ == "__main__":
   # Allow command line arguments to override defaults
   library = sys.argv[1] if len(sys.argv) > 1 else LIBRARY_NAME
   topic_arg = sys.argv[2] if len(sys.argv) > 2 else TOPIC

   print(f"🚀 Starting Context7 client for library '{library}' and topic '{topic_arg}'")
   asyncio.run(main(library, topic_arg))

We’ll break down how this works below.

Here are the instructions for running it:

# Work in a new directory
mkdir mcp-test && cd mcp-test

# Save to a file named get_docs.py
cat > get_docs.py
# paste code above, then press Ctrl+D

# Install and run
python -m venv venv
venv/bin/pip install mcp==1.9.2
venv/bin/python get_docs.py

If everything goes well, this will output something like the following:

🚀 Starting Context7 client for library 'numpy' and topic 'tensors'
Context7 Documentation MCP Server running on stdio
✅ Connected to Context7 MCP server
🔧 Available tools: ['resolve-library-id', 'get-library-docs']
🔍 Resolving library ID for 'numpy'...
🔗 Extracted library ID for 'numpy': /numpy/numpy
📚 Fetching docs for topic 'tensors'...
📖 Documentation for numpy on tensors:
--------------------------------------------------
TITLE: Ellipsis Equivalence with Full Slices - Python
DESCRIPTION: Shows that using Ellipsis (`...`) is equivalent to explicitly writing out the required number of full slices (`:`) for the dimensions it replaces.
SOURCE: https://github.com/numpy/numpy/blob/main/doc/source/user/basics.indexing.rst#_snippet_10

LANGUAGE: python
CODE:
x = np.array([[[1],[2],[3]], [[4],[5],[6]]]) # Assuming x is the 3D array from previous example
x[:, :, 0]

----------------------------------------

TITLE: Converting PyTorch CPU Tensor to NumPy Array via DLPack in Python
DESCRIPTION: Imports PyTorch, creates a CPU tensor, and converts it to a NumPy array using np.from_dlpack. It demonstrates that the resulting NumPy array is a view of the original tensor by modifying the tensor and showing the change reflected in the NumPy array.
SOURCE: https://github.com/numpy/numpy/blob/main/doc/source/user/basics.interoperability.rst#_snippet_21

LANGUAGE: Python
CODE:
import torch
x_torch = torch.arange(5
--------------------------------------------------
Above is only the first 1000 characters of the 35102 characters of docs returned by the Context7 MCP server.
🧹 Resources cleaned up

Here’s a detailed breakdown of how the script works:

1. Imports and Configuration

import asyncio
import sys
import re
from typing import Optional
from contextlib import AsyncExitStack

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

LIBRARY_NAME = "numpy"
TOPIC = "tensors"

The script starts by importing necessary modules for async operations, system interaction, regex parsing, and the MCP client libraries. It sets default values for the library name and topic to query.

2. Context7Client Class Structure

class Context7Client:
    def __init__(self):
        self.session: Optional[ClientSession] = None
        self.exit_stack = AsyncExitStack()

The Context7Client class encapsulates all MCP server interactions. It uses AsyncExitStack for proper resource management, ensuring connections are cleanly closed even if errors occur.

3. Server Connection

async def connect_to_server(self):
    server_params = StdioServerParameters(
        command="npx",
        args=["-y", "@upstash/context7-mcp"],
        env=None
    )

    stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
    self.stdio, self.write = stdio_transport
    self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))

This method launches the Context7 MCP server as a subprocess using npx, establishes stdio communication channels, and initializes the MCP session. The exit_stack ensures proper cleanup of these resources.

4. Library ID Resolution

async def resolve_library_id(self, library_name: str) -> str:
    resolve_resp = await self.session.call_tool(
        "resolve-library-id", {"libraryName": library_name}
    )

    # Handle different response formats
    if hasattr(resolve_resp, 'content'):
        library_id_response = resolve_resp.content[0].text if resolve_resp.content else str(resolve_resp)
    else:
        library_id_response = resolve_resp.get("context7CompatibleLibraryID", str(resolve_resp))

    # Extract library ID using regex
    library_id_match = re.search(r'Context7-compatible library ID:\s*(\/[\w\-]+\/[\w\.\-]+)', str(library_id_response))

This method converts a human-readable library name (like “numpy”) into Context7’s internal ID format (like “/numpy/numpy”). It handles different response formats and uses regex to extract the ID from the response text.

5. Documentation Retrieval

async def get_docs(self, library_id: str, topic: str) -> str:
    docs_resp = await self.session.call_tool(
        "get-library-docs",
        {"context7CompatibleLibraryID": library_id, "topic": topic, "tokens": 15000},
    )

    if hasattr(docs_resp, 'content'):
        docs_content = docs_resp.content[0].text if docs_resp.content else str(docs_resp)
    else:
        docs_content = docs_resp.get("docs", str(docs_resp))

This method fetches documentation for a specific topic within the resolved library. It requests up to 15,000 tokens of documentation and handles different response formats from the MCP server.

6. Main Execution Flow

async def main(library_name: str = LIBRARY_NAME, topic: str = TOPIC):
    client = Context7Client()
    try:
        await client.connect_to_server()
        library_id = await client.resolve_library_id(library_name)
        docs_content = await client.get_docs(library_id, topic)

        # Display results with truncation for readability
        print(f"📖 Documentation for {library_name} on {topic}:")
        print("-" * 50)
        print(docs_content[:1000])
        print("-" * 50)

The main function orchestrates the entire process: connecting to the server, resolving the library ID, fetching documentation, and displaying results. It includes error handling and ensures cleanup occurs in the finally block.

7. Command Line Interface

if __name__ == "__main__":
    library = sys.argv[1] if len(sys.argv) > 1 else LIBRARY_NAME
    topic_arg = sys.argv[2] if len(sys.argv) > 2 else TOPIC

    print(f"🚀 Starting Context7 client for library '{library}' and topic '{topic_arg}'")
    asyncio.run(main(library, topic_arg))

Notice how the script can accept command line arguments to override the default library and topic, e.g. python get_docs.py google-cloud-storage streaming would query GCP documentation about streaming.

Binding MCP Tools to an Agent Workflow

Agentic AI frameworks like LangGraph have MCP extensions that abstract out a lot of the complexity of the code we just looked at.

ReAct Agent with LangGraph

Here’s a simple example of a ReAct Agent[3] with a Context7 MCP integration:

import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent

async def main():
    client = MultiServerMCPClient(
        {
            "context7": {
                "command": "npx",
                "args": ["-y", "@upstash/context7-mcp"],
                "transport": "stdio",
            }
        }
    )

    tools = await client.get_tools()
    agent = create_react_agent(
        "anthropic:claude-3-5-haiku-latest",
        tools
    )

    print("Context7 MCP Agent Ready!")

    while True:
        user_input = input("\nYou: ")

        try:
            response = await agent.ainvoke(
                {"messages": [{"role": "user", "content": user_input}]}
            )
            last_message = response['messages'][-1]
            print(f"Agent: {last_message.content}")
        except Exception as e:
            print(f"Error: {e}")

if __name__ == "__main__":
    asyncio.run(main())

Requirements

This has the following requirements:

langchain-mcp-adapters==0.1.4
langgraph==0.4.8
langchain==0.3.25
langchain-anthropic==0.3.15

Running the Agent

Below are the instructions for running it.

Keep in mind that this will cost a bit of money, as we’re using the anthropic API.

Note that we set the model to claude-3-5-haiku-latest which is about 4x cheaper than Sonnet.

# Work in a new directory
mkdir agent-mcp-test && cd agent-mcp-test

# Save to a file named get_docs.py
cat > agent.py
# paste code above, then press Ctrl+D

# Save the requirements
cat > requirements.txt
# paste code above, then press Ctrl+D

export ANTHROPIC_API_KEY=<paste_your_key>

# Install and run
python -m venv venv
venv/bin/pip install -r requirements.txt
venv/bin/python agent.py

If everything goes well, this will output something like the following:

Context7 Documentation MCP Server running on stdio
Context7 MCP Agent Ready!
Type 'quit' to exit

You: hey who are you?
Agent: Hello! I'm an AI assistant designed to help you with documentation and technical queries. I specialize in retrieving and explaining library documentation
 using the Context7 tool set ...


You: tell me how to interpret boxplot diagrams from seaborn
Context7 Documentation MCP Server running on stdio
Context7 Documentation MCP Server running on stdio
Agent: Now, I'll explain how to interpret boxplot diagrams from Seaborn:

A boxplot (or box-and-whisker plot) is a powerful statistical visualization that provides a comprehensive summary of a dataset's distribution. Here's how to int
erpret the key components:

1. The Box:
   - The box itself represents the interquartile range (IQR), which contains the middle 50% of the data
   - The bottom of the box is the 25th percentile (Q1)
   - The top of the box is the 75th percentile (Q3)
   - The line inside the box is the median (50th percentile)

2. The Whiskers:
   - Extend from the box to show the rest of the distribution
   - Typically reach to 1.5 * IQR from the edges of the box
   - Represent the range of "typical" data points

3. Outliers:
   - Points beyond the whiskers are plotted as individual points
   - These represent unusual or extreme values in the dataset

Example of creating a boxplot in Seaborn:

import seaborn as sns
import matplotlib.pyplot as plt

# Basic boxplot
sns.boxplot(data=your_dataframe, x="category", y="value")
plt.show()

...

Conclusion

We started this lesson working with MCP using Node.js (via npx), and finished it by working with MCP using Python.

This is a common theme we see with MCP, where the majority of servers are written in TypeScript (and configured in MCP clients with npx) or Python (and configured with uvx[4]).

Key Takeaways

🗄️ Context7 delivers live, version-aware code documentation through the MCP protocol.

📁 Claude Desktop integration is a single JSON entry that launches Context7 with npx.

🔍 MCP Inspector is the quickest way to start, inspect, and troubleshoot any MCP server.

🐍 The mcp Python library lets you start servers and invoke tools programmatically with minimal async code.

🤖 Frameworks like LangGraph (via langchain_mcp_adapters) let you drop Context7 tools straight into ReAct-style agents for richer, documentation-aware conversations.

Next: Building MCP Servers

Now that we’ve seen how to use MCP servers, let’s flip perspectives and see how to build one.

We’ll use Python and FastMCP to get a demo server up and running on our local machine and distributed via GitHub.

It’s gonna be fun.

Footnotes


  1. I was going to include full installation instructions for Node, but removed them because it’s best if you find the latest instructions yourself. If you’re on Mac or Linux then I suggest using nvm to install and manage your Node environment. ↩︎

  2. At time of writing, Context7 only has tools (no resources, prompts, etc…), but the MCP Inspector is fully equipped to test those as well. We’ll revisit this in the next lesson when building an MCP server. ↩︎

  3. We talked about ReAct agents in the previous topic group. Check out the “AI Engineering > Agents > Agent Architectures” lesson. ↩︎

  4. uv is a package manager for Python that’s super fast and quickly being adopted across the community. uvx is a utility that executes and installs apps provided by Python packages (similar to how npx invokes an app that lives in an npm package). ↩︎

Comments (0)

No comments yet.