Skip to main content

AI17 min read

LangChain MCP Tutorial: Connect Agents with MCPAdapter

MCPAdapter in langchain.mcp turns MCP server tools into create_agent tools: install, stdio/HTTP/in-memory transports, migration from langchain-mcp-adapters.

In the tools article we saw that an agent talks to the outside world through tools. But what if we want our agent to reach GitHub, a database and the file system at the same time? Writing separate @tool functions for each of them doesn't look like a problem at first, but as the number of services grows, writing and maintaining that code gets harder. This is exactly where MCP (Model Context Protocol) helps: tools are written once as an MCP server, and we connect them to our agent with LangChain's MCPAdapter class.

We mentioned MCP in a few lines at the end of the tools article. The topic is too big for a single post, so I decided to turn it into a series. The LangChain documentation covers MCP under four headings, and we'll follow the same order.

Scope of this article: We can think of this article as the map of the series. We'll talk about what MCP is, how to set up MCPAdapter, our first agent, transports and migrating from the old langchain-mcp-adapters package. The rest of the series looks like this:

  1. LangChain MCP Tutorial (this article)
  2. LangChain MCP Tools – outputs, metadata, human-in-the-loop and elicitation
  3. LangChain MCP Connections – lifecycle, multiple servers, scaling, caching and protocol eras
  4. LangChain MCP Auth – bearer tokens, OAuth 2.1, per-server and per-user authorization

At a glance

Topic Value
Package langchain[mcp] (also installs FastMCP)
Minimum version langchain>=1.4.0
Namespace langchain.mcp
Status Beta; emits a LangChainBetaWarning once per process on import
Core class MCPAdapter (async context manager)
Foundation FastMCP client
Replaces langchain-mcp-adapters (MultiServerMCPClient)
Supported MCP primitive Tools (no wrapper yet for prompts and resources)

What is MCP and why do we need it?

Without MCP, every AI application has to write its own integration for every service it wants to use. Say we have five applications and ten services; that's fifty separate integrations. With MCP, a service is written once as an MCP server, and every application that supports MCP can use the same server. There's a common analogy for this: MCP is like a USB-C port for AI applications. As long as the plug is standard, it doesn't matter which device we connect.

The protocol has three core roles:

Role What it does LangChain counterpart
Host The AI application that manages one or more clients Our agent application
Client The component that holds the connection to one server fastmcp.Client (created internally by the adapter)
Server The program that exposes tools, resources and prompts A server written with FastMCP or another SDK

MCP has two layers. The data layer defines the JSON-RPC 2.0 message structure, the discovery step and primitives like tools, resources and prompts. The transport layer defines how those messages travel: stdio between local processes, or Streamable HTTP over the network.

As a flow:

User ──► Agent (create_agent)
            │  model picks a tool
            ▼
       LangChain tool (produced by MCPAdapter)
            │  tools/call (JSON-RPC)
            ▼
       MCP Client ──transport (stdio / HTTP)──► MCP Server
            ▲                                      │
            └──────────── CallToolResult ◄─────────┘
            │
            ▼
       ToolMessage ──► Model ──► Answer to the user

An important note: besides tools, MCP servers can also expose resources (readable data) and prompts (ready-made templates). langchain.mcp currently focuses only on tools; we'll see how to reach prompts and resources in the migration section.

Installation

Installing LangChain with the mcp extra is enough; it brings FastMCP along:

pip install "langchain[mcp]"

With uv:

uv add "langchain[mcp]"

The langchain.mcp namespace is still in beta. On the first import we see a LangChainBetaWarning once per process, and it's worth keeping in mind that the API may change between releases.

Writing our first MCP server

Before moving to the client side, let's have a server to talk to. Since LangChain's MCP support is built on FastMCP, writing the server with FastMCP is the most natural path:

# weather_server.py
from fastmcp import FastMCP

mcp = FastMCP(name="WeatherServer")


@mcp.tool
def get_forecast(city: str, days: int = 1) -> str:
    """Get the weather forecast for a city.

    Args:
        city: City name, e.g. "Oslo"
        days: Number of days to forecast (1-7)
    """
    return f"{city}: sunny for {days} day(s), 18°C"


if __name__ == "__main__":
    mcp.run()  # default transport: stdio

In this example:

  • FastMCP(name=...) sets the server's identity; this name also shows up in the tool metadata on the client side (we'll see it in the second article).
  • The @mcp.tool decorator turns the function into an MCP tool. It works almost like LangChain's @tool: the function name becomes the tool name, the docstring the description and the type hints the input schema.
  • When mcp.run() is called with no arguments it uses the stdio transport; the server talks over stdin/stdout and is launched by the client as a subprocess.

