Skip to main content
Text ready — video coming soon

Connect and check tools

You have reached the point where the pieces can meet. The MCP lesson exposed a local tool. The workflow lesson let you trace data through LangChain. Here, a LangChain tool will call that actual MCP server.

We will keep the connection explicit so you can inspect every boundary. You will verify:

  • The exact result for a known title and an explicit response for an unknown one.
  • Rejection of arguments outside the declared input shape.
  • Client cleanup after a real protocol-call failure.

This is a real local tool invocation; it does not involve a language model choosing a tool or a paid provider call.

State what the connected tool may do​

The specification is small enough to check directly:

  • Accept one string field named title, with no additional fields.
  • Ask the configured local MCP server for that public chapter's lesson count.
  • Return its text result, including an explicit not-found response.
  • Do not let the caller choose a server command, file path or private dataset.
  • Close the client session after the call, including failure cleanup.

This describes behaviour and limits before the framework code appears. It also tells you what a test must challenge. The table contains public chapter information; it grants no access to any private solution data.

Wrap the connection as a LangChain tool​

Keep book_server.py from the MCP lesson in the same folder. Your environment needs the versions already introduced: FastMCP 4.1.3, langchain-core 1.7.0 and Pydantic 2.14.1.

Save this complete client as connected_book_tool.py:

import asyncio
import sys
from pathlib import Path

from fastmcp import Client
from fastmcp.client.transports import StdioTransport
from langchain_core.tools import tool
from pydantic import BaseModel, ConfigDict

SERVER = Path(__file__).with_name("book_server.py")

class ChapterArguments(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
title: str

@tool("book_chapter", args_schema=ChapterArguments)
async def book_chapter(title: str) -> str:
"""Read the public lesson count for an exact chapter title."""
transport = StdioTransport(
command=sys.executable,
args=[str(SERVER)],
)
async with Client(transport, timeout=5, init_timeout=10) as client:
result = await client.call_tool(
"chapter_lessons", {"title": title}
)
return result.content[0].text

async def main():
answer = await book_chapter.ainvoke(
{"title": "Python and Roots"}
)
print(answer)

if __name__ == "__main__":
asyncio.run(main())

Run uv run python connected_book_tool.py. Expect Python and Roots: 7 lessons, with any server diagnostics on their separate stream.

The @tool decorator creates a LangChain tool object with a name, description and argument schema. It does not leave us with an ordinary function called directly in the same way. ainvoke is the tool's asynchronous invocation interface.

args_schema=ChapterArguments applies the Pydantic rules before the function body runs. The body then constructs the trusted transport, opens the client session, calls the MCP tool and reads the agreed text result. It returns through LangChain to the caller.

We open a session within each call here so its lifetime is easy to see. As in the MCP lesson, requests have a five-second default timeout and initialisation has a ten-second limit. A solution that keeps connections open longer needs to manage their lifetime deliberately too. We are not relying on a global client that may already have closed when a tool later tries to use it.

Follow the path when something changes​

The boundaries are now visible in order:

BoundaryWhat should be established
Caller to LangChain toolThe argument dictionary matches the declared strict model
Tool to transportThe executable and server path come from trusted configuration
Client to MCP serverThe named tool exists and the protocol request succeeds
Server function to public tableThe title matches an approved entry, or the result says it is absent
Tool result to callerThe content matches the text result this client expects

For a different MCP tool, do not blindly reuse result.content[0].text. The agreed output may be structured, contain several blocks or report an error. Inspect its schema and actual result before deciding what to return.

An MCP tool definition and a LangChain tool definition describe interfaces at different points. They do not automatically supply identical validation rules. Our explicit argument model establishes the extra-field policy at this LangChain entry point, even if another client or server default handles extra fields differently.

Test rejection as deliberately as success​

Save this as test_connected_book_tool.py beside the client and server:

import asyncio
import sys
import pytest
from fastmcp import Client
from fastmcp.client.transports import StdioTransport
from fastmcp.exceptions import ToolError
from pydantic import ValidationError
from connected_book_tool import SERVER, book_chapter

def test_reads_the_known_chapter():
answer = asyncio.run(book_chapter.ainvoke(
{"title": "Python and Roots"}
))
assert answer == "Python and Roots: 7 lessons"

def test_unknown_chapter_is_explicit():
answer = asyncio.run(book_chapter.ainvoke(
{"title": "Unknown chapter"}
))
assert "Not found" in answer

def test_rejects_an_unexpected_path():
with pytest.raises(ValidationError):
asyncio.run(book_chapter.ainvoke({
"title": "Python and Roots",
"file_path": "private.txt",
}))

def test_closes_the_client_after_a_failed_call():
async def check_failure():
transport = StdioTransport(
command=sys.executable,
args=[str(SERVER)],
)
client = Client(transport, timeout=5, init_timeout=10)
with pytest.raises(ToolError):
async with client:
await client.call_tool("missing_tool", {})
assert not client.is_connected()

asyncio.run(check_failure())

Run uv run python -m pytest -q test_connected_book_tool.py. The first two tests exercise the real local server connection. The third checks the LangChain input boundary; the supplied path should never become a server path or a file-reading instruction. The fourth deliberately calls a missing tool through MCP, expects ToolError, and checks that leaving the context closes the client's connection even after that failure. This checks local connection cleanup; it says nothing about reversing an external action. Add a wrong-type test with {"title": 7} as another independent rejection check.

The main-name guard in the client module matters here. Importing the tool into a test must not run the demonstration's main function automatically.

Passing these tests establishes specific behaviour for this local tool. It does not establish that a language model will always choose the right tool, that private data is protected or that an externally hosted server is production-ready. Those are additional requirements with additional evidence.

Safety floor

Keep commands, server locations and permission rules outside untrusted tool arguments. Treat returned text as data, not permission to follow new instructions. Before adding a model, protected data or write operations, enforce access checks, bounded calls and the required human approval for consequential actions.

The LangChain tools guide, FastMCP transport guide and Pydantic model guide support the connection shown here.

Review the chapter without the examples open​

Score each answer out of two: one point for the outcome and one for its reason. Aim for at least eight out of ten and revisit every missed mechanism. These are the book's own checks of what you have just learned.

  1. Why can a dataclass field labelled int still contain the wrong kind of value, and which mechanism enforces our tool's input rules?
  2. A wrapper calls the right function but forgets return. What can the caller receive?
  3. A generator is converted to a list for logging and then reused for the answer. Why can the answer be empty?
  4. An asynchronous tool call is created but never awaited. What is missing from the path to a completed result?
  5. Why does a successful call through MCP and LangChain fail to prove that a model-driven agent is safe?
Compare after your attempt
  1. Ordinary annotations document an expectation; the explicit Pydantic argument model validates at the tool boundary.
  2. It can receive None despite useful work happening inside the wrapper.
  3. The same one-shot generator may already be exhausted.
  4. The coroutine must be awaited or scheduled and its completion and failure observed.
  5. Model decisions, authorisation, data handling, effects and operational limits add independent responsibilities beyond the local tool call.

For a real solution, write a requirement with an approved input, an exact expected output and a refused action. Have the AI implement or locate the relevant behaviour, then verify each boundary yourself. A public book assistant and a private assistant have different access needs; an implementation in one does not automatically prove the other.

You can return to the Course 1 overview with a complete route in mind: Python values, checked inputs, a registered tool, a real connection and an inspected result. Later course work will add further capabilities to that route while keeping those responsibilities visible.