Skip to main content

AI20 min read

LangChain MCP Tools: Outputs, Metadata, HITL, Elicitation

MCP tool results become ToolMessages with content, artifact and error status; annotations drive human-in-the-loop gates and elicitation pauses via interrupt.

Connecting to an MCP server and handing the tools to an agent is just the beginning. The questions I was really curious about start after a tool runs. When the server returns a screenshot, how does the model see it? When a structured JSON comes back, where does that data go? Does the agent crash if the server returns an error? And who approves a tool that deletes data before it runs? In this article we look for answers to all of these, and we'll see that MCPAdapter actually does two jobs: it turns MCP results into LangChain's ToolMessage structure, and it carries what the server says about a tool to us as metadata.

In the first article of the series we covered MCPAdapter, transports and the first agent. In this article we go inside the tools: we focus on how outputs are handled, metadata, human approval with MCP annotations and elicitation, where the server asks the user for input while a tool is running.

Scope of this article: We touch on the human-in-the-loop (HITL) middleware and LangGraph's interrupt mechanism only in relation to MCP. We'll cover both topics separately and in detail in upcoming articles; for now it's enough to see how we pause and resume an agent.

Using an MCP tool in an agent

As a reminder, the basic flow is: discover tools with list_tools() and pass them to create_agent. From the agent's perspective these are ordinary LangChain tools; the model picks a tool, LangChain calls it and the result returns to the model as a ToolMessage.

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


async def run_agent(server) -> dict:
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("openai:gpt-6.1-sol", tools)
        return await agent.ainvoke(
            {"messages": [{"role": "user", "content": "What is the forecast for Oslo?"}]}
        )

In the examples in this article, the server parameter can be any of the targets we saw in the first article: a URL, a Path, an in-memory FastMCP server or a prebuilt client.

Tool outputs: content, artifact and status

When an MCP tool runs, the server returns a CallToolResult. This result has three important fields, and the adapter carries each into a different part of the ToolMessage:

MCP result ToolMessage counterpart Used by
content (text, image, resource...) content / content_blocks The model
structuredContent (JSON) artifact["structured_content"] The application
isError status="error" Model and application

This split comes from the adapter building every tool with response_format="content_and_artifact". What the model needs to see and the raw data the application needs are kept apart.

Multimodal content

The adapter converts model-visible MCP content into LangChain's standard content blocks. For example, the result of a tool that returns a screenshot reaches the model as an image block.

First, a simple server-side tool that returns an image:

# screenshot_server.py
from fastmcp import FastMCP
from fastmcp.utilities.types import Image

mcp = FastMCP("ScreenshotServer")


@mcp.tool
def take_screenshot() -> Image:
    """Take a screenshot of the current screen."""
    return Image(path="screen.png")

On the client side we can walk through the blocks via ToolMessage.content_blocks:

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


async def access_multimodal_tool_content(server) -> dict:
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("openai:gpt-6.1-sol", tools)
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Take a screenshot."}]}
        )

    for message in result["messages"]:
        if not isinstance(message, ToolMessage):
            continue
        for block in message.content_blocks:
            if block["type"] == "text":
                print(f"Text: {block['text']}")
            elif block["type"] == "image":
                print(f"Image mime type: {block.get('mime_type')}")
                print(f"Image base64: {block.get('base64', '')[:20]}...")

    return result

In this example:

  • content_blocks gives the provider-agnostic list of standard blocks; we can handle text, image and file types in the same loop.
  • Image blocks carry base64 and mime_type fields; we can render or store them in a UI.
  • For the model to actually "see" the image it has to be multimodal (vision-capable); otherwise the provider may reject the block.

The conversion rules I pulled from the adapter's source code:

