A LangGraph Agent With MCP Tools: Load a FastMCP Server's Tools With langchain-mcp-adapters, Survive a ToolError, Then Plug the Same Server Into Claude Code
One orders MCP server, many hosts. MultiServerMCPClient starts the server over stdio and turns get_order_status and list_orders into LangChain tools, a create_agent graph calls both, an unknown order Z-9999 comes back as an error message the model can read, and claude mcp add plugs the same server into Claude Code.
What you will learn
- Load an MCP server's tools as LangChain tools with MultiServerMCPClient over stdio
- Build a LangGraph agent with create_agent that calls those tools
- Show how a ToolError reaches the model as an error message instead of crashing the graph
- Register the same server in Claude Code with claude mcp add
Before you start
- What Is MCP? Host, Client, Server
- Building an MCP Server: Tools, Resources and Prompts
- LangGraph Nodes, Edges and State
You have an MCP server for an orders API. Now you want an agent of your own to use it, without writing glue code for every tool. In this article we plug the server into a LangGraph agent: the agent loads the server's tools, calls them, and keeps running when a tool fails. Then we plug the very same server into Claude Code.
The scripts run on a stand-in test model with scripted replies, so no key is needed. The MCP server and its tools are real.
One MCP server, many hosts
Think of USB-C. You build the port once, and every device can plug in. Our MCP server, called orders, has two tools and one resource. The first host is our own LangGraph agent in Python. The second is Claude Code, a coding agent in the terminal. A third could be Claude Desktop. The tools live in the server; a host only needs to speak MCP.
server.py and sees the same two tools.The project
mcp_server/:orders_api.py(five orders in memory) andserver.py(the MCP server).agent/:mcp_tools.pyconnects to the server,model.pygives us the model.scripts/: 01, 02 and 03, run in order.tests/: offline tests.
requirements.txt pins langchain-mcp-adapters==0.3.2, the bridge that turns MCP tools into LangChain tools, and mcp==1.30.0. The adapters work with the 1.x SDK, where the server class is called FastMCP. Then come langgraph, langchain and langchain-core for the agent itself.
The MCP server
orders_api.py holds five orders, A-1001 to A-1005, and two plain functions: find_order and orders_with_status. server.py wraps them as MCP tools.
from collections import Counter
from typing import Literal
# The MCP adapters work with the 1.x SDK, where the server class is called FastMCP.
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError
import orders_api # same folder: hosts start this file by its path
mcp = FastMCP("orders", log_level="WARNING")
@mcp.tool()
def get_order_status(order_id: str) -> dict:
"""Look up one order by its id, for example A-1001."""
order = orders_api.find_order(order_id)
if order is None:
raise ToolError(f"No order with id {order_id}")
return {"order_id": order_id.upper(), **order}
@mcp.tool()
def list_orders(status: Literal["packed", "shipped", "delivered"]) -> list[dict]:
"""List every order that currently has the given status."""
return orders_api.orders_with_status(status)
@mcp.resource("orders://summary")
def orders_summary() -> str:
"""How many orders sit in each status."""
counts = Counter(o["status"] for o in orders_api.ORDERS.values())
return ", ".join(f"{n} {s}" for s, n in sorted(counts.items()))
if __name__ == "__main__":
mcp.run(transport="stdio")
The name "orders" is what every host sees. Each docstring becomes the tool's description. status is a Literal, so only three values are allowed. An unknown id raises a ToolError. The server talks over standard input and output. Building servers in depth is in Building an MCP Server.
The client side: one adapter, one model factory
"""Shared helper: connect to the orders MCP server (started as a child process over stdio)."""
import sys
from pathlib import Path
from langchain_mcp_adapters.client import MultiServerMCPClient
SERVER = str(Path(__file__).resolve().parents[1] / "mcp_server" / "server.py")
def make_client():
return MultiServerMCPClient(
{"orders": {"transport": "stdio", "command": sys.executable, "args": [SERVER]}}
)
SERVER is the full path to server.py, built from this file's location, so it works wherever you run a script from. The client holds one server named orders, but it could hold many. The command is sys.executable, your own virtual-environment Python, which starts server.py as a child process.
class ScriptedModel(GenericFakeChatModel):
"""Replays AIMessages in order. bind_tools does nothing, because the script already holds the tool calls."""
def bind_tools(self, tools, **kwargs):
return self
def tool_call(name, args, call_id):
return AIMessage(content="", tool_calls=[{"name": name, "args": args, "id": call_id}])
def get_model(script=None):
load_dotenv(Path(__file__).resolve().parents[1] / ".env") # the .env in the project root, if there is one
if os.getenv("MODEL_NAME"):
from langchain.chat_models import init_chat_model
return init_chat_model(os.environ["MODEL_NAME"])
return ScriptedModel(messages=iter(script or []))
Everything else asks get_model() for its model and never cares which one it gets. With MODEL_NAME set (and your key and the provider's package), it returns a real chat model. Without it, ScriptedModel replays the replies we give it, and tool_call builds one scripted reply that asks for a tool.
What the adapter does
Step 1: load the tools
import asyncio
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # project root, so "agent" can be imported
from agent.mcp_tools import make_client
async def main():
client = make_client()
tools = await client.get_tools()
for t in tools:
print("tool:", t.name)
print(" description:", t.description)
print(" arguments: ", json.dumps(t.args))
# A loaded MCP tool is a normal LangChain tool, so we can call it directly.
result = await tools[0].ainvoke({"order_id": "A-1001"})
print("direct call:", " ".join(result[0]["text"].split()))
asyncio.run(main())
tool: get_order_status
description: Look up one order by its id, for example A-1001.
arguments: {"order_id": {"title": "Order Id", "type": "string"}}
tool: list_orders
description: List every order that currently has the given status.
arguments: {"status": {"enum": ["packed", "shipped", "delivered"], "title": "Status", "type": "string"}}
direct call: { "order_id": "A-1001", "customer": "Priya", "item": "Desk lamp", "status": "shipped" }
The descriptions are our docstrings, and the Literal became a JSON-schema enum. The direct ainvoke call proves it: an MCP tool is a normal LangChain tool.
Step 2: an agent that calls them
from langchain.agents import create_agent
from agent.mcp_tools import make_client
from agent.model import AIMessage, get_model, tool_call
QUESTION = "Where is order A-1001, and which orders are still packed?"
# The scripted "test model reply": two tool calls, then the final answer.
SCRIPT = [
tool_call("get_order_status", {"order_id": "A-1001"}, "call_1"),
tool_call("list_orders", {"status": "packed"}, "call_2"),
AIMessage(content="Order A-1001 (Desk lamp for Priya) has shipped. "
"Two orders are still packed: A-1002 and A-1004."),
]
async def main():
tools = await make_client().get_tools()
agent = create_agent(get_model(SCRIPT), tools)
result = await agent.ainvoke({"messages": [("user", QUESTION)]})
for m in result["messages"]:
if m.type == "ai" and m.tool_calls:
print("model -> tool call:", m.tool_calls[0]["name"], m.tool_calls[0]["args"])
elif m.type == "tool":
print("tool -> result: ", " ".join(m.text.split()))
elif m.type == "ai":
print("model -> answer: ", m.content)
model -> tool call: get_order_status {'order_id': 'A-1001'}
tool -> result: { "order_id": "A-1001", "customer": "Priya", "item": "Desk lamp", "status": "shipped" }
model -> tool call: list_orders {'status': 'packed'}
tool -> result: { "order_id": "A-1002", "customer": "Marcus", "item": "Notebook set", "status": "packed" }{ "order_id": "A-1004", "customer": "Omar", "item": "USB-C hub", "status": "packed" }
model -> answer: Order A-1001 (Desk lamp for Priya) has shipped. Two orders are still packed: A-1002 and A-1004.
create_agent builds a LangGraph agent from a model and a list of tools: the model asks for a tool, the tool node runs it, the result goes back to the model, and so on until the model answers. The tool calls and the final answer are scripted test model replies, but both tool results came from the real MCP server.
Step 3: when a tool fails
QUESTION = "What is the status of order Z-9999?"
SCRIPT = [
tool_call("get_order_status", {"order_id": "Z-9999"}, "call_1"),
AIMessage(content="I could not find an order with id Z-9999. "
"Please check the id; it looks like A-1001."),
]
async def main():
tools = await make_client().get_tools()
agent = create_agent(get_model(SCRIPT), tools)
result = await agent.ainvoke({"messages": [("user", QUESTION)]})
for m in result["messages"]:
if m.type == "tool":
# The server raised ToolError. The adapter turns it into an error message
# the model can read, so the graph keeps running instead of crashing.
print("tool error?", m.status == "error")
print("tool text: ", m.text)
elif m.type == "ai" and not m.tool_calls:
print("model -> answer:", m.text)
tool error? True
tool text: Error executing tool get_order_status: No order with id Z-9999
model -> answer: I could not find an order with id Z-9999. Please check the id; it looks like A-1001.
The tool message is marked status="error", and its text carries our ToolError from the server. The adapter handed the error to the model as a message, so the graph kept running and the model still answered. That is the behaviour you want: a bad id is a normal event in a support chat, not a crash.
The project's three tests check the same three things (the tools load, a result reaches the model, an error doesn't crash the graph). Each test starts the real server over stdio, fully offline: 3 passed.
Same server, new host: Claude Code
For Claude Desktop, claude_desktop_config.json has an mcpServers entry named orders: the command is your virtual-environment python.exe, and the args is the full path to server.py. For Claude Code, one command in the project folder registers it (use your own full paths):
claude mcp add orders -- C:\path\to\S01L05_LangGraphMcpAgent\.venv\Scripts\python.exe C:\path\to\S01L05_LangGraphMcpAgent\mcp_server\server.py
The first word after add is the name. Everything after -- is the command that starts the server. Claude Code saves it in its local config, private to you and this project, and claude mcp get orders reports the scope as local and the status as connected. The project's .claude/settings.local.json allows the two tools, so Claude Code won't stop to ask before calling them:
{
"permissions": {
"allow": [
"mcp__orders__get_order_status",
"mcp__orders__list_orders"
]
}
}
Asked the same question as 02_agent.py, Claude Code called the orders server two times and answered with the same facts: A-1001, Priya's desk lamp, has shipped, and A-1002 (Marcus) and A-1004 (Omar) are still packed. This time a real model picked the tools, not a script. More on scopes and troubleshooting is in Configuring MCP Servers in Claude Code.
Common mistakes
- A relative path to
server.py. The host starts the server from its own working directory. Build the path from__file__, asSERVERdoes. - The wrong Python. The command must be the Python that has
mcpinstalled.sys.executableis safe for your own agent; for Claude Code and Claude Desktop, give the full virtual-environment path. - Raising a plain exception for an expected case. Use
ToolErrorwith a clear message, so the model can read it and recover. - Mixing SDK versions. The adapters pinned here use the 1.x SDK, so the class is
FastMCP. Pin versions and import what your installed version provides. - A very deep folder on Windows. The README warns that a path over 260 characters can stop
server.pyfrom importingorders_api. Keep the project on a short path.
Quick recap
| Piece | Job |
|---|---|
FastMCP("orders") | The server: two tools, one resource, stdio transport |
MultiServerMCPClient | Starts the server and turns its tools into LangChain tools with get_tools() |
create_agent(model, tools) | A LangGraph agent that calls the tools until it can answer |
ToolError | Reaches the model as an error message; the graph keeps running |
claude mcp add orders -- ... | The same server in Claude Code |
For the protocol basics, see What Is MCP?. For several agents sharing work, see Supervisor and Worker Agents in LangGraph and LangGraph vs CrewAI vs the Claude Agent SDK.
Try it yourself
Add a cancel_order tool to mcp_server/server.py and run 01_load_tools.py again: it shows up with no other change. Then ask Claude Code to use it. Or change 03_tool_error.py to ask for A-1003 and watch the error path go away.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.
