Guilds AI / AI Blog

,

LangChain MCP Adapter: Python Setup and Migration Guide

Illustrated software adapter connecting a chain-link hub to coding tools, databases, documents and cloud services.

The LangChain MCP adapter connects tools exposed by Model Context Protocol (MCP) servers to a LangChain agent. For a new Python integration using LangChain 1.4 or later, the documentation now describes the beta MCPAdapter interface under langchain.mcp. Existing projects may instead use the separate langchain-mcp-adapters package and its MultiServerMCPClient class.

Both approaches convert server tools into forms that a LangChain agent can invoke. They differ in installation, tool discovery and connection lifecycle. This guide explains how to identify the appropriate API, connect a small read-only server, and test the integration without granting unnecessary permissions. Examples are based on documentation reviewed November 29, 2026; they have not been executed against a live model or MCP server here.

What is the LangChain MCP adapter?

An MCP server exposes capabilities through a standard protocol. A client connects to that server and discovers available tools, including their descriptions and input schemas. The adapter makes the discovered tools available to the agent’s model and execution layer. When the agent requests a tool, the adapter forwards the operation to the server and returns the result in a compatible form.

The model does not need to implement the transport itself. Our LLM MCP guide explains the roles of clients, hosts, servers and models in more detail. An adapter provides interoperability, not automatic authorization. The server and surrounding application must still enforce access controls.

LayerResponsibility
MCP serverDefine tools and implement permitted operations
Client or adapterDiscover tools, handle connections and translate invocation
LangChain agentChoose a tool and interpret its response
Application policyEnforce permissions, validate inputs and review results

Choose the correct adapter API

InterfaceNew Python APIOlder Python package
Installationlangchain[mcp] version 1.4 or laterlangchain-mcp-adapters
Importlangchain.mcp.MCPAdapterlangchain_mcp_adapters.client.MultiServerMCPClient
Tool discoveryawait adapter.list_tools()await client.get_tools()
LifecycleAdapter and underlying FastMCP clientPer-call sessions by default; explicit sessions available
StatusBeta API; subject to changeSeparate package used by existing integrations

Do not replace only the import in an existing application. Tool naming, authentication and lifecycle assumptions may also change. Keep the versions that an existing integration has been tested with until a migration passes its acceptance checks. For a new experiment, install the documented MCP extra in a separate virtual environment.

See our LangChain installation guide for interpreter and dependency troubleshooting. Use pip show and pip check to confirm the installed package versions before following a tutorial written for a different interface.

Connect an MCP server with MCPAdapter

Install the dependencies

python -m pip install "langchain[mcp]>=1.4.0" langchain-openai
python -m pip check

The example uses a model-free discovery test first. The MCP extra supplies FastMCP; langchain-openai is needed only for the subsequent OpenAI model example. Select an available model identifier and configure your provider credentials securely if you run the agent.

Create a local read-only example server

Save the following as inventory_server.py in an isolated test directory. The server exposes one tool for fictional inventory data. It performs no network requests, writes or access to real customer information.

from fastmcp import FastMCP

mcp = FastMCP("demo-inventory")

@mcp.tool
def lookup_stock(sku: str) -> str:
    """Return stock information for a demo SKU."""
    stock = {"DEMO-42": 12, "DEMO-99": 0}
    if sku not in stock:
        return "Unknown SKU"
    return f"{sku}: {stock[sku]} units"

if __name__ == "__main__":
    mcp.run()

Discover and inspect tools

Create a second file, client.py, in the same directory. A Path target tells the current adapter to launch a local script over standard input and output. A remote HTTP URL is a different target type; use the transport configuration appropriate to the server.

import asyncio
from pathlib import Path
from langchain.mcp import MCPAdapter

async def main():
    path = Path(__file__).with_name("inventory_server.py")
    async with MCPAdapter(path) as adapter:
        tools = await adapter.list_tools()
        for tool in tools:
            print(tool.name, tool.description)

asyncio.run(main())

Run python client.py from the same compatible environment. The intended result is discovery of the lookup_stock tool. If discovery fails, stop and fix the connection before involving a model. For remote connections and the choice of transport, see our MCP server setup guide.

Add the tool to a LangChain agent

After confirming the tool catalog, select the expected tool explicitly and pass only that tool to the agent. The following version of the client requires MODEL_ID and OPENAI_API_KEY to be set securely. It uses the documented agent interface and keeps the adapter context open while the agent runs.

import asyncio
import os
from pathlib import Path
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter

async def main():
    path = Path(__file__).with_name("inventory_server.py")
    async with MCPAdapter(path) as adapter:
        tools = await adapter.list_tools()
        allowed = [t for t in tools if t.name == "lookup_stock"]
        if len(allowed) != 1:
            raise RuntimeError("Unexpected tool catalog")
        agent = create_agent(
            model="openai:" + os.environ["MODEL_ID"],
            tools=allowed,
        )
        result = await agent.ainvoke({"messages": [
            {"role": "user", "content":
             "Check stock for DEMO-42 using the tool."}
        ]})
        print(result["messages"][-1].content)