To make the same server reachable over the network, changing the transport is enough:

if __name__ == "__main__":
    mcp.run(transport="http", host="127.0.0.1", port=8000)

The server then serves Streamable HTTP at http://localhost:8000/mcp and can handle several clients at once.

The parameters of @mcp.tool directly affect how the agent behaves on the client side. The most common ones:

Parameter What it does
name Tool name shown to the model. Defaults to the function name.
description Tool description. If set, the description part of the docstring is ignored.
title Human-readable title. Some clients drop tools that have no title.
tags A set of tags to group and filter tools.
annotations Behavior hints like readOnlyHint, destructiveHint, idempotentHint, openWorldHint.
meta Free-form metadata sent to the client as the _meta field (version, owning team, etc.).
timeout Execution time limit in seconds; an MCP error is returned if exceeded.
output_schema JSON schema of the structured output. Generated from the return type if omitted.

annotations and meta are especially important, because LangChain carries them into the tool metadata and we can build policies on top of them, such as "ask for human approval on destructive tools". We cover this in detail in the MCP tools article.

First agent with MCPAdapter

With the server ready we can move to the client side. The basic flow has three steps: open the adapter, discover the tools and build the agent.

import asyncio
from pathlib import Path

from langchain.agents import create_agent
from langchain.mcp import MCPAdapter


async def main():
    async with MCPAdapter(Path("weather_server.py")) as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("openai:gpt-6.1-sol", tools)

    # We left the context, but the agent is still usable
    result = await agent.ainvoke(
        {"messages": [{"role": "user", "content": "What's the weather in Oslo?"}]}
    )
    print(result["messages"][-1].content)


asyncio.run(main())

In this example:

  • MCPAdapter(...) is an async context manager. Entering the async with block connects the underlying FastMCP client; leaving it releases the connection.
  • list_tools() discovers the server's tool catalog and converts each tool into a standard LangChain BaseTool. These can be passed to create_agent directly, like any other tool.
  • The returned tools hold the client. That's why the agent keeps working after we leave the context; on each tool call the client is reopened as needed. We'll go through this behavior in the connections article.
  • We call the agent with ainvoke. MCP tools are async-only; the adapter builds them with only a coroutine, with no sync body. So we'll need ainvoke / astream rather than invoke.

Anatomy of an adapted tool

Each tool returned by list_tools() is a StructuredTool whose fields come from the server:

LangChain field Source
name MCP tool name (prefixed {server}_{tool} with multiple servers)
description MCP tool description (empty string if missing)
args_schema MCP inputSchema (JSON Schema)
response_format Always "content_and_artifact"
metadata Annotations, _meta and server identity under {"mcp": {...}}

The response_format="content_and_artifact" setting means the tool result is split into two parts: the content the model reads and the artifact the application uses. So the structured data returned by the server can reach the application without bloating the model's context. We'll look at this with examples in the next article.

The MCPAdapter API

The part of the class we actually use is pretty small:

MCPAdapter(target: MCPAdapterTarget)
Member Kind Description
target Constructor parameter What to connect to: URL, Path, transport, FastMCP server, MCPConfig, fastmcp.Client or ClientGroup
list_tools(*, cache_mode="use") Async method Discovers tools and returns list[BaseTool]
client Property The underlying fastmcp.Client or ClientGroup, for advanced MCP operations

list_tools takes a single parameter, cache_mode, which selects how discovery interacts with the client-side response cache:

cache_mode Behavior
"use" (default) Serves a valid cached list if present; otherwise fetches from the server and stores it
"refresh" Fetches a fresh list from the server and repopulates the cache
"bypass" Skips the cache entirely

The cache itself is configured on the client (Client(cache=...)); cache_mode only selects how discovery reads it. We cover the details in the connections article.

There's also a lower-level helper: as_langchain_tool. It converts a single MCP tool into a LangChain tool that's called through the client we pass in. Since it's a coroutine, we need to await it:

from fastmcp import Client
from langchain.mcp import as_langchain_tool

client = Client("https://example.com/mcp")
async with client:
    mcp_tools = await client.list_tools()

# Convert only selected tools
tools = [
    await as_langchain_tool(t, client)
    for t in mcp_tools
    if t.name.startswith("search_")
]
Parameter What it does
tool An MCP Tool returned by fastmcp.Client.list_tools()
client The fastmcp.Client or ClientGroup to call the tool through

For everyday use MCPAdapter.list_tools() is enough. as_langchain_tool is handy when we want to filter the server's catalog ourselves or bind a single tool to a custom client. One difference worth keeping in mind: elicitation support (second article) is added to the client by MCPAdapter; a bare Client we create ourselves and use with as_langchain_tool doesn't get it.

Transports: how do we pass the target?

My favorite thing about MCPAdapter is that it picks the transport by looking at the type of target we give it. Connecting to an in-memory server, a local script over stdio or a remote URL only differs in what we pass to the adapter:

from pathlib import Path

from langchain.mcp import MCPAdapter
from weather_server import mcp as server  # a FastMCP instance

# In-memory: no subprocess, no socket. Ideal for tests.
in_memory = MCPAdapter(server)

# Script path: one subprocess per adapter, over stdio
stdio = MCPAdapter(Path("weather_server.py"))

# A string must be an http(s) URL: Streamable HTTP
http = MCPAdapter("http://localhost:8000/mcp")

Here is everything that can be a target:

Target Type Transport When?
http/https URL str Streamable HTTP Remote or networked servers
Script path Path stdio (subprocess) Local tools, development
Transport object e.g. StreamableHttpTransport Preconfigured When headers or httpx settings are needed
FastMCP server FastMCP In-memory Unit tests
MCPConfig dict {"mcpServers": {...}} Inferred per server Several servers behind one adapter
Prebuilt client fastmcp.Client Client's setting Full control over auth, caching, protocol era
Client group ClientGroup Per member Separate connection/auth per server

The last three options come up a lot in the rest of this series: MCPConfig and ClientGroup star in the connections article, and fastmcp.Client(auth=...) in the auth article.

When we need transport-level settings such as extra headers, we can build the transport object ourselves:

from fastmcp.client.transports import StreamableHttpTransport
from langchain.mcp import MCPAdapter

transport = StreamableHttpTransport(
    "https://example.com/mcp",
    headers={"X-Tenant-Id": "acme"},
)
async with MCPAdapter(transport) as adapter:
    tools = await adapter.list_tools()

Writing tests with an in-memory server

The in-memory target is the easiest way to test an agent's MCP integration without starting a real process or opening a port:

import pytest
from fastmcp import FastMCP
from langchain.mcp import MCPAdapter

server = FastMCP("TestServer")


@server.tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b


@pytest.mark.asyncio
async def test_add_tool():
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()

    add_tool = next(t for t in tools if t.name == "add")
    result = await add_tool.ainvoke({"a": 2, "b": 3})
    assert "5" in str(result)

Here the server and client run in the same Python process and talk directly through memory. Since it runs in CI without any network dependency, it's fast and deterministic.

Why can a string target only be a URL?

At first glance this rule may look like an unnecessary restriction, but there's a serious security reason behind it. When FastMCP resolves a string, it tests it as a filesystem path first, then as a URL. So a string like "tools.py" is launched as a subprocess if that file exists on disk.

Strings are usually the form a target arrives in from outside: a config file, a database record or the output of a model. To prevent such a value from executing local code without us noticing, MCPAdapter rejects strings that don't look like a URL. When we want to reach a local server, we'll need to use a Path, a transport object or an MCPConfig, all of which make our intent explicit.

MCPAdapter("http://localhost:8000/mcp")   # ✅ URL
MCPAdapter(Path("weather_server.py"))      # ✅ explicitly a local script
MCPAdapter("weather_server.py")            # ❌ rejected

A real server: the LangChain docs MCP

We don't even need to write our own server to try things out. The LangChain documentation publishes a public MCP server at https://docs.langchain.com/mcp that doesn't require an API key:

from langchain.agents import create_agent
from langchain.mcp import MCPAdapter


async def ask_docs(question: str) -> str:
    async with MCPAdapter("https://docs.langchain.com/mcp") as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("openai:gpt-6.1-sol", tools)

    result = await agent.ainvoke(
        {"messages": [{"role": "user", "content": question}]}
    )
    return result["messages"][-1].content


# await ask_docs("How do I add short-term memory to a LangChain agent?")

The tools the server exposes:

Tool Description
search_docs_by_lang_chain Searches the docs for relevant guides, how-tos and examples
query_docs_filesystem_docs_by_lang_chain Reads the docs through a virtual filesystem (rg, head, cat)
submit_feedback Reports a problem with a documentation page

