π The fast, Pythonic way to build MCP servers and clients.
client: deprecate inferring stdio transports from str, prefer Path (#4941)
nate nowack3685866cd8a9
diff --git a/docs/clients/client-groups.mdx b/docs/clients/client-groups.mdxindex 988735ce0..0ffa6a321 100644--- a/docs/clients/client-groups.mdx+++ b/docs/clients/client-groups.mdx@@ -17,12 +17,13 @@ This differs from passing a multi-server configuration directly to `Client`. `ClConstruct the clients explicitly when each server needs its own handlers, authentication, or connection settings:```python+from pathlib import Pathimport asynciofrom fastmcp import Clientfrom fastmcp.client.group import ClientGroup-legacy_client = Client("legacy_server.py", mode="legacy")+legacy_client = Client(Path("legacy_server.py"), mode="legacy")modern_client = Client("https://modern.example.com/mcp", mode="auto")group = ClientGroup(diff --git a/docs/clients/client-only-package.mdx b/docs/clients/client-only-package.mdxindex 020b2f077..8406dbc1c 100644--- a/docs/clients/client-only-package.mdx+++ b/docs/clients/client-only-package.mdx@@ -29,13 +29,14 @@ Use `fastmcp-slim[client]` when your code connects to MCP servers but does not dClient-only installs support remote and subprocess transports:```python+from pathlib import Pathfrom fastmcp import Client# Remote MCP serverhttp_client = Client("https://example.com/mcp")# Local MCP server over stdio-stdio_client = Client("my_server.py")+stdio_client = Client(Path("my_server.py"))```Single-server MCP configuration works as well:diff --git a/docs/clients/client.mdx b/docs/clients/client.mdxindex a1b831d7e..21b4d9032 100644--- a/docs/clients/client.mdx+++ b/docs/clients/client.mdx@@ -22,6 +22,7 @@ This is a programmatic client that requires explicit function calls and providesYou provide a server source and the client automatically infers the appropriate transport mechanism.```python+from pathlib import Pathimport asynciofrom fastmcp import Client, FastMCP@@ -33,7 +34,7 @@ client = Client(server)client = Client("https://example.com/mcp")# Local Python script-client = Client("my_mcp_server.py")+client = Client(Path("my_mcp_server.py"))async def main():async with client:@@ -67,11 +68,12 @@ client = Client(server) # In-memory, no network or subprocess**STDIO transport** launches a server as a subprocess and communicates through stdin/stdout pipes. This is the standard mechanism used by desktop clients like Claude Desktop. By default, the subprocess receives the MCP SDK's default environment; pass an explicit transport when you need to add environment variables, set a working directory, or control process reuse.```python+from pathlib import Pathfrom fastmcp import Clientfrom fastmcp.client.transports import PythonStdioTransport# Simple inference from file path-client = Client("my_server.py")+client = Client(Path("my_server.py"))# With explicit environment configurationtransport = PythonStdioTransport(@@ -151,9 +153,10 @@ async with Client(mcp) as client:For advanced scenarios where you need precise control over when initialization happens, disable automatic initialization and call `initialize()` manually. `initialize()` is a handshake-era operation, so pin the connection with `mode="legacy"`: the modern protocol has no `initialize` round trip, and calling it on a modern connection raises.```python+from pathlib import Pathfrom fastmcp import Client-client = Client("my_mcp_server.py", auto_initialize=False, mode="legacy")+client = Client(Path("my_mcp_server.py"), auto_initialize=False, mode="legacy")async with client:# Connection established, but not initialized yetdiff --git a/docs/clients/logging.mdx b/docs/clients/logging.mdxindex 407b1ebd5..f70461511 100644--- a/docs/clients/logging.mdx+++ b/docs/clients/logging.mdx@@ -105,7 +105,8 @@ This structure is preserved even when logs are forwarded through a FastMCP proxyIf you do not provide a custom `log_handler`, FastMCP's default handler routes server logs to Python's logging system at the appropriate severity level. The MCP levels map as follows: `notice` becomes INFO; `alert` and `emergency` become CRITICAL.```python-client = Client("my_mcp_server.py")+from pathlib import Path+client = Client(Path("my_mcp_server.py"))async with client:# Server logs are forwarded at proper severity automaticallydiff --git a/docs/clients/notifications.mdx b/docs/clients/notifications.mdxindex b771c903e..a2b36d36b 100644--- a/docs/clients/notifications.mdx+++ b/docs/clients/notifications.mdx@@ -139,6 +139,7 @@ class MyMessageHandler(MessageHandler):A practical example of maintaining a tool cache that refreshes when tools change:```python+from pathlib import Pathfrom fastmcp import Clientfrom fastmcp.client.messages import MessageHandlerimport mcp.types@@ -154,7 +155,7 @@ class ToolCacheHandler(MessageHandler):print("Tools changed - clearing cache")self.cached_tools = [] # Force refresh on next access-client = Client("server.py", message_handler=ToolCacheHandler())+client = Client(Path("server.py"), message_handler=ToolCacheHandler())```## Server Requestsdiff --git a/docs/clients/sampling.mdx b/docs/clients/sampling.mdxindex f2dfe82e3..489509d15 100644--- a/docs/clients/sampling.mdx+++ b/docs/clients/sampling.mdx@@ -18,6 +18,7 @@ The handler receives the conversation the server wants completed, the parameters## Handler Template```python+from pathlib import Pathfrom fastmcp import Clientfrom fastmcp.client.sampling import SamplingMessage, SamplingParams, RequestContextfrom mcp.types import TextContent@@ -40,7 +41,7 @@ async def sampling_handler(return "Generated response based on the messages"-client = Client("my_mcp_server.py", sampling_handler=sampling_handler)+client = Client(Path("my_mcp_server.py"), sampling_handler=sampling_handler)```The client answers with this handler however the server asks for a completion. The default `mode="auto"` negotiates whichever protocol era the server speaks, and one handler covers both of the routes an era can use β see [Request Routes](#request-routes).diff --git a/docs/clients/transports.mdx b/docs/clients/transports.mdxindex d165eb953..586969a7a 100644--- a/docs/clients/transports.mdx+++ b/docs/clients/transports.mdx@@ -37,9 +37,10 @@ client = Client(transport)For convenience, the client can infer STDIO transport from file paths, though this limits configuration options:```python+from pathlib import Pathfrom fastmcp import Client-client = Client("my_server.py") # Limited - no configuration options+client = Client(Path("my_server.py")) # Limited - no configuration options```<Warning>diff --git a/docs/development/tests.mdx b/docs/development/tests.mdxindex 37760e7aa..d29974614 100644--- a/docs/development/tests.mdx+++ b/docs/development/tests.mdx@@ -40,6 +40,7 @@ Our test organization mirrors the source package structure, creating a predictabWe use pytest markers to categorize tests that require special resources or take longer to run:```python+from pathlib import Path@pytest.mark.integrationasync def test_github_api_integration():"""Test GitHub API integration with real service."""@@ -56,7 +57,7 @@ async def test_github_api_integration():async def test_stdio_transport():"""Test STDIO transport with separate process."""# This spawns a subprocess- async with Client("python examples/simple_echo.py") as client:+ async with Client(Path("examples/simple_echo.py")) as client:result = await client.call_tool("echo", {"message": "test"})assert result.content[0].text == "test"```diff --git a/docs/getting-started/upgrading/from-fastmcp-3.mdx b/docs/getting-started/upgrading/from-fastmcp-3.mdxindex a5f8a42fd..ee5bf119d 100644--- a/docs/getting-started/upgrading/from-fastmcp-3.mdx+++ b/docs/getting-started/upgrading/from-fastmcp-3.mdx@@ -109,11 +109,12 @@ The SDK v2 raises FastMCP's dependency floors, which matters before any of yourObjects that FastMCP hands back to you β the results of `client.list_tools()`, `client.call_tool_mcp()`, `client.read_resource()`, and the parameter objects passed to your sampling and elicitation handlers β are SDK v2 objects with snake_case fields. FastMCP installs a compatibility bridge at import time that routes the old camelCase names to their new snake_case fields, so code written against FastMCP 2.x still reads correctly:```python+from pathlib import Pathfrom fastmcp import Clientasync def read_schema():- async with Client("my_mcp_server.py") as client:+ async with Client(Path("my_mcp_server.py")) as client:tools = await client.list_tools()return tools[0].inputSchema # still works, warns once```@@ -381,6 +382,15 @@ ToolError: elicitation via server-initiated requests is unavailable on 2026-07-2The gate is strict in both directions, which is what makes it debuggable: a guard tool that returns an input request on a handshake connection raises the mirror-image error rather than misbehaving quietly. You have three ways forward. Rewrite the tool as a guard tool that *returns* a description of the input it needs, which is the form that works on modern connections. Branch on `ctx.request_context.protocol_version` and keep both paths if you serve both eras. Or keep this server's clients on the handshake era with `Client(server, mode="legacy")`, which leaves `ctx.elicit()` working as written. See [Elicitation](/servers/elicitation#which-approach-to-use) for the two shapes side by side.+**`Client("server.py")` warns.** Inferring a stdio transport from a string is deprecated and will be removed in FastMCP 5, when a string will only ever mean a URL. Today a string that names an existing `.py` or `.js` file still starts that script, but emits a `FastMCPDeprecationWarning`. Pass a `pathlib.Path` to say explicitly that the value is a script, or build a `StdioTransport`:++```python test="skip"+from pathlib import Path+from fastmcp import Client++client = Client(Path("server.py"))+```+**Middleware sees traffic it never saw before.** Dispatch now begins in the SDK's middleware layer, the single point every inbound message passes through, so `on_message`, `on_request`, and `on_notification` observe *every* message a client sends β including `notifications/cancelled`, `notifications/initialized`, and `notifications/progress`, and including requests that fail before reaching a handler, such as an unknown method or a `tools/call` whose params fail validation. In 3.x those never reached your hooks. Middleware that assumed every message it saw was a routable request, or that counted messages to measure tool traffic, needs a guard on the message type. The operation hooks (`on_call_tool`, `on_list_tools`, and the rest) are unaffected: they still fire exactly once per request and still receive typed component results. See [What middleware sees](/servers/middleware#what-middleware-sees).**Templated resources are path-screened by default.** Every templated resource now has its extracted parameter values checked for path-traversal (`..` segments), absolute paths, and null bytes *before your handler runs*, at the server's read chokepoint. A rejected read returns a non-leaky "resource not found" error. Only a standalone `..` segment counts as traversal, so values that merely contain dots (`file.tar.gz`, `HEAD~3..HEAD`) and dotfiles (`.env`) still pass. If a template legitimately accepts `..`-bearing or absolute values, exempt the parameter with `ResourceSecurity(exempt_params={...})`, disable the check per-component with `security=None`, or set a server-wide default with `FastMCP(resource_security=...)`. See [Resources β Path Security](/servers/resources#path-security).diff --git a/docs/integrations/gemini.mdx b/docs/integrations/gemini.mdxindex 1b17ab6ee..a7d6dc24e 100644--- a/docs/integrations/gemini.mdx+++ b/docs/integrations/gemini.mdx@@ -58,11 +58,12 @@ export GEMINI_API_KEY="your-api-key"Gemini's SDK interacts directly with the MCP client session. To call the server, you'll need to instantiate a FastMCP client, enter its connection context, and pass the client session to the Gemini SDK.```python {5, 9, 15}+from pathlib import Pathfrom fastmcp import Clientfrom google import genaiimport asyncio-mcp_client = Client("server.py")+mcp_client = Client(Path("server.py"))gemini_client = genai.Client()async def main():diff --git a/docs/integrations/pydantic-ai.mdx b/docs/integrations/pydantic-ai.mdxindex 0c8ffa524..62bebec66 100644--- a/docs/integrations/pydantic-ai.mdx+++ b/docs/integrations/pydantic-ai.mdx@@ -87,10 +87,11 @@ For [SSE](/clients/transports#sse-transport), use a `/sse` URL instead.To launch a FastMCP server as a subprocess, pass a script path and the toolset will use the [STDIO transport](/clients/transports#stdio-transport).```python+from pathlib import Pathfrom pydantic_ai import Agentfrom pydantic_ai.toolsets.fastmcp import FastMCPToolset-toolset = FastMCPToolset("server.py")+toolset = FastMCPToolset(Path("server.py"))agent = Agent("openai:gpt-4.1", toolsets=[toolset])```diff --git a/docs/servers/composition.mdx b/docs/servers/composition.mdxindex 9175c2438..618b21601 100644--- a/docs/servers/composition.mdx+++ b/docs/servers/composition.mdx@@ -39,6 +39,7 @@ main.mount(weather)Mount remote HTTP servers or subprocess-based MCP servers using `create_proxy()`:```python+from pathlib import Pathfrom fastmcp import FastMCPfrom fastmcp.server import create_proxy@@ -48,7 +49,7 @@ mcp = FastMCP("Orchestrator")mcp.mount(create_proxy("http://api.example.com/mcp"), namespace="api")# Mount local Python scripts (file paths work directly)-mcp.mount(create_proxy("./my_server.py"), namespace="local")+mcp.mount(create_proxy(Path("./my_server.py")), namespace="local")```### Mounting npm/uvx Packagesdiff --git a/docs/servers/providers/proxy.mdx b/docs/servers/providers/proxy.mdxindex 1ff116bbd..ed3b2cb78 100644--- a/docs/servers/providers/proxy.mdx+++ b/docs/servers/providers/proxy.mdx@@ -82,10 +82,11 @@ if __name__ == "__main__":Or expose a local server via HTTP:```python+from pathlib import Pathfrom fastmcp.server import create_proxy# Bridge local server to HTTP-local_proxy = create_proxy("local_server.py", name="stdio-to-HTTP")+local_proxy = create_proxy(Path("local_server.py"), name="stdio-to-HTTP")if __name__ == "__main__":local_proxy.run(transport="http", host="0.0.0.0", port=8080)@@ -98,10 +99,11 @@ if __name__ == "__main__":`create_proxy()` provides session isolation - each request gets its own isolated backend session:```python+from pathlib import Pathfrom fastmcp.server import create_proxy# Each request creates a fresh backend session (recommended)-proxy = create_proxy("backend_server.py")+proxy = create_proxy(Path("backend_server.py"))# Multiple clients can use this proxy simultaneously:# - Client A calls a tool β gets isolated session@@ -114,10 +116,11 @@ proxy = create_proxy("backend_server.py")If you pass an already-connected client, the proxy reuses that session:```python+from pathlib import Pathfrom fastmcp import Clientfrom fastmcp.server import create_proxy-async with Client("backend_server.py") as connected_client:+async with Client(Path("backend_server.py")) as connected_client:# This proxy reuses the connected sessionproxy = create_proxy(connected_client)@@ -143,10 +146,11 @@ Proxies automatically forward MCP protocol features:| Progress | Progress notifications |```python+from pathlib import Pathfrom fastmcp.server import create_proxy# All features forwarded automatically-proxy = create_proxy("advanced_backend.py")+proxy = create_proxy(Path("advanced_backend.py"))# When the backend:# - Requests LLM sampling β forwarded to your client@@ -177,10 +181,11 @@ A proxy passes a backend's tool results through untouched, including results thaThis matters when a backend's declared schema is subtly wrong β an enum missing a variant it actually returns, say. A proxy that enforced the schema would replace the backend's working response with an error of its own, and the client would never see what the backend actually said.```python+from pathlib import Pathfrom fastmcp import Clientfrom fastmcp.server import create_proxy-proxy = create_proxy("backend_server.py")+proxy = create_proxy(Path("backend_server.py"))async with Client(proxy) as client:# The backend's response arrives as the backend sent it. If it violates@@ -199,11 +204,12 @@ A proxy is a server on its front and a client on its back, and the two MCP protoBy default the proxy relays the era: whatever era your client negotiates on the front, the proxy negotiates the same era on its backend connection, per request. A handshake client reaches a handshake backend, so server-initiated forwarding works; a modern client reaches a modern backend, so a guard tool's input request round-trips. Different clients hitting the same proxy each get a backend session in their own era β the eras never cross.```python+from pathlib import Pathfrom fastmcp import Clientfrom fastmcp.server import create_proxy# No mode: the backend mirrors each client's negotiated era.-proxy = create_proxy("backend_server.py")+proxy = create_proxy(Path("backend_server.py"))# A handshake client gets a handshake backend (push-forwarding works).async with Client(proxy, mode="legacy") as client:@@ -217,8 +223,9 @@ async with Client(proxy, mode="auto") as client:Passing an explicit `mode` pins the backend to one era regardless of the client:```python+from pathlib import Path# Always negotiate the modern era upstream, whatever the client speaks.-proxy = create_proxy("backend_server.py", mode="auto")+proxy = create_proxy(Path("backend_server.py"), mode="auto")```Pinning breaks the end-to-end era agreement, so reserve it for a backend that only speaks one era. When the client's era and the pinned backend era disagree on a feature β a modern client asking for a guard round-trip against a handshake-pinned backend, say β the mismatch surfaces through the normal era gates rather than silently degrading. Mirroring applies to proxies created from a target the proxy connects itself (a URL, path, config, or `FastMCP` instance); when you hand `create_proxy` an already-configured `Client`, that client carries its own mode and mirroring does not override it.@@ -309,10 +316,11 @@ Components from a proxy server are "mirrored" - they reflect the remote server'sTo modify a proxied component (like disabling it), create a local copy:```python+from pathlib import Pathfrom fastmcp import FastMCPfrom fastmcp.server import create_proxy-proxy = create_proxy("backend_server.py")+proxy = create_proxy(Path("backend_server.py"))# Get mirrored toolmirrored_tool = await proxy.get_tool("useful_tool")@@ -413,11 +421,12 @@ By default the gateway keeps its own `serverInfo`; pass `identity="upstream"` toFor explicit session control, use `FastMCPProxy` directly:```python+from pathlib import Pathfrom fastmcp.server.providers.proxy import FastMCPProxy, ProxyClient# Custom session factorydef create_client():- return ProxyClient("backend_server.py")+ return ProxyClient(Path("backend_server.py"))proxy = FastMCPProxy(client_factory=create_client)```diff --git a/examples/code_mode/client.py b/examples/code_mode/client.pyindex 3757becf6..ccc5ab6db 100644--- a/examples/code_mode/client.py+++ b/examples/code_mode/client.py@@ -11,6 +11,7 @@ Run with:import asyncioimport json+from pathlib import Pathfrom typing import Anyfrom rich.console import Console@@ -68,7 +69,7 @@ def _tool_table(async def main():- async with Client("examples/code_mode/server.py") as client:+ async with Client(Path("examples/code_mode/server.py")) as client:console.print()console.rule("[bold]CodeMode[/bold]")console.print()diff --git a/examples/prompts_as_tools/client.py b/examples/prompts_as_tools/client.pyindex 43f9bb477..73c4a091b 100644--- a/examples/prompts_as_tools/client.py+++ b/examples/prompts_as_tools/client.py@@ -9,13 +9,14 @@ Run with:import asyncioimport json+from pathlib import Pathfrom fastmcp.client import Clientasync def main():# Connect to the server- async with Client("examples/prompts_as_tools/server.py") as client:+ async with Client(Path("examples/prompts_as_tools/server.py")) as client:# List all available toolsprint("=== Available Tools ===")tools = await client.list_tools()diff --git a/examples/resources_as_tools/client.py b/examples/resources_as_tools/client.pyindex 8a23b12a6..d765309da 100644--- a/examples/resources_as_tools/client.py+++ b/examples/resources_as_tools/client.py@@ -9,13 +9,14 @@ Run with:import asyncioimport json+from pathlib import Pathfrom fastmcp.client import Clientasync def main():# Connect to the server- async with Client("examples/resources_as_tools/server.py") as client:+ async with Client(Path("examples/resources_as_tools/server.py")) as client:# List all available toolsprint("=== Available Tools ===")tools = await client.list_tools()diff --git a/examples/search/client_bm25.py b/examples/search/client_bm25.pyindex b33e395a3..4a6eada55 100644--- a/examples/search/client_bm25.py+++ b/examples/search/client_bm25.py@@ -9,6 +9,7 @@ Run with:import asyncioimport json+from pathlib import Pathfrom typing import Anyfrom rich.console import Console@@ -65,7 +66,7 @@ def _tool_table(async def main():- async with Client("examples/search/server_bm25.py") as client:+ async with Client(Path("examples/search/server_bm25.py")) as client:console.print()console.rule("[bold]BM25 Search Transform[/bold]")console.print()diff --git a/examples/search/client_regex.py b/examples/search/client_regex.pyindex ccccefbd2..e97413bc4 100644--- a/examples/search/client_regex.py+++ b/examples/search/client_regex.py@@ -9,6 +9,7 @@ Run with:import asyncioimport json+from pathlib import Pathfrom typing import Anyfrom rich.console import Console@@ -65,7 +66,7 @@ def _tool_table(async def main():- async with Client("examples/search/server_regex.py") as client:+ async with Client(Path("examples/search/server_regex.py")) as client:console.print()console.rule("[bold]Regex Search Transform[/bold]")console.print()diff --git a/fastmcp_slim/fastmcp/client/transports/inference.py b/fastmcp_slim/fastmcp/client/transports/inference.pyindex 84711d198..288737da8 100644--- a/fastmcp_slim/fastmcp/client/transports/inference.py+++ b/fastmcp_slim/fastmcp/client/transports/inference.py@@ -1,9 +1,12 @@+import sys+import warningsfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, cast, overloadfrom mcp.server.mcpserver import MCPServer as SDKServerfrom pydantic import AnyUrl+from fastmcp._warnings import FastMCPDeprecationWarningfrom fastmcp.client.transports.base import ClientTransport, ClientTransportTfrom fastmcp.client.transports.config import MCPConfigTransportfrom fastmcp.client.transports.http import StreamableHttpTransport@@ -24,6 +27,26 @@ else:logger = get_logger(__name__)+_PACKAGE_ROOT = str(Path(__file__).resolve().parents[2])+++def _external_stacklevel() -> int:+ """Stack level of the first caller outside the fastmcp package.++ Public entry points reach `infer_transport` through different wrapper depths+ (`Client(...)`, `create_proxy(...)`, a direct call), so a fixed stacklevel+ would point the deprecation warning at internal frames for some of them.+ """+ level = 1+ frame = sys._getframe(1)+ while frame is not None:+ if not frame.f_code.co_filename.startswith(_PACKAGE_ROOT):+ return level+ frame = frame.f_back+ level += 1+ return 1++@overloaddef infer_transport(transport: ClientTransportT) -> ClientTransportT: ...@@ -82,8 +105,10 @@ def infer_transport(The function supports these input types:- ClientTransport: Used directly without modification- FastMCP or SDKServer: Creates an in-memory FastMCPTransport- - Path or str (file path): Creates PythonStdioTransport (.py) or NodeStdioTransport (.js)- - AnyUrl or str (URL): Creates StreamableHttpTransport (default) or SSETransport (for /sse endpoints)+ - Path: Creates PythonStdioTransport (.py) or NodeStdioTransport (.js)+ - AnyUrl or str (URL): Creates StreamableHttpTransport (default) or SSETransport (for /sse endpoints).+ A str naming an existing .py or .js file still infers a stdio transport but+ emits a FastMCPDeprecationWarning; pass a Path instead.- MCPConfig or dict: Creates MCPConfigTransport, potentially connecting to multiple serversFor HTTP URLs, they are assumed to be Streamable HTTP URLs unless they end in `/sse`.@@ -97,7 +122,7 @@ def infer_transport(Examples:```python# Connect to a local Python script- transport = infer_transport("my_script.py")+ transport = infer_transport(Path("my_script.py"))# Connect to a remote server via HTTPtransport = infer_transport("http://example.com/mcp")@@ -124,14 +149,30 @@ def infer_transport()# the transport is a path to a script- elif isinstance(transport, Path | str) and Path(transport).exists():- if str(transport).endswith(".py"):- inferred_transport = PythonStdioTransport(script_path=cast(Path, transport))- elif str(transport).endswith(".js"):- inferred_transport = NodeStdioTransport(script_path=cast(Path, transport))+ elif isinstance(transport, Path):+ if transport.suffix == ".py":+ inferred_transport = PythonStdioTransport(script_path=transport)+ elif transport.suffix == ".js":+ inferred_transport = NodeStdioTransport(script_path=transport)else:raise ValueError(f"Unsupported script type: {transport}")+ # a string naming an existing script: still works, but warns. Strings will+ # mean URLs only in FastMCP 5; a Path is the explicit way to run a script.+ elif (+ isinstance(transport, str)+ and transport.endswith((".py", ".js"))+ and Path(transport).exists()+ ):+ warnings.warn(+ f"Inferring a stdio transport from the string {transport!r} is"+ " deprecated and will be removed in FastMCP 5. Pass"+ f" pathlib.Path({transport!r}) or an explicit StdioTransport instead.",+ FastMCPDeprecationWarning,+ stacklevel=_external_stacklevel(),+ )+ inferred_transport = infer_transport(Path(transport))+# the transport is an http(s) URLelif isinstance(transport, AnyUrl | str) and str(transport).startswith("http"):inferred_transport_type = infer_transport_type_from_url(diff --git a/tests/client/client/test_transport.py b/tests/client/client/test_transport.pyindex d0d80f79d..fe486f587 100644--- a/tests/client/client/test_transport.py+++ b/tests/client/client/test_transport.py@@ -1,15 +1,20 @@"""Client transport inference tests."""+import warnings+import pytestfrom fastmcp.client.transports import (FastMCPTransport,MCPConfigTransport,+ NodeStdioTransport,+ PythonStdioTransport,SSETransport,StdioTransport,StreamableHttpTransport,infer_transport,)+from fastmcp.exceptions import FastMCPDeprecationWarningclass TestInferTransport:@@ -135,3 +140,49 @@ class TestInferTransport:server = FastMCP1()transport = infer_transport(server)assert isinstance(transport, FastMCPTransport)+++class TestScriptPathInference:+ def test_path_to_python_script_infers_stdio(self, tmp_path):+ script = tmp_path / "server.py"+ script.write_text("")+ assert isinstance(infer_transport(script), PythonStdioTransport)++ def test_path_to_node_script_infers_stdio(self, tmp_path):+ script = tmp_path / "server.js"+ script.write_text("")+ assert isinstance(infer_transport(script), NodeStdioTransport)++ def test_string_script_path_still_works_but_warns(self, tmp_path):+ script = tmp_path / "server.py"+ script.write_text("")+ with pytest.warns(FastMCPDeprecationWarning, match="pathlib.Path") as record:+ transport = infer_transport(str(script))+ assert isinstance(transport, PythonStdioTransport)+ assert record[0].filename == __file__++ def test_warning_points_at_the_caller_for_every_entry_point(self, tmp_path):+ from fastmcp import Client+ from fastmcp.server import create_proxy++ script = tmp_path / "server.py"+ script.write_text("")+ for build in (Client, create_proxy):+ with pytest.warns(FastMCPDeprecationWarning) as record:+ build(str(script))+ assert record[0].filename == __file__, build++ def test_path_does_not_warn(self, tmp_path):+ script = tmp_path / "server.py"+ script.write_text("")+ with warnings.catch_warnings():+ warnings.simplefilter("error")+ infer_transport(script)++ def test_string_to_missing_script_is_not_a_transport(self, tmp_path):+ with pytest.raises(ValueError, match="Could not infer"):+ infer_transport(str(tmp_path / "missing.py"))++ def test_path_with_unsupported_suffix_is_rejected(self, tmp_path):+ with pytest.raises(ValueError, match="Unsupported script type"):+ infer_transport(tmp_path / "server.rb")diff --git a/tests/docs/test_upgrade_guide_examples.py b/tests/docs/test_upgrade_guide_examples.pyindex 142c662b4..72d070d5d 100644--- a/tests/docs/test_upgrade_guide_examples.py+++ b/tests/docs/test_upgrade_guide_examples.py@@ -35,7 +35,7 @@ UPGRADE_DIR = Path("docs/getting-started/upgrading")# Blocks deliberately not executable: SDK v1 API that is no longer installable,# and before/after fragments that are not standalone programs. Pinned so that# adding a skip is a visible decision rather than a silent one.-EXPECTED_SKIPS = 35+EXPECTED_SKIPS = 36def _examples() -> list[CodeExample]: