Skip to content

The agent that grows with you

fix(mcp): _connect_server installs the owner scope inside the try so a failed install releases the claim

teknium192deb8e87135
diff --git a/tests/tools/test_mcp_connect_secret_scope.py b/tests/tools/test_mcp_connect_secret_scope.py
index 954a5e70f78..f40956ee515 100644
--- a/tests/tools/test_mcp_connect_secret_scope.py
+++ b/tests/tools/test_mcp_connect_secret_scope.py
@@ -102,3 +102,22 @@ def test_unscoped_discover_interpolates_header_refs_under_the_owners_scope(profi
assert handed_over["httpsrv"]["headers"]["Authorization"] == f"Bearer {TOKEN_VALUE}"
assert current_secret_scope() is None
+
+def test_connect_scope_install_failure_releases_the_discovery_claim(monkeypatch, spawn_env):
+ """Red on base: the scope install sat between the claim ``set(None)`` and the try, so a raise from
+ hydration skipped ``_connect_server_claim.reset`` and the caller's claim stayed cleared."""
+ async def _boom():
+ raise RuntimeError("hydration failed")
+ monkeypatch.setattr(discovery, "_install_owner_secret_scope", _boom)
+ claim = lambda server: None # noqa: E731
+
+ async def _run():
+ token = discovery._core._connect_server_claim.set(claim)
+ try:
+ with pytest.raises(RuntimeError, match="hydration failed"):
+ await discovery._connect_server("demo", {"command": "true"})
+ assert discovery._core._connect_server_claim.get() is claim
+ finally:
+ discovery._core._connect_server_claim.reset(token)
+
+ asyncio.run(_run())
diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py
index 550c3d3bcaa..628a67a162a 100644
--- a/tools/mcp_tool_discovery.py
+++ b/tools/mcp_tool_discovery.py
@@ -113,8 +113,9 @@ async def _connect_server(name: str, config: dict) -> _core.MCPServerTask:
claim(server)
# The run task copies this context: don't retain the discovery closure for its life.
claim_token = _core._connect_server_claim.set(None) if claim is not None else None
- scope_token = await _install_owner_secret_scope()
+ scope_token = None
try:
+ scope_token = await _install_owner_secret_scope()
await server.start(config)
except asyncio.CancelledError:
raise # start() already reaps server._task; shutdown() here could swallow the cancel