The same server can be added as an MCP server to editors like Claude Code, Cursor or VS Code; a nice example of an agent reaching up-to-date documentation without custom tools.

Migrating from langchain-mcp-adapters

Before LangChain 1.4.0, MCP support came with a separate package, langchain-mcp-adapters, centered on MultiServerMCPClient. That class is now collapsed into a single MCPAdapter. On the install side, removing the old package and adding the new one is enough:

pip uninstall langchain-mcp-adapters
pip install "langchain[mcp]"

On the code side, the biggest change is the shape of the configuration. Before:

from langchain_mcp_adapters.client import MultiServerMCPClient

client = MultiServerMCPClient(
    {
        "math": {"transport": "stdio", "command": "python", "args": ["/path/to/math_server.py"]},
        "weather": {"transport": "http", "url": "http://localhost:8000/mcp"},
    }
)
tools = await client.get_tools()

After:

from langchain.mcp import MCPAdapter

config = {
    "mcpServers": {
        "math": {"command": "python", "args": ["/path/to/math_server.py"]},
        "weather": {"url": "http://localhost:8000/mcp"},
    }
}
async with MCPAdapter(config) as adapter:
    tools = await adapter.list_tools()

The config now uses the standard MCPConfig (mcpServers) shape also used by tools like Claude Desktop and Cursor, and there's no transport key; the transport is inferred from each entry (command → stdio, url → HTTP).

The mappings we'll run into during migration:

langchain-mcp-adapters langchain.mcp
MultiServerMCPClient(...).get_tools() MCPAdapter(...).list_tools()
load_mcp_tools MCPAdapter(...).list_tools()
convert_mcp_tool_to_langchain_tool as_langchain_tool (now a coroutine)
MCPToolArtifact Same name, in langchain.mcp
tool_name_prefix Automatic {server}_{tool} prefix with multiple servers
handle_tool_errors Removed; behavior is fixed (second article)
tool_interceptors @wrap_tool_call middleware
Callbacks(on_progress=..., on_logging_message=...) Client(progress_handler=..., log_handler=...)
Callbacks(on_elicitation=...) Automatic, via a LangGraph interrupt
Per-connection auth / headers fastmcp.Client(auth=...) / StreamableHttpTransport(url, headers=...)
httpx_client_factory On the FastMCP transport
session(...) Not exposed; each tool call opens its own session

A short example of how callbacks move over:

from fastmcp.client import Client
from langchain.mcp import MCPAdapter


async def on_progress(progress: float, total: float | None, message: str | None):
    print(f"Progress: {progress}/{total} {message or ''}")


client = Client("https://example.com/mcp", progress_handler=on_progress)
async with MCPAdapter(client) as adapter:
    tools = await adapter.list_tools()

Not supported yet

Some features are either not wrapped by langchain.mcp yet or were removed from the MCP protocol itself:

Feature Status
Prompts (get_prompt, load_mcp_prompt) No wrapper; reachable through FastMCP via adapter.client.get_prompt(...)
Resources (get_resources, load_mcp_resources) No wrapper; reachable via adapter.client.read_resource(...)
Sampling and roots Not supported; raises NotImplementedError
HTTP+SSE transport Deprecated in the protocol; still works through Client(SSETransport(url))
WebSocket No FastMCP transport; the server needs to move to Streamable HTTP
to_fastmcp (LangChain tool → MCP tool) No equivalent

The lack of sampling (a server asking the client to run an LLM completion) and roots (a server asking which local paths the client can reach) is a deliberate decision: the modern MCP era is stateless, and there's no longer a live channel for the server to call back into the client mid-request. We expand on these concepts in the protocol eras section of the connections article.

Wrapping up

In this article we saw what MCP is, why it's useful and how to connect it to an agent with MCPAdapter in LangChain. What we do is actually quite simple: we give the adapter a target, get the tools with list_tools() and pass them to create_agent. From the agent's point of view, these tools are no different from the ones we write ourselves. Passing the target as a URL, a Path or an in-memory server is enough; the adapter picks the transport on its own.

In the second article we'll dig a little deeper into these tools. We'll talk about how we handle images, structured data and errors returned by tools, how we ask for human approval with MCP annotations, and elicitation, where the server asks the user a question while a tool is running. See you in the next article.

Sources

The langchain.mcp API described here is in beta and may change between releases. It's a good habit to verify the details for the version you're using against the official documentation.

  • langchain
  • mcp
  • agents
  • tools
  • python

← Back to all posts