Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

ci: smoke-test FastMCP through pydantic-ai and langchain-mcp-adapters (#5207)

nate nowack9d7afdf8e639
diff --git a/.github/workflows/run-downstream-smoke.yml b/.github/workflows/run-downstream-smoke.yml
new file mode 100644
index 000000000..4fc01a049
--- /dev/null
+++ b/.github/workflows/run-downstream-smoke.yml
@@ -0,0 +1,68 @@
+name: Downstream smoke
+
+# Drive this checkout's FastMCP through the frameworks that depend on it, using
+# their latest releases, so a change that breaks them fails here first.
+
+env:
+ PY_COLORS: 1
+
+on:
+ push:
+ branches: ["main"]
+ paths:
+ - "fastmcp_slim/**"
+ - "tests/downstream/**"
+ - "pyproject.toml"
+ - "uv.lock"
+ - ".github/workflows/run-downstream-smoke.yml"
+
+ pull_request:
+ paths:
+ - "fastmcp_slim/**"
+ - "tests/downstream/**"
+ - "pyproject.toml"
+ - "uv.lock"
+ - ".github/workflows/run-downstream-smoke.yml"
+
+ schedule:
+ # Downstream releases can break us without any change here.
+ - cron: "30 2 * * *"
+
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ smoke:
+ name: ${{ matrix.name }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ # pydantic-ai builds on fastmcp.Client, so it shares FastMCP's environment.
+ - name: pydantic-ai
+ run: uv run --with 'pydantic-ai-slim[mcp]' tests/downstream/smoke_pydantic_ai.py
+ # langchain-mcp-adapters pins mcp<2, so it runs in its own environment and reaches FastMCP over the wire.
+ - name: langchain
+ run: uv run tests/downstream/smoke_langchain.py
+
+ steps:
+ - uses: actions/checkout@v7
+
+ - name: Setup uv
+ uses: ./.github/actions/setup-uv
+ with:
+ python-version: "3.12"
+
+ - name: Run ${{ matrix.name }} smoke
+ run: ${{ matrix.run }}
+ env:
+ PYDANTIC_AI_NO_BANNER: 1
+ FASTMCP_LOG_LEVEL: WARNING
diff --git a/pyproject.toml b/pyproject.toml
index 629032417..3661f18e3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -163,6 +163,7 @@ exclude = [
"examples/screenshot.py", # needs pyautogui, Pillow
"examples/memory.py", # needs asyncpg, numpy, pydantic_ai, pgvector
"examples/get_file.py", # needs aiohttp
+ "tests/downstream/smoke_*.py", # needs langchain / pydantic_ai, installed per-job in CI
]
[tool.ty.environment]
diff --git a/tests/downstream/_http.py b/tests/downstream/_http.py
new file mode 100644
index 000000000..70f420db5
--- /dev/null
+++ b/tests/downstream/_http.py
@@ -0,0 +1,40 @@
+"""Serve server.py over streamable HTTP in a subprocess for the length of a `with` block."""
+
+import os
+import socket
+import subprocess
+import sys
+import time
+from collections.abc import Iterator
+from contextlib import contextmanager
+from pathlib import Path
+
+SERVER = Path(__file__).with_name("server.py")
+
+
+def free_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+@contextmanager
+def http_server(python: list[str]) -> Iterator[str]:
+ port = free_port()
+ proc = subprocess.Popen([*python, str(SERVER), "http", str(port)], env=os.environ)
+ try:
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ if proc.poll() is not None:
+ sys.exit(f"server exited with {proc.returncode}")
+ try:
+ socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
+ break
+ except OSError:
+ time.sleep(0.1)
+ else:
+ sys.exit("server did not start listening within 30s")
+ yield f"http://127.0.0.1:{port}/mcp"
+ finally:
+ proc.terminate()
+ proc.wait(timeout=10)
diff --git a/tests/downstream/server.py b/tests/downstream/server.py
new file mode 100644
index 000000000..0cf931cf8
--- /dev/null
+++ b/tests/downstream/server.py
@@ -0,0 +1,117 @@
+"""The FastMCP server every downstream smoke script connects to.
+
+Run as `python server.py stdio` or `python server.py http <port>`.
+"""
+
+import sys
+from dataclasses import dataclass
+
+from mcp.types import (
+ ElicitRequest,
+ ElicitRequestFormParams,
+ ElicitResult,
+ InputRequiredResult,
+)
+from mcp_types.version import MODERN_PROTOCOL_VERSIONS
+from pydantic import BaseModel
+
+from fastmcp import Context, FastMCP
+from fastmcp.exceptions import ToolError
+
+mcp = FastMCP(
+ "downstream-smoke", instructions="Arithmetic and weather for smoke tests."
+)
+
+
+class Forecast(BaseModel):
+ city: str
+ celsius: float
+ conditions: list[str]
+
+
+def add(a: int, b: int) -> int:
+ """Add two integers."""
+ return a + b
+
+
+def forecast(city: str, days: int = 1) -> Forecast:
+ """Structured weather forecast for a city."""
+ return Forecast(city=city, celsius=21.5, conditions=["sunny"] * days)
+
+
+def divide(a: float, b: float) -> float:
+ """Divide a by b."""
+ if b == 0:
+ raise ToolError("cannot divide by zero")
+ return a / b
+
+
+async def count_to(n: int, ctx: Context) -> str:
+ """Count to n, reporting progress and logging along the way."""
+ for i in range(1, n + 1):
+ await ctx.report_progress(i, n)
+ await ctx.info(f"counted to {n}")
+ return f"counted to {n}"
+
+
+@dataclass
+class Approval:
+ approved: bool
+
+
+async def confirm(action: str, ctx: Context) -> str | InputRequiredResult:
+ """Ask the client to approve an action, using whichever elicitation path the connection's protocol era supports."""
+ rc = ctx.request_context
+ if rc is not None and rc.protocol_version in MODERN_PROTOCOL_VERSIONS:
+ if ctx.input_responses is None:
+ form = ElicitRequestFormParams(
+ message=f"approve {action}?",
+ requested_schema={
+ "type": "object",
+ "properties": {"approved": {"type": "boolean"}},
+ "required": ["approved"],
+ },
+ )
+ return InputRequiredResult(
+ result_type="input_required",
+ input_requests={
+ "approval": ElicitRequest(method="elicitation/create", params=form)
+ },
+ )
+ answer = ctx.input_responses["approval"]
+ assert isinstance(answer, ElicitResult), answer
+ if answer.action == "accept" and answer.content and answer.content["approved"]:
+ return f"{action}: approved"
+ return f"{action}: {answer.action}"
+ result = await ctx.elicit(f"approve {action}?", response_type=Approval)
+ if result.action == "accept" and result.data.approved:
+ return f"{action}: approved"
+ return f"{action}: {result.action}"
+
+
[email protected]("config://app", mime_type="application/json")
+def app_config() -> str:
+ return '{"mode": "smoke"}'
+
+
[email protected]("greeting://{name}")
+def greeting(name: str) -> str:
+ return f"hello, {name}"
+
+
+def review(code: str) -> str:
+ """Ask for a code review."""
+ return f"please review:\n{code}"
+
+
+if __name__ == "__main__":
+ if sys.argv[1:2] == ["http"]:
+ mcp.run("http", host="127.0.0.1", port=int(sys.argv[2]), show_banner=False)
+ else:
+ mcp.run("stdio", show_banner=False)
diff --git a/tests/downstream/smoke_langchain.py b/tests/downstream/smoke_langchain.py
new file mode 100644
index 000000000..d070bac36
--- /dev/null
+++ b/tests/downstream/smoke_langchain.py
@@ -0,0 +1,148 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = ["langchain-mcp-adapters", "langchain"]
+# ///
+"""Exercise a FastMCP server through langchain-mcp-adapters.
+
+The adapters pin `mcp<2` while FastMCP 4 needs `mcp>=2`, so they cannot share an
+environment. This script runs in its own environment and reaches the server
+over the wire, the way LangChain users do:
+
+ uv run tests/downstream/smoke_langchain.py
+"""
+
+import asyncio
+from typing import Any
+
+from _http import SERVER, http_server
+from langchain.agents import create_agent
+from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
+from langchain_core.messages import AIMessage
+from langchain_mcp_adapters.callbacks import Callbacks
+from langchain_mcp_adapters.client import MultiServerMCPClient
+from langchain_mcp_adapters.tools import load_mcp_tools
+from mcp.types import ElicitResult
+
+REPO = SERVER.parents[2]
+FASTMCP_PYTHON = ["uv", "run", "--project", str(REPO), "--frozen", "python"]
+
+
+class ScriptedToolModel(GenericFakeChatModel):
+ def bind_tools(self, tools: Any, **kwargs: Any) -> "ScriptedToolModel":
+ return self
+
+
+def scripted_model() -> ScriptedToolModel:
+ return ScriptedToolModel(
+ messages=iter(
+ [
+ AIMessage(
+ content="",
+ tool_calls=[
+ {"name": "add", "args": {"a": 2, "b": 3}, "id": "call-add"},
+ {
+ "name": "forecast",
+ "args": {"city": "Chicago", "days": 2},
+ "id": "call-forecast",
+ },
+ ],
+ ),
+ AIMessage(content="done"),
+ ]
+ )
+ )
+
+
+async def exercise(label: str, connection: dict[str, Any]) -> None:
+ progress: list[float] = []
+ logs: list[str] = []
+
+ async def on_progress(
+ value: float, total: float | None, message: str | None, context: Any
+ ) -> None:
+ progress.append(value)
+
+ async def on_log(params: Any, context: Any) -> None:
+ logs.append(str(params.data))
+
+ async def on_elicitation(
+ mcp_context: Any, params: Any, context: Any
+ ) -> ElicitResult:
+ return ElicitResult(action="accept", content={"approved": True})
+
+ client = MultiServerMCPClient(
+ {"smoke": connection},
+ callbacks=Callbacks(
+ on_progress=on_progress,
+ on_logging_message=on_log,
+ on_elicitation=on_elicitation,
+ ),
+ )
+
+ tools = {tool.name: tool for tool in await client.get_tools()}
+ assert {"add", "forecast", "divide", "count_to", "confirm"} <= set(tools), tools
+
+ agent = create_agent(scripted_model(), list(tools.values()))
+ state = await agent.ainvoke(
+ {"messages": [("user", "add 2 and 3, then get the Chicago forecast")]}
+ )
+ returned = {m.name: m.content for m in state["messages"] if m.type == "tool"}
+ assert "5" in str(returned["add"]), returned
+ assert "sunny" in str(returned["forecast"]), returned
+
+ assert "42" in str(await tools["add"].ainvoke({"a": 40, "b": 2}))
+ failed = await tools["divide"].ainvoke(
+ {
+ "type": "tool_call",
+ "name": "divide",
+ "args": {"a": 1, "b": 0},
+ "id": "call-divide",
+ }
+ )
+ assert failed.status == "error" and "divide by zero" in str(failed.content), failed
+
+ assert "deploy: approved" in str(
+ await tools["confirm"].ainvoke({"action": "deploy"})
+ )
+ assert "counted to 3" in str(await tools["count_to"].ainvoke({"n": 3}))
+ assert progress == [1, 2, 3], progress
+ assert any("counted to 3" in line for line in logs), logs
+
+ async with client.session("smoke") as session:
+ assert {"add", "forecast"} <= {
+ tool.name for tool in await load_mcp_tools(session)
+ }
+
+ blobs = await client.get_resources(
+ "smoke", uris=["config://app", "greeting://nate"]
+ )
+ assert [blob.as_string() for blob in blobs] == [
+ '{"mode": "smoke"}',
+ "hello, nate",
+ ], blobs
+
+ messages = await client.get_prompt("smoke", "review", arguments={"code": "x = 1"})
+ assert "x = 1" in str(messages[0].content), messages
+ print(f"ok langchain via {label}")
+
+
+async def main() -> None:
+ from importlib.metadata import version
+
+ print(
+ f"langchain-mcp-adapters {version('langchain-mcp-adapters')}, mcp {version('mcp')}"
+ )
+ await exercise(
+ "stdio",
+ {
+ "transport": "stdio",
+ "command": FASTMCP_PYTHON[0],
+ "args": [*FASTMCP_PYTHON[1:], str(SERVER), "stdio"],
+ },
+ )
+ with http_server(FASTMCP_PYTHON) as url:
+ await exercise("streamable HTTP", {"transport": "streamable_http", "url": url})
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/tests/downstream/smoke_pydantic_ai.py b/tests/downstream/smoke_pydantic_ai.py
new file mode 100644
index 000000000..a8f7494b5
--- /dev/null
+++ b/tests/downstream/smoke_pydantic_ai.py
@@ -0,0 +1,120 @@
+"""Exercise FastMCP through pydantic-ai's MCPToolset, which is built on fastmcp.Client.
+
+Runs inside the FastMCP project environment with pydantic-ai layered on top:
+
+ uv run --with 'pydantic-ai-slim[mcp]' tests/downstream/smoke_pydantic_ai.py
+"""
+
+import asyncio
+import sys
+from typing import Any
+
+from _http import SERVER, http_server
+from pydantic_ai import Agent, ModelRetry
+from pydantic_ai.mcp import MCPToolset
+from pydantic_ai.messages import (
+ ModelMessage,
+ ModelResponse,
+ TextPart,
+ ToolCallPart,
+ ToolReturnPart,
+)
+from pydantic_ai.models.function import AgentInfo, FunctionModel
+from server import mcp
+
+import fastmcp
+
+
+def scripted_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
+ """Call add and forecast on the first turn, then answer with what they returned."""
+ returns = [
+ p
+ for m in messages
+ for p in getattr(m, "parts", [])
+ if isinstance(p, ToolReturnPart)
+ ]
+ if not returns:
+ return ModelResponse(
+ parts=[
+ ToolCallPart("add", {"a": 2, "b": 3}),
+ ToolCallPart("forecast", {"city": "Chicago", "days": 2}),
+ ]
+ )
+ return ModelResponse(parts=[TextPart(" | ".join(str(p.content) for p in returns))])
+
+
+async def accept(
+ message: str, response_type: Any, params: Any, context: Any
+) -> dict[str, bool]:
+ return {"approved": True}
+
+
+async def exercise(label: str, target: Any) -> None:
+ progress: list[float] = []
+ logs: list[str] = []
+
+ async def on_progress(
+ value: float, total: float | None, message: str | None
+ ) -> None:
+ progress.append(value)
+
+ async def on_log(message: Any) -> None:
+ logs.append(str(message.data))
+
+ toolset = MCPToolset(
+ target,
+ elicitation_handler=accept,
+ progress_handler=on_progress,
+ log_handler=on_log,
+ )
+ async with toolset:
+ names = {tool.name for tool in await toolset.list_tools()}
+ assert {"add", "forecast", "divide", "count_to", "confirm"} <= names, names
+
+ agent = Agent(FunctionModel(scripted_model), toolsets=[toolset])
+ result = await agent.run("add 2 and 3, then get the Chicago forecast")
+ assert "5" in result.output and "sunny" in result.output, result.output
+
+ assert await toolset.direct_call_tool("add", {"a": 40, "b": 2}) == 42
+ forecast = await toolset.direct_call_tool("forecast", {"city": "Oslo"})
+ assert forecast == {"city": "Oslo", "celsius": 21.5, "conditions": ["sunny"]}, (
+ forecast
+ )
+
+ try:
+ await toolset.direct_call_tool("divide", {"a": 1, "b": 0})
+ except ModelRetry as error:
+ assert "divide by zero" in str(error), error
+ else:
+ raise AssertionError("divide by zero did not raise")
+
+ assert (
+ await toolset.direct_call_tool("confirm", {"action": "deploy"})
+ == "deploy: approved"
+ )
+
+ assert await toolset.direct_call_tool("count_to", {"n": 3}) == "counted to 3"
+ assert progress == [1, 2, 3], progress
+ assert any("counted to 3" in line for line in logs), logs
+
+ assert "config://app" in {str(r.uri) for r in await toolset.list_resources()}
+ assert await toolset.read_resource("config://app") == '{"mode": "smoke"}'
+ assert await toolset.read_resource("greeting://nate") == "hello, nate"
+
+ prompt = await toolset.get_prompt("review", {"code": "x = 1"})
+ assert "x = 1" in str(prompt.messages[0].content), prompt
+ print(f"ok pydantic-ai via {label}")
+
+
+async def main() -> None:
+ import pydantic_ai
+
+ print(f"fastmcp {fastmcp.__version__}, pydantic-ai {pydantic_ai.__version__}")
+ await exercise("in-process FastMCP server", mcp)
+ await exercise("stdio", str(SERVER))
+ with http_server([sys.executable]) as url:
+ await exercise("streamable HTTP", url)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())