asyncio.run(main())

The expected business result is 12 units. Verify that a tool call actually occurred and that the reported SKU and quantity match its output. A plausible final message is not proof that the agent queried the server. A model request may incur provider charges.

Use the older MultiServerMCPClient

Many existing tutorials install the standalone package and use MultiServerMCPClient. The following illustrates its documented local connection pattern. Use this separately from the beta example, in an environment with compatible versions of the older package and server SDK.

python -m pip install langchain-mcp-adapters langchain fastmcp
import asyncio
import sys
from pathlib import Path
from langchain_mcp_adapters.client import MultiServerMCPClient

async def main():
    client = MultiServerMCPClient({
        "inventory": {
            "transport": "stdio",
            "command": sys.executable,
            "args": [str(Path(__file__).with_name("inventory_server.py"))],
        }
    })
    tools = await client.get_tools()
    print([tool.name for tool in tools])

asyncio.run(main())

This older client normally creates a new session for each tool invocation. For tools that rely on session state, use the documented explicit client.session context and load_mcp_tools interface. In versions 0.1.0 and later of the older package, do not use MultiServerMCPClient itself as an async context manager. Check your installed version rather than combining snippets from different releases.

Migrate and manage connections

The current LangChain adapter is built on FastMCP. It can infer the transport for a single script path or HTTP URL, and supports more advanced configurations for multiple servers. When separate connections require different authentication or protocol negotiation behavior, the documented FastMCP ClientGroup approach may be appropriate.

Migration checkWhat to confirm
Tool catalogExpected tool names, descriptions and argument schemas
Multiple serversServer prefixes and collision handling
CredentialsCorrect per-server authorization and scopes
Session assumptionsStateful tools continue to behave as expected
Error handlingTool errors and connection failures are handled explicitly
Release controlsExisting tests pass before switching production traffic

Use a test environment for migration and compare representative tool responses against the previous integration. In multi-server configurations the tool names may be prefixed by server name. Update allowlists and instructions to match the discovered names instead of assuming that names remain unchanged.

For larger tool catalogs, our tool discovery for AI agents guide explains how to expose only relevant authorized capabilities. Do not automatically grant every newly discovered tool to the model.

Test tools and troubleshoot errors

SymptomWhat to check
Import errorInstalled framework version and correct package
Local process exitsInterpreter, script path, SDK and server logs
Remote connection failsEndpoint, transport and authorized credentials
No expected toolServer registration and actual catalog names
Tool call failsInput schema, permissions and error result
Incorrect final answerTrace the tool call and compare output with the response

For the local example, test DEMO-42, DEMO-99 and an unknown SKU. The expected results are 12 units, zero units and an explicit unknown-SKU message. Test an invalid input against the server schema, not just the model’s final wording. Use actual observed outcomes before claiming the integration passed.

If discovery succeeds but invocation fails, inspect the connection lifetime and the underlying tool response. Keep diagnostic logging separate from protocol output on a stdio server. Do not repeatedly retry authorization or schema errors as if they were temporary network failures.

Secure your agent integration

An MCP server can provide tools with side effects, sensitive data access or misleading tool descriptions. Use trusted servers, narrowly scoped credentials and explicit allowlists. A locally launched server is executable software: inspect its code and dependencies before starting it, and avoid inheriting unnecessary secrets from the surrounding process.

Keep read and write capabilities separate. Validate record identities, restrict permitted actions and require independent approval for consequential operations. Treat tool results as untrusted data, including instructions embedded in returned text. Use bounded timeouts and safe retry rules; a failed response from a write operation may not mean that the operation failed.

For production use, document the supported version, approved tools, data boundaries and expected failure behavior. The beta API may change, so pin a verified dependency set and run integration tests before upgrading.

Frequently asked questions

What is the LangChain MCP adapter?

It converts tools exposed by MCP servers into tools a LangChain agent can invoke, handling the integration between the agent and MCP client.

Should I use MCPAdapter or MultiServerMCPClient?

For a new experiment with LangChain 1.4 or later, evaluate the documented beta MCPAdapter. Existing applications can retain the compatible older package until a migration has been tested.

Can the adapter connect to local and remote servers?

Yes. The current adapter supports local script targets and remote HTTP endpoints, along with more advanced client configurations.

Do I need an AI model to discover MCP tools?

No. Tool discovery can be tested separately from agent creation. A model is needed when you want the agent to decide which tool to invoke.

Does MCP automatically make tools safe?

No. The protocol standardizes communication. Authentication, tool permissions, data validation and approval requirements remain the responsibility of the server and application.