LangChain MCP Adapters

repository·main·Indexed 25 days ago

https://github.com/langchain-ai/langchain-mcp-adapters

A lightweight wrapper that makes Anthropic Model Context Protocol (MCP) tools compatible with LangChain and LangGraph agents. It provides the MultiServerMCPClient to manage connections to multiple MCP servers via stdio, http, and streamable_http transports, enabling the conversion of MCP tools into LangChain BaseTool objects.

Tokens
7.1K
Snippets
10
Records
42
Agent score
86%

What's inside langchain-mcp-adapters

  1. Quickstart: Use MCP tools with a single stdio server

    main

    To use MCP tools from a local server via stdio transport, use load_mcp_tools within an asynchronous stdio_client context. This allows you to convert MCP tools into LangChain tools for use with agents.

    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client
    
    from langchain_mcp_adapters.tools import load_mcp_tools
    from langchain.agents import create_agent
    
    server_params = StdioServerParameters(
        command="python",
        # Make sure to update to the full absolute path to your math_server.py file
        args=["/path/to/math_server.py"],
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the connection
            await session.initialize()
    
            # Get tools
            tools = await load_mcp_tools(session)
    
            # Create and run the agent
            agent = create_agent("openai:gpt-4.1", tools)
            agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
  2. Use MCP tools with Streamable HTTP transport

    main

    The library supports the MCP streamable_http transport. You can connect using the standard streamablehttp_client from the MCP SDK or via MultiServerMCPClient.

    # Using MultiServerMCPClient with streamable HTTP
    from langchain_mcp_adapters.client import MultiServerMCPClient
    from langchain.agents import create_agent
    
    client = MultiServerMCPClient(
        {
            "math": {
                "transport": "http",
                "url": "http://localhost:3000/mcp"
            },
        }
    )
    tools = await client.get_tools()
    agent = create_agent("openai:gpt-4.1", tools)
    math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
  3. Integrate MCP tools with LangGraph StateGraph

    main

    You can use MCP tools within a LangGraph StateGraph by binding the loaded tools to a model and using a ToolNode to handle tool execution.

    from langchain_mcp_adapters.client import MultiServerMCPClient
    from langgraph.graph import StateGraph, MessagesState, START
    from langgraph.prebuilt import ToolNode, tools_condition
    from langchain.chat_models import init_chat_model
    
    model = init_chat_model("openai:gpt-4.1")
    
    client = MultiServerMCPClient(
        {
            "math": {
                "command": "python",
                "args": ["./examples/math_server.py"],
                "transport": "stdio",
            },
        }
    )
    tools = await client.get_tools()
    
    def call_model(state: MessagesState):
        response = model.bind_tools(tools).invoke(state["messages"])
        return {"messages": response}
    
    builder = StateGraph(MessagesState)
    builder.add_node(call_model)
    builder.add_node(ToolNode(tools))
    builder.add_edge(START, "call_model")
    builder.add_conditional_edges(
        "call_model",
        tools_condition,
    )
    builder.add_edge("tools", "call_model")
    graph = builder.compile()
  4. Run the MCP Simple StreamableHttp Stateless Server

    main

    The mcp-simple-streamablehttp-stateless server demonstrates how to use the StreamableHTTP transport in stateless mode (mcp_session_id=None). This mode is suitable for multi-node environments because each request creates a new ephemeral connection and no session state is maintained between requests.

    You can run the server using uv with various configuration flags for ports, logging, and response formats.

    # Using default port 3000
    uv run mcp-simple-streamablehttp-stateless
    
    # Using custom port
    uv run mcp-simple-streamablehttp-stateless --port 3000
    
    # Custom logging level
    uv run mcp-simple-streamablehttp-stateless --log-level DEBUG
    
    # Enable JSON responses instead of SSE streams
    uv run mcp-simple-streamablehttp-stateless --json-response
  5. Deploy MCP tools with LangGraph API Server

    main

    To use MCP tools in a LangGraph API server, define an asynchronous function (e.g., make_graph) that initializes the MultiServerMCPClient and returns the agent. Specify this function as the graph entrypoint in your langgraph.json configuration.

    # graph.py
    from langchain_mcp_adapters.client import MultiServerMCPClient
    from langchain.agents import create_agent
    
    async def make_graph():
        client = MultiServerMCPClient(
            {
                "weather": {
                    "url": "http://localhost:8000/mcp",
                    "transport": "http",
                },
            }
        )
        tools = await client.get_tools()
        agent = create_agent("openai:gpt-4.1", tools)
        return agent

    langgraph.json

    { "dependencies": ["."], "graphs": { "agent": "./graph.py:make_graph" } }

  6. Pass runtime headers for SSE and HTTP transports

    main

    When using sse or http (including streamable_http) transports, you can provide custom headers (e.g., for Authorization) via the headers field in the connection configuration within MultiServerMCPClient.

    from langchain_mcp_adapters.client import MultiServerMCPClient
    from langchain.agents import create_agent
    
    client = MultiServerMCPClient(
        {
            "weather": {
                "transport": "http",
                "url": "http://localhost:8000/mcp",
                "headers": {
                    "Authorization": "Bearer YOUR_TOKEN",
                    "X-Custom-Header": "custom-value"
                },
            }
        }
    )
    tools = await client.get_tools()
    agent = create_agent("openai:gpt-4.1", tools)
    response = await agent.ainvoke({"messages": "what is the weather in nyc?"})
  7. Connect to multiple MCP servers with MultiServerMCPClient

    main

    Use MultiServerMCPClient to manage connections to multiple MCP servers (e.g., one via stdio and one via http) simultaneously. You can pass a dictionary defining the configuration for each server.

    from langchain_mcp_adapters.client import MultiServerMCPClient
    from langchain.agents import create_agent
    
    client = MultiServerMCPClient(
        {
            "math": {
                "command": "python",
                # Make sure to update to the full absolute path to your math_server.py file
                "args": ["/path/to/math_server.py"],
                "transport": "stdio",
            },
            "weather": {
                # Make sure you start your weather server on port 8000
                "url": "http://localhost:8000/mcp",
                "transport": "http",
            }
        }
    )
    tools = await client.get_tools()
    agent = create_agent("openai:gpt-4.1", tools)
    math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
    weather_response = await agent.ainvoke({"messages": "what is the weather in nyc?"})
  8. Configure tool error handling

    main

    By default, MCP tool execution errors (isError=True) are returned to the model as a ToolMessage with status="error", allowing the agent to self-correct.

    To change this to the legacy behavior where execution errors raise a ToolException, set handle_tool_errors=False in MultiServerMCPClient or load_mcp_tools.