Connecting to MCP servers
Let's connect to a real MCP server. We'll use a weather MCP server published as an npm package. One command downloads and runs it, then we discover what tools it provides.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Define the MCP server to connect to
server_params = StdioServerParameters(
command="npx",
args=["-y", "@philschmid/weather-mcp"],
env=None
)
# This downloads and runs the weather MCP server
# using npx (Node.js package executor)StdioServerParameters defines how to launch the MCP server. npx downloads and runs it automatically with no manual installation.
Good question! Many MCP servers are published as npm packages, so you do need Node.js installed for npx to work. But your agent code stays 100% Python. Think of npx as just the delivery mechanism for the server binary. Once the server is running, your Python MCP client talks to it over standard I/O.
MCP uses async/await because tool calls happen over a network. async lets Python wait for responses without blocking other work. If you have not used async before, just know that "async def" defines an async function, and "await" pauses until a result comes back.
async def explore_mcp_server():
"""Connect to MCP server and discover its tools."""
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the MCP session
await session.initialize()
print("Connected to MCP weather server!")
# Discover available tools
tools_result = await session.list_tools()
tools = tools_result.tools
for tool in tools:
print(f" Tool: {tool.name}")
print(f" Description: {tool.description}")
print(f" Parameters: {json.dumps(tool.inputSchema)}")
# Run it
await explore_mcp_server()
# Output:
# Tool: get_weather_forecast
# Description: Get weather forecast for a location
# Parameters: {"type": "object", "properties": {"city": ...}}session.list_tools() discovers what the server offers. You don't need to know the tools in advance because the server tells you.
MCP connection lifecycle
The step-by-step flow from connecting to calling tools.
Timed quiz: Quick review
Loading practice…
Ordering exercise: MCP connection steps
Loading practice…
You can now connect to any MCP server and discover its tools. Next, we will wire this into a full agent workflow where the AI decides which tool to call and processes the results.