Skip to content

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

Cache component lists in ProxyProvider (#3479)

Jeremiah Lowina52036ed0f25
diff --git a/docs/servers/providers/proxy.mdx b/docs/servers/providers/proxy.mdx
index a2def6892..c870c97f8 100644
--- a/docs/servers/providers/proxy.mdx
+++ b/docs/servers/providers/proxy.mdx
@@ -258,7 +258,50 @@ Proxying introduces network latency:
When mounting proxy servers, this latency affects all operations on the parent server.
-For low-latency requirements, consider caching strategies or limiting mounting depth.
+### Component List Caching
+
+<VersionBadge version="3.2.0" />
+
+`ProxyProvider` caches the backend's component lists (tools, resources, templates, prompts) so that individual lookups β€” like resolving a tool by name during `call_tool` β€” don't require a separate backend connection. The cache stores raw component metadata and is shared across all proxy sessions; per-session visibility, auth, and transforms are still applied after cache lookup by the server layer. The cache refreshes whenever an explicit `list_*` call is made, and entries expire after a configurable TTL (default 300 seconds).
+
+For backends whose component lists change dynamically, disable caching by setting `cache_ttl=0`.
+
+```python
+from fastmcp.server.providers.proxy import ProxyProvider, ProxyClient
+
+# Default 300s TTL
+provider = ProxyProvider(lambda: ProxyClient("http://backend/mcp"))
+
+# Custom TTL
+provider = ProxyProvider(lambda: ProxyClient("http://backend/mcp"), cache_ttl=60)
+
+# Disable caching
+provider = ProxyProvider(lambda: ProxyClient("http://backend/mcp"), cache_ttl=0)
+```
+
+### Session Reuse for Stateless Backends
+
+By default, each tool call opens a fresh MCP session to the backend. This is the safe default because it prevents state from leaking between requests. However, for stateless HTTP backends where there's no session state to protect, this overhead is unnecessary.
+
+You can reuse a single backend session by providing a client factory that returns the same client instance:
+
+```python
+from fastmcp.server.providers.proxy import FastMCPProxy, ProxyClient
+
+base_client = ProxyClient("http://backend:8000/mcp")
+shared_client = base_client.new()
+
+proxy = FastMCPProxy(
+ client_factory=lambda: shared_client,
+ name="ReusedSessionProxy",
+)
+```
+
+This eliminates the MCP initialization handshake on every call, which can dramatically reduce latency under load. The `Client` uses reference counting for its session lifecycle, so concurrent callers sharing the same instance is safe.
+
+<Warning>
+Only reuse sessions when you know the backend is stateless (e.g. stateless HTTP). For stateful backends (stdio processes, servers that track session state), use the default fresh-session behavior to avoid context mixing.
+</Warning>
## Advanced Usage
diff --git a/src/fastmcp/server/providers/proxy.py b/src/fastmcp/server/providers/proxy.py
index 8fc1da93e..3fa1bc110 100644
--- a/src/fastmcp/server/providers/proxy.py
+++ b/src/fastmcp/server/providers/proxy.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import base64
import inspect
+import time
from collections.abc import Awaitable, Callable, Sequence
from typing import TYPE_CHECKING, Any, cast
from urllib.parse import quote
@@ -47,6 +48,7 @@ from fastmcp.server.tasks.config import TaskConfig
from fastmcp.tools.tool import Tool, ToolResult
from fastmcp.utilities.components import FastMCPComponent, get_fastmcp_metadata
from fastmcp.utilities.logging import get_logger
+from fastmcp.utilities.versions import VersionSpec, version_sort_key
if TYPE_CHECKING:
from pathlib import Path
@@ -477,6 +479,22 @@ class ProxyPrompt(Prompt):
# -----------------------------------------------------------------------------
+class _CacheEntry:
+ """A cached sequence of components with a monotonic timestamp."""
+
+ __slots__ = ("items", "timestamp")
+
+ def __init__(self, items: Sequence[Any], timestamp: float):
+ self.items = items
+ self.timestamp = timestamp
+
+ def is_fresh(self, ttl: float) -> bool:
+ return (time.monotonic() - self.timestamp) < ttl
+
+
+_DEFAULT_CACHE_TTL: float = 300.0
+
+
class ProxyProvider(Provider):
"""Provider that proxies to a remote MCP server via a client factory.
@@ -486,6 +504,16 @@ class ProxyProvider(Provider):
All components returned by this provider have task_config.mode="forbidden"
because tasks cannot be executed through a proxy.
+ Component lists (tools, resources, templates, prompts) are cached so that
+ individual lookups (e.g. during ``call_tool``) can resolve from the cache
+ instead of opening a new backend connection. The cache stores the
+ backend's raw component metadata and is shared across all sessions;
+ per-session visibility and auth filtering are applied after cache lookup
+ by the server layer. The cache is refreshed whenever a ``list_*`` call
+ is made, and entries expire after ``cache_ttl`` seconds (default 300).
+ Set ``cache_ttl=0`` to disable caching. Disabling is recommended for
+ backends whose component lists change dynamically.
+
Example:
```python
from fastmcp import FastMCP
@@ -505,6 +533,7 @@ class ProxyProvider(Provider):
def __init__(
self,
client_factory: ClientFactoryT,
+ cache_ttl: float | None = None,
):
"""Initialize a ProxyProvider.
@@ -512,9 +541,17 @@ class ProxyProvider(Provider):
client_factory: A callable that returns a Client instance when called.
This gives you full control over session creation and reuse.
Can be either a synchronous or asynchronous function.
+ cache_ttl: How long (in seconds) to cache component lists for
+ individual lookups. Defaults to 300. Set to 0 to
+ disable caching.
"""
super().__init__()
self.client_factory = client_factory
+ self._cache_ttl = cache_ttl if cache_ttl is not None else _DEFAULT_CACHE_TTL
+ self._tools_cache: _CacheEntry[Tool] | None = None
+ self._resources_cache: _CacheEntry[Resource] | None = None
+ self._templates_cache: _CacheEntry[ResourceTemplate] | None = None
+ self._prompts_cache: _CacheEntry[Prompt] | None = None
async def _get_client(self) -> Client:
"""Gets a client instance by calling the sync or async factory."""
@@ -533,13 +570,31 @@ class ProxyProvider(Provider):
client = await self._get_client()
async with client:
mcp_tools = await client.list_tools()
- return [
+ tools = [
ProxyTool.from_mcp_tool(self.client_factory, t) for t in mcp_tools
]
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
- return []
- raise
+ tools = []
+ else:
+ raise
+ self._tools_cache = _CacheEntry(tools, time.monotonic())
+ return tools
+
+ async def _get_tool(
+ self, name: str, version: VersionSpec | None = None
+ ) -> Tool | None:
+ cache = self._tools_cache
+ if cache is None or not cache.is_fresh(self._cache_ttl):
+ await self._list_tools()
+ cache = self._tools_cache
+ assert cache is not None
+ matching = [t for t in cache.items if t.name == name]
+ if version:
+ matching = [t for t in matching if version.matches(t.version)]
+ if not matching:
+ return None
+ return max(matching, key=version_sort_key) # type: ignore[type-var]
# -------------------------------------------------------------------------
# Resource methods
@@ -551,14 +606,32 @@ class ProxyProvider(Provider):
client = await self._get_client()
async with client:
mcp_resources = await client.list_resources()
- return [
+ resources = [
ProxyResource.from_mcp_resource(self.client_factory, r)
for r in mcp_resources
]
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
- return []
- raise
+ resources = []
+ else:
+ raise
+ self._resources_cache = _CacheEntry(resources, time.monotonic())
+ return resources
+
+ async def _get_resource(
+ self, uri: str, version: VersionSpec | None = None
+ ) -> Resource | None:
+ cache = self._resources_cache
+ if cache is None or not cache.is_fresh(self._cache_ttl):
+ await self._list_resources()
+ cache = self._resources_cache
+ assert cache is not None
+ matching = [r for r in cache.items if str(r.uri) == uri]
+ if version:
+ matching = [r for r in matching if version.matches(r.version)]
+ if not matching:
+ return None
+ return max(matching, key=version_sort_key) # type: ignore[type-var]
# -------------------------------------------------------------------------
# Resource template methods
@@ -570,14 +643,32 @@ class ProxyProvider(Provider):
client = await self._get_client()
async with client:
mcp_templates = await client.list_resource_templates()
- return [
+ templates = [
ProxyTemplate.from_mcp_template(self.client_factory, t)
for t in mcp_templates
]
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
- return []
- raise
+ templates = []
+ else:
+ raise
+ self._templates_cache = _CacheEntry(templates, time.monotonic())
+ return templates
+
+ async def _get_resource_template(
+ self, uri: str, version: VersionSpec | None = None
+ ) -> ResourceTemplate | None:
+ cache = self._templates_cache
+ if cache is None or not cache.is_fresh(self._cache_ttl):
+ await self._list_resource_templates()
+ cache = self._templates_cache
+ assert cache is not None
+ matching = [t for t in cache.items if t.matches(uri) is not None]
+ if version:
+ matching = [t for t in matching if version.matches(t.version)]
+ if not matching:
+ return None
+ return max(matching, key=version_sort_key) # type: ignore[type-var]
# -------------------------------------------------------------------------
# Prompt methods
@@ -589,14 +680,32 @@ class ProxyProvider(Provider):
client = await self._get_client()
async with client:
mcp_prompts = await client.list_prompts()
- return [
+ prompts = [
ProxyPrompt.from_mcp_prompt(self.client_factory, p)
for p in mcp_prompts
]
except McpError as e:
if e.error.code == METHOD_NOT_FOUND:
- return []
- raise
+ prompts = []
+ else:
+ raise
+ self._prompts_cache = _CacheEntry(prompts, time.monotonic())
+ return prompts
+
+ async def _get_prompt(
+ self, name: str, version: VersionSpec | None = None
+ ) -> Prompt | None:
+ cache = self._prompts_cache
+ if cache is None or not cache.is_fresh(self._cache_ttl):
+ await self._list_prompts()
+ cache = self._prompts_cache
+ assert cache is not None
+ matching = [p for p in cache.items if p.name == name]
+ if version:
+ matching = [p for p in matching if version.matches(p.version)]
+ if not matching:
+ return None
+ return max(matching, key=version_sort_key) # type: ignore[type-var]
# -------------------------------------------------------------------------
# Task methods
diff --git a/tests/server/providers/proxy/test_proxy_server.py b/tests/server/providers/proxy/test_proxy_server.py
index cd2514809..6cfbcb72e 100644
--- a/tests/server/providers/proxy/test_proxy_server.py
+++ b/tests/server/providers/proxy/test_proxy_server.py
@@ -1,6 +1,8 @@
import inspect
import json
+import time
from typing import Any, cast
+from unittest.mock import AsyncMock, patch
import mcp.types as mcp_types
import pytest
@@ -19,6 +21,7 @@ from fastmcp.server import create_proxy
from fastmcp.server.providers.proxy import (
FastMCPProxy,
ProxyClient,
+ ProxyProvider,
)
from fastmcp.tools.tool import ToolResult
from fastmcp.tools.tool_transform import (
@@ -767,3 +770,118 @@ class TestProxyComponentEnableDisable:
with pytest.raises(NotImplementedError, match="server.disable"):
prompt.disable()
+
+
+class TestProxyProviderCache:
+ """Tests for the ProxyProvider component list caching."""
+
+ async def test_get_tool_uses_cached_list(self, fastmcp_server):
+ """Calling call_tool should resolve from cache after an initial list."""
+ provider = ProxyProvider(
+ lambda: ProxyClient(FastMCPTransport(fastmcp_server)),
+ )
+ # Warm the cache via list
+ tools = await provider.list_tools()
+ assert any(t.name == "greet" for t in tools)
+
+ # _get_tool should resolve from cache without calling _list_tools again
+ with patch.object(
+ provider, "_get_client", new_callable=AsyncMock
+ ) as mock_client:
+ tool = await provider._get_tool("greet")
+ assert tool is not None
+ assert tool.name == "greet"
+ mock_client.assert_not_called()
+
+ async def test_get_tool_fetches_on_cold_cache(self, fastmcp_server):
+ """First _get_tool with no prior list should populate the cache."""
+ provider = ProxyProvider(
+ lambda: ProxyClient(FastMCPTransport(fastmcp_server)),
+ )
+ assert provider._tools_cache is None
+ tool = await provider._get_tool("greet")
+ assert tool is not None
+ assert provider._tools_cache is not None
+
+ async def test_cache_expires_after_ttl(self, fastmcp_server):
+ """After TTL expires, _get_tool should re-fetch from the backend."""
+ provider = ProxyProvider(
+ lambda: ProxyClient(FastMCPTransport(fastmcp_server)),
+ cache_ttl=0.0,
+ )
+ # Warm the cache
+ await provider._list_tools()
+ # With ttl=0 the cache is immediately stale, so _get_tool must re-fetch
+ assert provider._tools_cache is not None
+ original_ts = provider._tools_cache.timestamp
+
+ time.sleep(0.01)
+
+ await provider._get_tool("greet")
+ assert provider._tools_cache.timestamp > original_ts
+
+ async def test_list_tools_refreshes_cache(self, fastmcp_server):
+ """Explicit list_tools always refreshes the cache timestamp."""
+ provider = ProxyProvider(
+ lambda: ProxyClient(FastMCPTransport(fastmcp_server)),
+ )
+ await provider._list_tools()
+ first_ts = provider._tools_cache.timestamp # type: ignore[union-attr]
+
+ # Tiny sleep so monotonic clock advances
+ time.sleep(0.01)
+
+ await provider._list_tools()
+ assert provider._tools_cache.timestamp > first_ts # type: ignore[union-attr]
+
+ async def test_cache_ttl_zero_disables_caching(self, fastmcp_server):
+ """With cache_ttl=0, every _get_tool call should re-fetch."""
+ provider = ProxyProvider(
+ lambda: ProxyClient(FastMCPTransport(fastmcp_server)),
+ cache_ttl=0.0,
+ )
+ # Each _get_tool call should trigger a fresh _list_tools
+ call_count = 0
+ original_list = provider._list_tools
+
+ async def counting_list():
+ nonlocal call_count
+ call_count += 1
+ return await original_list()
+
+ with patch.object(provider, "_list_tools", side_effect=counting_list):
+ await provider._get_tool("greet")
+ await provider._get_tool("add")
+ assert call_count == 2
+
+ async def test_get_resource_uses_cache(self, fastmcp_server):
+ """Resource lookups should also use the cache."""
+ provider = ProxyProvider(
+ lambda: ProxyClient(FastMCPTransport(fastmcp_server)),
+ )
+ await provider._list_resources()
+ with patch.object(
+ provider, "_get_client", new_callable=AsyncMock
+ ) as mock_client:
+ # Even if no resources match, the cache is used (no backend call)
+ await provider._get_resource("config://app")
+ mock_client.assert_not_called()
+
+ async def test_call_tool_through_server_uses_cache(self, fastmcp_server):
+ """End-to-end: calling a tool on a proxy server should only connect
+ for the actual tool execution, not for tool resolution."""
+ proxy = create_proxy(fastmcp_server)
+ # Warm the cache by listing
+ await proxy.list_tools()
+
+ # Now call a tool β€” the provider's _list_tools should NOT be called
+ # because the cache is warm. The connection happens only in ProxyTool.run.
+ proxy_provider = next(
+ p for p in proxy.providers if isinstance(p, ProxyProvider)
+ )
+ with patch.object(
+ proxy_provider, "_list_tools", wraps=proxy_provider._list_tools
+ ) as mock_list:
+ result = await proxy.call_tool("greet", {"name": "Alice"})
+ mock_list.assert_not_called()
+ assert result.content[0].text == "Hello, Alice!" # type: ignore[union-attr]