:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp-store): re-list tools when a gateway call names an unregistered one (#105115)
Vojta Bartoša1ecc0593a77
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex 47b9474552d2..29eeb126bf9c 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -43,7 +43,12 @@ from products.mcp_store.backend.models import ()from products.mcp_store.backend.policy import GatewayCaller, PolicyContext, is_read_only_connector_toolfrom products.mcp_store.backend.proxy import record_tool_call_audit, resolve_call_decision, validate_installation_auth-from products.mcp_store.backend.tools import ToolCallError, ToolsFetchError, call_upstream_tool+from products.mcp_store.backend.tools import (+ ToolCallError,+ ToolsFetchError,+ call_upstream_tool,+ resync_installation_tools,+)# Re-exported for the presentation layer ("presentation must use facade"# import-linter contract): the single MCP URL policy entry point — shared SSRF@@ -569,6 +574,22 @@ def member_server_tools(team_id: int, user_id: int, server_host: str) -> list[Coreturn tools+def _registered_tool(installation: MCPServerInstallation, tool_name: str) -> MCPServerInstallationTool | None:+ """The installation's row for one tool, re-listing upstream once on a miss.++ A connection whose connect-time listing never landed holds no rows at all,+ and a call it cannot resolve against policy is refused. A row marked removed+ counts as a miss too, so a tool the upstream server brings back under the+ same name is picked up here rather than waiting for "Refresh tools".+ """++ rows = installation.tools.filter(tool_name=tool_name).order_by("-last_seen_at", "-id")+ tool = rows.first()+ if (tool is None or tool.removed_at is not None) and resync_installation_tools(installation):+ tool = rows.first()+ return tool++def _member_access_outcome(installation: MCPServerInstallation, team_id: int, user_id: int) -> ConnectorCallOutcome | None:@@ -616,7 +637,7 @@ def call_member_server_tool(if access_outcome is not None:return access_outcome- tool = installation.tools.filter(tool_name=tool_name).order_by("-last_seen_at", "-id").first()+ tool = _registered_tool(installation, tool_name)if tool is None:return ConnectorCallOutcome(status="tool_missing", detail=f"Tool '{tool_name}' is not registered for this connection."diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex 90ef6352c453..336a5c969aa9 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -28,6 +28,7 @@ logger = structlog.get_logger(__name__)UPSTREAM_TIMEOUT = 180MAX_PROXY_BODY_SIZE = 1_048_576 # 1 MB+MAX_LOGGED_MISSING_TOOLS = 20REDIRECT_STATUS_CODES = {301, 302, 307, 308}# JSON-RPC error codes used by per-tool approval enforcement. -32000..-32099 is@@ -365,6 +366,57 @@ def _evaluate_tool_call(return None+def _requested_tool_names(data: dict[str, Any] | list[Any]) -> set[str]:+ names: set[str] = set()+ for item in data if isinstance(data, list) else [data]:+ if not _is_tools_call(item):+ continue+ params = item.get("params") or {}+ name = params.get("name") if isinstance(params, dict) else None+ if isinstance(name, str) and name:+ names.add(name)+ return names+++def _unresolvable_tool_names(tools: dict[str, MCPServerInstallationTool], requested: set[str]) -> set[str]:+ """The requested names no live row answers. A row marked removed counts as a+ miss, so a tool the upstream server brings back is picked up by a re-listing."""+ return {name for name in requested if tools.get(name) is None or tools[name].removed_at is not None}+++def _tools_by_name(installation: MCPServerInstallation, requested: set[str]) -> dict[str, MCPServerInstallationTool]:+ """The installation's tool rows, re-listed from upstream on a miss.++ These rows are the policy registry rather than a performance cache: a call+ whose tool has no row cannot be resolved against policy, so it is refused.+ An installation whose connect-time listing never landed therefore refuses+ every call until a person presses "Refresh tools". Re-listing once on a miss+ repairs that without waiting for them, and covers a tool the upstream server+ renamed after the last listing.+ """+ tools = {t.tool_name: t for t in installation.tools.all()}+ if not _unresolvable_tool_names(tools, requested):+ return tools++ from .tools import resync_installation_tools # noqa: PLC0415 — tools.py imports this module++ if resync_installation_tools(installation):+ tools = {t.tool_name: t for t in installation.tools.all()}+ missing = _unresolvable_tool_names(tools, requested)+ if missing:+ logger.warning(+ "MCP tool call refers to an unregistered tool",+ installation_id=str(installation.id),+ url=installation.url,+ # A batch carries as many names as the body allows, and the size limit+ # is checked further down, so log a sample rather than all of them.+ missing_tools=sorted(missing)[:MAX_LOGGED_MISSING_TOOLS],+ missing_tool_count=len(missing),+ registered_tool_count=len(tools),+ )+ return tools++def enforce_tool_approval(installation: MCPServerInstallation,data: dict[str, Any] | list[Any],@@ -382,7 +434,7 @@ def enforce_tool_approval(if not any(_is_tools_call(item) for item in data):return None# Pre-fetch the installation's tools once to avoid N queries on batched tools/call.- tools_by_name = {t.tool_name: t for t in installation.tools.all()}+ tools_by_name = _tools_by_name(installation, _requested_tool_names(data))responses: list[dict[str, Any]] = []any_blocked = Falseany_passthrough = False@@ -423,7 +475,7 @@ def enforce_tool_approval(if not _is_tools_call(data):return None- tools_by_name = {t.tool_name: t for t in installation.tools.all()}+ tools_by_name = _tools_by_name(installation, _requested_tool_names(data))blocked = _evaluate_tool_call(tools_by_name, data, policy_context, audit_entries)if blocked is None:return Nonediff --git a/products/mcp_store/backend/tasks/tasks.py b/products/mcp_store/backend/tasks/tasks.pyindex 16c18fa4c150..5dad7d6b57f2 100644--- a/products/mcp_store/backend/tasks/tasks.py+++ b/products/mcp_store/backend/tasks/tasks.py@@ -43,7 +43,16 @@ def queue_sync_mcp_server_templates() -> None:logger.exception("Failed to release sync_mcp_server_templates lock")-@shared_task(ignore_result=True)+# A listing that fails here leaves the installation with no tool rows, and the+# gateway refuses every call to a tool that has no row.+@shared_task(+ ignore_result=True,+ autoretry_for=(ToolsFetchError,),+ retry_backoff=30,+ retry_backoff_max=600,+ retry_jitter=True,+ max_retries=5,+)@skip_team_scope_auditdef sync_installation_tools_task(installation_id: str) -> None:try:@@ -51,11 +60,4 @@ def sync_installation_tools_task(installation_id: str) -> None:except MCPServerInstallation.DoesNotExist:logger.info("sync_installation_tools_task: installation gone", installation_id=installation_id)return- try:- sync_installation_tools(installation)- except ToolsFetchError as exc:- logger.info(- "sync_installation_tools_task: upstream fetch failed",- installation_id=installation_id,- error=str(exc),- )+ sync_installation_tools(installation)diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex e77f60472f92..b43c1d50c484 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -939,6 +939,28 @@ class TestCallMemberServerTool(BaseTest):def _call(self, name: str = "list_events", **kwargs):return call_member_server_tool(self.team.id, self.user.id, self.HOST, name, {"limit": 5}, **kwargs)+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")+ @patch("products.mcp_store.backend.facade.api.call_upstream_tool", return_value={"content": []})+ def test_a_tool_with_no_row_is_listed_before_the_call_is_refused(self, mock_call, mock_fetch) -> None:+ # A connection whose connect-time listing never landed holds no rows, and+ # without a re-listing it refuses every call for the life of the connection.+ self._installation()+ mock_fetch.return_value = [{"name": "list_events", "annotations": {"readOnlyHint": True}}]++ # Freshly listed tools are opt-in, so policy answers the call now.+ assert self._call().status == "needs_approval"+ mock_call.assert_not_called()++ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")+ @patch("products.mcp_store.backend.facade.api.call_upstream_tool", return_value={"content": []})+ def test_a_removed_tool_the_server_brought_back_is_callable_again(self, mock_call, mock_fetch) -> None:+ installation = self._installation()+ self._tool(installation, removed_at=timezone.now())+ mock_fetch.return_value = [{"name": "list_events", "annotations": {"readOnlyHint": True}}]++ assert self._call().status == "ok"+ mock_call.assert_called_once()+@patch("products.mcp_store.backend.facade.api.call_upstream_tool",return_value={"content": [{"type": "text", "text": "3 events"}], "isError": False},diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.pyindex 3cc9821fe0f6..7c6e74265af0 100644--- a/products/mcp_store/backend/test/test_proxy.py+++ b/products/mcp_store/backend/test/test_proxy.py@@ -734,8 +734,9 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTeassert body["error"]["code"] == -32002mock_client_cls.assert_not_called()+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools", return_value=[])@patch("products.mcp_store.backend.proxy.pinned_client")- def test_unknown_tool_returns_method_not_found(self, mock_client_cls):+ def test_unknown_tool_returns_method_not_found(self, mock_client_cls, mock_fetch):installation = self._installation()response = self.client.post(@@ -746,12 +747,44 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTebody = response.json()assert body["error"]["code"] == -32601+ assert mock_fetch.call_count == 1mock_client_cls.assert_not_called()+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")@patch("products.mcp_store.backend.proxy.pinned_client")- def test_removed_tool_is_not_callable(self, mock_client_cls):+ def test_call_for_an_unlisted_tool_relists_before_refusing(self, mock_client_cls, mock_fetch):+ # An installation whose connect-time listing never landed has no rows, and+ # without a re-listing it refuses every call for the life of the connection.installation = self._installation()- self._tool(installation, "legacy", "approved", removed_at=timezone.now())+ mock_fetch.return_value = [{"name": "search", "description": "Search"}]++ response = self.client.post(+ self._proxy_url(installation.id),+ data={"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "search"}},+ format="json",+ )++ # Freshly listed tools are opt-in, so policy answers the call now.+ assert response.json()["error"]["code"] == -32001+ assert installation.tools.filter(tool_name="search").exists()+ mock_client_cls.assert_not_called()++ @parameterized.expand(+ [+ # A tool the upstream server brought back under the same name must stop+ # being refused; the row alone cannot tell the two cases apart.+ ("still_gone", [], -32601),+ ("restored_upstream", [{"name": "legacy"}], -32001),+ ]+ )+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")+ @patch("products.mcp_store.backend.proxy.pinned_client")+ def test_removed_tool_is_relisted_before_it_is_refused(+ self, _name, upstream_tools, expected_code, mock_client_cls, mock_fetch+ ):+ installation = self._installation()+ self._tool(installation, "legacy", "needs_approval", removed_at=timezone.now())+ mock_fetch.return_value = upstream_toolsresponse = self.client.post(self._proxy_url(installation.id),@@ -759,8 +792,8 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTeformat="json",)- body = response.json()- assert body["error"]["code"] == -32601+ assert response.json()["error"]["code"] == expected_code+ assert mock_fetch.call_count == 1mock_client_cls.assert_not_called()@patch("products.mcp_store.backend.proxy.pinned_client")diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.pyindex e48451fe22cf..c1a4b4c9d884 100644--- a/products/mcp_store/backend/test/test_tools.py+++ b/products/mcp_store/backend/test/test_tools.py@@ -13,16 +13,19 @@ from django.utils import timezoneimport httpxfrom parameterized import parameterized+from posthog.redis import get_clientfrom posthog.security.url_validation import PinnedUrlVerdictfrom products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationToolfrom products.mcp_store.backend.tools import (CALL_TIMEOUT,HANDSHAKE_TIMEOUT,+ RESYNC_FAILURE_THROTTLE_SECONDS,ToolCallError,ToolsFetchError,call_upstream_tool,fetch_upstream_tools,+ resync_installation_tools,sync_installation_tools,)@@ -287,6 +290,25 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):with pytest.raises(ToolsFetchError, match="unreachable"):fetch_upstream_tools(installation)+ @parameterized.expand(+ [+ ("remote_protocol", httpx.RemoteProtocolError("server disconnected")),+ ("too_many_redirects", httpx.TooManyRedirects("redirect loop")),+ ]+ )+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)+ @patch("products.mcp_store.backend.tools.pinned_client")+ def test_fetch_upstream_tools_reports_handshake_faults_as_fetch_errors(self, _name, error, mock_client_cls, _allow):+ # Callers on the request path turn ToolsFetchError into a refusal, so an+ # httpx error escaping here would become a 500 instead.+ installation = self._installation()+ client = MagicMock()+ client.post.side_effect = error+ mock_client_cls.return_value.__enter__.return_value = client++ with pytest.raises(ToolsFetchError, match="handshake failed"):+ fetch_upstream_tools(installation)+@patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)@patch("products.mcp_store.backend.tools.pinned_client")def test_fetch_upstream_tools_raises_on_initialize_error(self, mock_client_cls, _allow):@@ -298,6 +320,19 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):with pytest.raises(ToolsFetchError, match="initialize returned status 401"):fetch_upstream_tools(installation)+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)+ @patch("products.mcp_store.backend.tools.pinned_client")+ def test_fetch_upstream_tools_drops_a_tool_whose_name_is_not_a_string(self, mock_client_cls, _allow):+ # A non-string name is unhashable, so sync_installation_tools would raise+ # TypeError on it — a 500 on the request path that re-lists.+ installation = self._installation()+ tools_body = json.dumps(+ {"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": ["search"]}, {"name": "alpha"}]}}+ )+ _install_handshake_mock(mock_client_cls, tools_list_response=_build_response(body=tools_body))++ assert [tool["name"] for tool in fetch_upstream_tools(installation)] == ["alpha"]+@patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)@patch("products.mcp_store.backend.tools.pinned_client")def test_fetch_upstream_tools_raises_when_result_missing(self, mock_client_cls, _allow):@@ -440,6 +475,32 @@ class TestSyncInstallationTools(ClickhouseTestMixin, APIBaseTest):assert tool.description == "Search something"assert tool.removed_at is None+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")+ def test_a_row_another_sync_created_is_updated_rather_than_duplicated(self, mock_fetch):+ # The install task, "Refresh tools" and the request-path repair can overlap,+ # and the loser of the (installation, tool_name) unique constraint would+ # raise — a 500 out of the proxy, since nothing catches IntegrityError.+ installation = self._installation()+ mock_fetch.return_value = [{"name": "search", "description": "fresh"}]++ def create_the_row_behind_this_sync(_installation):+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="search",+ description="raced",+ approval_state="approved",+ last_seen_at=timezone.now(),+ )+ return mock_fetch.return_value++ mock_fetch.side_effect = create_the_row_behind_this_sync+ sync_installation_tools(installation)++ tool = installation.tools.get(tool_name="search")+ assert tool.description == "fresh"+ # The row the other sync created keeps its approval state.+ assert tool.approval_state == "approved"+@patch("products.mcp_store.backend.tools.fetch_upstream_tools")def test_sync_persists_upstream_annotations(self, mock_fetch):installation = self._installation()@@ -515,3 +576,40 @@ class TestSyncInstallationTools(ClickhouseTestMixin, APIBaseTest):assert tool.description == "new description"assert "properties" in tool.input_schemaassert tool.approval_state == "approved"+++class TestResyncInstallationTools(ClickhouseTestMixin, APIBaseTest):+ def _installation(self) -> MCPServerInstallation:+ return MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ url=f"https://mcp-{uuid.uuid4().hex[:8]}.example.com/mcp",+ display_name="Test",+ auth_type="api_key",+ sensitive_configuration={"api_key": "sk-test"},+ )++ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")+ def test_upstream_is_listed_once_per_throttle_window(self, mock_fetch):+ # Callers re-list on a miss, so without the throttle an agent looping on a+ # name the server does not have opens one handshake per call.+ installation = self._installation()+ mock_fetch.return_value = [{"name": "search"}]++ assert resync_installation_tools(installation) is True+ assert resync_installation_tools(installation) is False+ assert mock_fetch.call_count == 1+ assert installation.tools.filter(tool_name="search").exists()++ @patch("products.mcp_store.backend.tools.fetch_upstream_tools", side_effect=ToolsFetchError("upstream down"))+ def test_failed_listing_is_reported_rather_than_raised(self, _mock_fetch):+ # This runs inside the proxy request path, where raising turns a refused+ # tool call into a 500.+ installation = self._installation()++ assert resync_installation_tools(installation) is False++ # A listing that failed refreshed nothing, so holding the full window would+ # keep both repair paths shut long after a transient fault cleared.+ remaining = get_client().ttl(f"mcp_store:tools_resync:{installation.id}")+ assert 0 < remaining <= RESYNC_FAILURE_THROTTLE_SECONDSdiff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.pyindex 414e50db90b5..470b05a1b97b 100644--- a/products/mcp_store/backend/tools.py+++ b/products/mcp_store/backend/tools.py@@ -2,7 +2,8 @@The proxy enforces per-tool approval (`approved` / `needs_approval` / `do_not_use`)against these cached rows — so they need to stay reasonably fresh. Refresh happens-on successful install/reconnect and on-demand via the UI's "Refresh tools" button.+on successful install/reconnect, on-demand via the UI's "Refresh tools" button, and+through `resync_installation_tools` when a caller names a tool that has no row."""import json@@ -13,6 +14,7 @@ from django.utils import timezoneimport httpximport structlog+from posthog.redis import get_clientfrom posthog.security.pinned_httpx import pinned_clientfrom posthog.security.pinned_requests import SSRFBlockedError@@ -47,6 +49,19 @@ HANDSHAKE_TIMEOUT = 10# interactive agent, and a worker blocked for minutes is worse than a retry.CALL_TIMEOUT = 60+# Bounds how often a cache miss can reach upstream, so a caller looping on a+# name the server does not have cannot open a handshake per call. A re-listing+# is three requests at HANDSHAKE_TIMEOUT each, inside the request that refuses+# the call, so the window is wide. A person who cannot wait it out presses+# "Refresh tools", which lists upstream directly and ignores this.+RESYNC_THROTTLE_SECONDS = 60 * 60++# A listing that failed refreshed nothing, so holding the full window would let+# one transient upstream fault keep both repair paths shut for an hour. This is+# still long enough that a caller looping on a missing name cannot make every+# call pay for a failed handshake.+RESYNC_FAILURE_THROTTLE_SECONDS = 5 * 60+class ToolsFetchError(Exception):pass@@ -126,6 +141,11 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,raise ToolsFetchError("Upstream MCP server unreachable") from excexcept httpx.TimeoutException as exc:raise ToolsFetchError("Upstream MCP server timed out") from exc+ except httpx.HTTPError as exc:+ # A malformed reply or a redirect loop is an upstream fault like the+ # cases above. Callers on the request path turn ToolsFetchError into a+ # refusal; anything else escaping here becomes a 500.+ raise ToolsFetchError(f"Upstream MCP handshake failed: {exc}") from excdef call_upstream_tool(@@ -281,7 +301,9 @@ def _mcp_list_tools(client: httpx.Client, url: str, headers: dict[str, str]) ->if not isinstance(tools, list):raise ToolsFetchError("tools/list response missing 'result.tools' array")- return [t for t in tools if isinstance(t, dict) and t.get("name")]+ # The upstream server is untrusted input, and a non-string name is unhashable:+ # it would crash the sync rather than cost us one skipped tool.+ return [t for t in tools if isinstance(t, dict) and isinstance(t.get("name"), str) and t["name"]]def _mcp_call_tool(@@ -405,39 +427,46 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServrow = existing_by_name.get(tool_name)if row is None:- MCPServerInstallationTool.objects.create(+ # get_or_create rather than create: the install task, "Refresh tools"+ # and the request-path repair can overlap, and the loser of the+ # (installation, tool_name) unique constraint would raise.+ row, created = MCPServerInstallationTool.objects.get_or_create(installation=installation,tool_name=tool_name,- display_name=display_name,- description=description,- input_schema=input_schema,- annotations=annotations,- # New tools default to needs_approval so adoption stays explicit.- # The policy engine keys off this exact value to tell a synced- # default apart from a member's real choice — keep them in step.- approval_state=SYNC_DEFAULT_APPROVAL_STATE,- last_seen_at=now,- removed_at=None,- )- else:- row.display_name = display_name- row.description = description- row.input_schema = input_schema- row.annotations = annotations- row.last_seen_at = now- # A previously-removed tool reappeared; preserve approval_state but clear the flag.- row.removed_at = None- row.save(- update_fields=[- "display_name",- "description",- "input_schema",- "annotations",- "last_seen_at",- "removed_at",- "updated_at",- ]+ defaults={+ "display_name": display_name,+ "description": description,+ "input_schema": input_schema,+ "annotations": annotations,+ # New tools default to needs_approval so adoption stays explicit.+ # The policy engine keys off this exact value to tell a synced+ # default apart from a member's real choice — keep them in step.+ "approval_state": SYNC_DEFAULT_APPROVAL_STATE,+ "last_seen_at": now,+ "removed_at": None,+ },)+ if created:+ continue++ row.display_name = display_name+ row.description = description+ row.input_schema = input_schema+ row.annotations = annotations+ row.last_seen_at = now+ # A previously-removed tool reappeared; preserve approval_state but clear the flag.+ row.removed_at = None+ row.save(+ update_fields=[+ "display_name",+ "description",+ "input_schema",+ "annotations",+ "last_seen_at",+ "removed_at",+ "updated_at",+ ]+ )# Mark anything we didn't see as removed; keep their approval_state intact.for tool_name, row in existing_by_name.items():@@ -449,3 +478,36 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServrow.save(update_fields=["removed_at", "updated_at"])return list(installation.tools.all())+++def resync_installation_tools(installation: MCPServerInstallation) -> bool:+ """Re-list an installation's tools on a cache miss, at most once per window.++ Returns whether the rows were refreshed, so the caller knows to re-read them.+ A refusal to call a tool is only correct while the rows describe the upstream+ server.+ """+ key = f"mcp_store:tools_resync:{installation.id}"+ try:+ if not get_client().set(key, 1, nx=True, ex=RESYNC_THROTTLE_SECONDS):+ return False+ except Exception:+ # Fail closed: an unbounded re-listing is worse than none.+ logger.exception("mcp_store tools re-listing throttle unavailable", installation_id=str(installation.id))+ return False++ try:+ sync_installation_tools(installation)+ except ToolsFetchError as exc:+ logger.warning(+ "mcp_store tools re-listing failed",+ installation_id=str(installation.id),+ url=installation.url,+ error=str(exc),+ )+ try:+ get_client().expire(key, RESYNC_FAILURE_THROTTLE_SECONDS)+ except Exception:+ logger.exception("mcp_store tools re-listing throttle not shortened", installation_id=str(installation.id))+ return False+ return True