MCP content type LangChain block
TextContent text
ImageContent image (base64 + mime_type)
ResourceLink image (if mime is image/*) or file (with url)
EmbeddedResource (text) text
EmbeddedResource (blob) image (if mime is image/*) or file (with base64)
AudioContent Not supported; NotImplementedError

If we work with servers that return audio, this limitation is worth knowing: the conversion error is treated like a transport error and raised to us rather than sent to the model.

Structured content

When a tool returns structured data, the adapter attaches it to the ToolMessage as an artifact instead of folding it into the model-visible text. In FastMCP, annotating a tool's return type as a dict, dataclass or Pydantic model is enough to produce structured output:

# crm_server.py
from pydantic import BaseModel
from fastmcp import FastMCP

mcp = FastMCP("CRM")


class User(BaseModel):
    id: int
    name: str
    plan: str


@mcp.tool
def get_user(user_id: int) -> User:
    """Look up a user by id."""
    return User(id=user_id, name="Ada", plan="pro")

On the client side we reach the artifact like this:

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


async def run_agent_structured(server) -> dict:
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("openai:gpt-6.1-sol", tools)
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Look up user 42."}]}
        )

    for message in result["messages"]:
        if isinstance(message, ToolMessage) and message.artifact is not None:
            structured = message.artifact["structured_content"]
            print(f"Structured content: {structured}")

    return result

The artifact is an MCPToolArtifact (TypedDict) with a single field for now: structured_content, the result's structuredContent. If the tool returns no structured content, artifact stays None; so a non-None artifact always carries structured_content. It's designed as a TypedDict so that other MCP result fields can be added later without changing its shape.

This split is very useful in practice: a short summary goes to the model, while our UI can render the full JSON as a table or card. It's the MCP counterpart of the content_and_artifact idea we saw in the tools article.

Errors

An MCP tool result carries an isError flag. When the server returns isError=True, the adapter converts it into a ToolMessage with status="error" that carries the server's own error message. This lets the agent read the error and correct itself.

In FastMCP the clearest way to return an error from a tool is to raise ToolError:

# calc_server.py
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError

mcp = FastMCP("Calc")


@mcp.tool
def divide(a: float, b: float) -> float:
    """Divide a by b."""
    if b == 0:
        raise ToolError("Division by zero is not allowed. Ask for a non-zero divisor.")
    return a / b

On the client side we can tell failed tool messages apart by their status:

async def divide_by_zero(server) -> dict:
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("openai:gpt-6.1-sol", tools)
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Use the divide tool to calculate 10 divided by 0."}]}
        )

    for message in result["messages"]:
        if isinstance(message, ToolMessage) and message.status == "error":
            print(f"Tool reported: {message.text}")

    return result

It's very important to separate two kinds of errors here:

Error kind Example Behavior
Server-reported error (isError=True) Invalid argument, business rule violation Returns to the model as ToolMessage(status="error"); the agent continues
Transport / session error Server down, connection dropped Raises an exception; the agent run stops
Unconvertible content Audio content Raises an exception

When we think about why, it makes sense. A model can read an error like "this argument is invalid" and try again with a different argument. But there's nothing it can do with "the server is unreachable". That's also why the handle_tool_errors option from the old langchain-mcp-adapters package was removed; the behavior is now fixed. If we want to catch connection errors and show the user a meaningful message, we need to do that around the agent call or in a wrap_tool_call middleware.

A small detail: if the server returns an error with empty content, the adapter substitutes a descriptive text block, because some providers don't accept an empty ToolMessage.

Tool metadata

Each tool produced by the adapter may carry its MCP provenance in the LangChain tool's metadata under an mcp namespace:

tool.metadata
# {
#     "mcp": {
#         "tool": {
#             "annotations": {
#                 "destructive_hint": True,
#                 "read_only_hint": False,
#             },
#             "_meta": {"origin": "crm"},
#         },
#         "server": {
#             "name": "crm",
#             "version": "2.1.0",
#         },
#     },
# }
Field Source Contents
mcp.tool.annotations annotations on the server MCP behavior hints, with Python-friendly snake_case names
mcp.tool._meta meta on the server Opaque metadata from the server; the field name is kept as in the protocol
mcp.server The connection's server info Name and version of the server that advertised the tool

On the server side we produce this metadata like so:

from fastmcp import FastMCP

mcp = FastMCP("crm", version="2.1.0")


@mcp.tool(
    annotations={"destructiveHint": True, "readOnlyHint": False},
    meta={"origin": "crm"},
)
def delete_customer(customer_id: int) -> str:
    """Permanently delete a customer record."""
    return f"Customer {customer_id} deleted"

The annotations defined by MCP:

Annotation (server) Metadata key (LangChain) Meaning
readOnlyHint read_only_hint The tool doesn't modify its environment
destructiveHint destructive_hint The tool may perform destructive updates
idempotentHint idempotent_hint Repeating the call with the same arguments has no extra effect
openWorldHint open_world_hint The tool interacts with external entities
title title Human-readable title

There's one thing to keep in mind here: none of these fields are required. A server may send annotations, _meta or server info, only some of them, or none at all. So when reading metadata it's a good idea to give a default value with .get() at every step, so a missing field doesn't break our code:

from langchain.tools import BaseTool


def is_destructive(tool: BaseTool) -> bool:
    """Read the MCP destructive hint off the adapter's tool metadata."""
    annotations = (
        (tool.metadata or {}).get("mcp", {}).get("tool", {}).get("annotations", {})
    )
    return annotations.get("destructive_hint", False)

I'd also like to add a caveat: annotations are, as the name says, hints. The server declares them itself; an untrusted server claiming "I'm read-only" isn't a security guarantee on its own. Using annotations to build policies makes sense, but for untrusted servers additional checks based on tool names or arguments are a good idea.

Intercepting tool calls

The old package's tool_interceptors are gone; instead we use LangChain's @wrap_tool_call middleware. This middleware wraps every tool the agent runs, not just MCP tools; but thanks to the metadata we can tell MCP tools apart:

from collections.abc import Awaitable, Callable

from langchain.agents import create_agent
from langchain.agents.middleware import wrap_tool_call
from langchain.mcp import MCPAdapter
from langchain.messages import ToolMessage
from langchain.tools.tool_node import ToolCallRequest


@wrap_tool_call
async def log_mcp_calls(
    request: ToolCallRequest,
    handler: Callable[[ToolCallRequest], Awaitable[ToolMessage]],
) -> ToolMessage:
    mcp_info = (request.tool.metadata or {}).get("mcp", {})
    server = mcp_info.get("server", {}).get("name", "local")
    print(f"[{server}] calling: {request.tool_call['name']}")
    result = await handler(request)
    print(f"[{server}] done: {request.tool_call['name']} ({result.status})")
    return result


async def agent_with_interception(target):
    async with MCPAdapter(target) as adapter:
        tools = await adapter.list_tools()
        return create_agent("openai:gpt-6.1-sol", tools, middleware=[log_mcp_calls])

In this example:

  • request.tool_call carries the call the model produced (name, args, id); arguments can also be rewritten here.
  • request.tool is the BaseTool being called; we reach its MCP provenance via metadata["mcp"].
  • handler(request) runs the actual tool. Since MCP tools are async, we wrote the middleware as async def and used await handler(...).

We covered middleware and wrap_tool_call in more detail in the error handling section of the tools article.

Human-in-the-loop: an approval gate driven by annotations

In my opinion, this is where being able to read metadata really pays off. To decide which tool needs approval, we don't have to write tool names one by one into our code. Instead, we can look at what the server says about the tool. So the MCP annotation classifies the tool, and LangChain's human-in-the-loop middleware applies the approval rule.

We'll go through human-in-the-loop in detail in a separate article. For now, here's what we need to know: HumanInTheLoopMiddleware pauses the agent with an interrupt before certain tool calls, saves the state with a checkpointer and continues from where it left off once a human decision arrives.

from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langchain.agents.middleware.human_in_the_loop import InterruptOnConfig
from langchain.mcp import MCPAdapter
from langchain.tools import BaseTool
from langchain.tools.tool_node import ToolCallRequest
from langgraph.checkpoint.memory import InMemorySaver


def is_destructive(tool: BaseTool) -> bool:
    annotations = (
        (tool.metadata or {}).get("mcp", {}).get("tool", {}).get("annotations", {})
    )
    return annotations.get("destructive_hint", False)


async def gate_destructive_tools(server):
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()

    # Read the metadata once, during discovery
    destructive = {tool.name for tool in tools if is_destructive(tool)}

    def needs_approval(request: ToolCallRequest) -> bool:
        return request.tool_call["name"] in destructive

    gate = InterruptOnConfig(
        allowed_decisions=["approve", "reject"],
        when=needs_approval,
    )
    interrupt_on: dict[str, bool | InterruptOnConfig] = {
        tool.name: gate for tool in tools
    }
    return create_agent(
        "openai:gpt-6.1-sol",
        tools,
        middleware=[HumanInTheLoopMiddleware(interrupt_on=interrupt_on)],
        checkpointer=InMemorySaver(),
    )

In this example:

  • interrupt_on is a dict mapping tool names to approval configs. A value can be True (interrupt with defaults), False (auto-approve) or an InterruptOnConfig.
  • InterruptOnConfig.allowed_decisions limits the decisions a human can make. Here we allow only approve and reject; editing arguments (edit) is off.
  • InterruptOnConfig.when is a predicate that receives each pending tool call (ToolCallRequest) and returns whether it needs approval. We give a single gate to every tool and let this function decide; so if the server adds a new destructive tool tomorrow, we don't have to change our code.
  • checkpointer stores the agent state during the interrupt. Approval flows don't work without a checkpointer; in production we'll want a persistent checkpointer instead of InMemorySaver.

The decisions available in InterruptOnConfig:

Decision Effect
approve The tool runs with the arguments the model proposed
edit The arguments are changed before execution
reject The tool doesn't run; the model is told it was rejected
respond The tool doesn't run; the human's answer is returned as the tool result (for "ask user" tools)

When the agent calls a tool that needs approval, the run pauses. We continue by sending the decision with the same thread_id:

from langgraph.types import Command

config = {"configurable": {"thread_id": "crm-1"}}

paused = await agent.ainvoke(
    {"messages": [{"role": "user", "content": "Delete customer 42."}]},
    config,
)
print(paused["__interrupt__"])  # calls waiting for approval

resumed = await agent.ainvoke(
    Command(resume={"decisions": [{"type": "approve"}]}),
    config,
)

Conditional approval based on arguments

The when predicate can look at a call's arguments, not just the tool's name. That way a tool runs freely for safe inputs and pauses only for risky ones. For example, when delete_file targets a protected directory:

PROTECTED = ("/etc/", "/var/lib/", "/home/")


def needs_approval(request: ToolCallRequest) -> bool:
    name = request.tool_call["name"]
    if name not in destructive:
        return False
    if name == "delete_file":
        path = request.tool_call["args"].get("path", "")
        return path.startswith(PROTECTED)
    return True

Here we combine the metadata classification with an argument check: we ask for approval only when the tool is marked destructive and its input is risky. Because the predicate runs again when the agent resumes, it has to return the same result for the same call; otherwise the decision may be ignored. We'll discuss these details in the human-in-the-loop article.

Server requests during tool execution: elicitation

Most tools finish without asking the client for anything. But sometimes the server needs to ask the user something mid-task: "Which date should I book?", "Do you confirm this operation?" In MCP this is called elicitation.

MCPAdapter passes these questions to us as a LangGraph interrupt. We can picture the flow like this:

Agent ──tools/call──► MCP Server
                        │ "need a date" (InputRequiredResult)
                        ▼
         MCPAdapter pauses the run with interrupt()
                        │
        The application shows the question to the user
                        │
    Resume with Command(resume={"responses": {...}})
                        │
Agent ──tools/call (with answers)──► MCP Server ──► Result

The reason I like this approach: the person already following the agent's work answers the server's question from the same place. So the approval flow we saw in the previous section and elicitation work with the same "pause, ask, resume" logic.

Server side: the guard pattern

In the modern MCP protocol (2026-07-28), a server can't send a separate request to the client and wait for the answer while a tool runs, because the protocol is stateless and there's no such back-channel. Instead the tool returns what it needs as an InputRequiredResult. The client attaches the answer and calls the tool again; the tool runs from the top, sees the answer and either asks the next question or returns the result. FastMCP calls this the guard pattern:

# booking_server.py
from fastmcp import FastMCP, Context
from mcp.types import InputRequiredResult, ElicitRequest, ElicitRequestFormParams

mcp = FastMCP("Booking")


def ask_date() -> InputRequiredResult:
    params = ElicitRequestFormParams(
        message="Which date should we book?",
        requested_schema={
            "type": "object",
            "properties": {"date": {"type": "string"}},
            "required": ["date"],
        },
    )
    return InputRequiredResult(
        result_type="input_required",
        input_requests={"date": ElicitRequest(method="elicitation/create", params=params)},
    )


@mcp.tool
async def book_table(party_size: int, ctx: Context) -> str | InputRequiredResult:
    """Book a restaurant table."""
    responses = ctx.input_responses
    if responses is None:
        return ask_date()

    answer = responses["date"]
    if answer.action != "accept":
        return "Booking cancelled."
    return f"Table for {party_size} booked on {answer.content['date']}."

In this example:

  • ctx.input_responses is None on the first round; on later rounds it carries the client's answers under the key we gave the request ("date").
  • requested_schema is the JSON schema of the expected answer. MCP only allows flat objects with primitive fields (string, number, boolean, enum) here.
  • We need to check the answer's action before reading content; if the user declined or cancelled, there's no content.

In the old (handshake-era) protocol the same thing was done with await ctx.elicit(...). FastMCP's documentation covers both paths in detail; the LangChain side works with the modern guard pattern.

Client side: answering the interrupt

On the LangChain side elicitation is on by default; there's nothing extra to enable. The only requirement is a place for the paused run to wait, meaning a checkpointer and a consistent thread_id:

from typing import Any

from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command


async def book_with_elicitation(server) -> dict:
    async with MCPAdapter(server) as adapter:
        tools = await adapter.list_tools()

        agent = create_agent("openai:gpt-6.1-sol", tools, checkpointer=InMemorySaver())
        config: Any = {"configurable": {"thread_id": "booking-1"}}

        paused = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Book a table for 4."}]},
            config,
        )
        [interrupt] = paused["__interrupt__"]
        [question] = interrupt.value["requests"]
        print(question["message"])  # "Which date should we book?"

        # In a real app this answer comes from the user
        answer = {"action": "accept", "content": {"date": "2026-12-14"}}
        return await agent.ainvoke(
            Command(resume={"responses": {question["key"]: answer}}),
            config,
        )

The interrupt payload (interrupt.value) is an MCPElicitationInterrupt. Based on the types in the langchain.mcp.elicitation module, its fields are:

Field Description
type Always "mcp_elicitation"; lets us recognize the interrupt as an elicitation
tool_name Name of the MCP tool waiting for an answer
requests Every question in this round, in the order they should be asked

Each question in requests comes in one of two modes:

Mode Fields What's expected
form key, message, mode, requested_schema An answer with content matching the schema
url key, message, mode, url The user visits an address; confirmation without content

We send answers with Command(resume={"responses": {key: answer}}), under the server's own key. That way nothing has to be tracked across the pause. Each answer carries one of three actions:

Action Meaning
accept Send content matching the schema for a form; for URL mode, confirm completion without content
decline The user refuses to provide the information; the tool call continues
cancel The user cancels the interaction; abandons the tool call, not just the question

The adapter forwards the answer to the server, and the server decides how the tool call finishes. There's validation too: if a question has no answer, or the action isn't one of these three, the adapter raises a ValueError.

Things to watch out for with elicitation

I think this is the most important point in this section: when we resume the agent, the tool runs from the beginning. If the server asks its question before doing any work, there's no problem. But if it does some work and then asks, that work is repeated every round. So any work done before the question needs to be safe to run again (idempotent). For example, taking a payment first and then asking for a date could mean charging the user twice.

The other limits, in one table:

Situation Behavior
A prebuilt client already has its own elicitation_handler The adapter doesn't override it; that handler keeps answering
The server asks for sampling or roots NotImplementedError; the modern protocol has no back-channel for these
The server returns a "continuation" round with no questions NotImplementedError; long-running background work isn't supported this way
A legacy-era server pushes elicitation Can't be answered via interrupt; needs a client with its own handler

For the last case, building a prebuilt fastmcp.Client with our own handler is enough; the adapter leaves the client as it is:

from fastmcp import Client
from fastmcp.client.elicitation import ElicitResult


async def handler(message, response_type, params, ctx):
    # e.g. ask the user in a CLI
    value = input(f"{message} ")
    return ElicitResult(action="accept", content=response_type(date=value))


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

The interrupt-based approach, on the other hand, fits scenarios where the agent runs behind a web UI or LangSmith Agent Server better, because the question reaches the user through the same channel as the agent's other approval requests.

Wrapping up

In this article we saw how MCP tool results are handled on the LangChain side. Content for the model goes to content_blocks, and structured data for our application goes to artifact. Errors reported by the server go back to the model as status="error", so the model can correct itself. Since we can reach what the server says about a tool through metadata["mcp"], we can set up rules like human approval without listing tool names one by one. Elicitation uses the same interrupt logic to let the server ask the user questions.

In the next article we move on to connections. We'll talk about when the adapter opens and closes connections, how we combine several servers with MCPConfig and ClientGroup, what we can do in an application serving many requests, caching and protocol eras. 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
  • human-in-the-loop
  • python

← Back to all posts