From f725b3634587127bf2487bf0132ecea32f6dedb9 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 14 Nov 2026 07:34:25 +0000 Subject: [PATCH 1/2] docs(openspec): plan #4372 retry the first mcp connection --- .../changes/4372-mcp-retry/.openspec.yaml | 2 + openspec/changes/4372-mcp-retry/design.md | 27 ++++++ openspec/changes/4372-mcp-retry/proposal.md | 37 ++++++++ .../specs/roadmap-mcp-client/spec.md | 20 +++++ openspec/changes/4372-mcp-retry/tasks.md | 10 +++ src/devops_cli/config/constants.py | 7 ++ src/devops_cli/roadmap/mcp.py | 29 +++++- .../roadmap/test_roadmap_mcp_connect_retry.py | 88 +++++++++++++++++++ 8 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/4372-mcp-retry/.openspec.yaml create mode 100644 openspec/changes/4372-mcp-retry/design.md create mode 100644 openspec/changes/4372-mcp-retry/proposal.md create mode 100644 openspec/changes/4372-mcp-retry/specs/roadmap-mcp-client/spec.md create mode 100644 openspec/changes/4372-mcp-retry/tasks.md create mode 100644 tests/roadmap/test_roadmap_mcp_connect_retry.py diff --git a/openspec/changes/4372-mcp-retry/.openspec.yaml b/openspec/changes/4372-mcp-retry/.openspec.yaml new file mode 100644 index 0000000000..be831cee61 --- /dev/null +++ b/openspec/changes/4372-mcp-retry/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-14 diff --git a/openspec/changes/4372-mcp-retry/design.md b/openspec/changes/4372-mcp-retry/design.md new file mode 100644 index 0000000000..037b73182f --- /dev/null +++ b/openspec/changes/4372-mcp-retry/design.md @@ -0,0 +1,27 @@ +# Design + +## Context + +`RoadmapMcpToolset.__aenter__` calls `MCPToolset.__aenter__` once and wraps any exception in `RoadmapMcpUnavailableError`. + +## Goals + +- Survive the policy start delay of a new pod. +- Do not delay an authentication failure. + +## Decisions + +- **tenacity `AsyncRetrying`.** A predicate retries a `ConnectionRefusedError`, an `OSError` and an exception whose class name holds `connect`, which covers `httpx.ConnectError` without an import. +- **A bounded budget from constants.** `stop_after_delay` reads `ROADMAP_MCP_CONNECT_RETRY_SECONDS`; the wait reads the initial and maximum constants. +- **The existing error at the end.** After the budget, the last connection error is the cause of `RoadmapMcpUnavailableError`, so the message keeps the reason. + +## Risks + +- A name test for `connect` could retry an unrelated class. The name is specific to a connection error, and the budget bounds the cost. + +## Tests + +- A refused attempt twice then a success enters once. +- Every attempt refused raises the error with the URL and the last cause. +- An authentication failure is attempted once. +- The constants hold the budget values. diff --git a/openspec/changes/4372-mcp-retry/proposal.md b/openspec/changes/4372-mcp-retry/proposal.md new file mode 100644 index 0000000000..ad2cbd8bc8 --- /dev/null +++ b/openspec/changes/4372-mcp-retry/proposal.md @@ -0,0 +1,37 @@ +# Proposal + +## Why + +A new roadmap Job pod can fail its first MCP connection until kube-router programs the network policy of the pod. The MCP client raises `RoadmapMcpUnavailableError` on that first refusal and the job stops (#4372). + +## What Changes + +- `RoadmapMcpToolset.__aenter__` retries a refused connection with tenacity for `ROADMAP_MCP_CONNECT_RETRY_SECONDS`, with exponential delays from `ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS` capped at `ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS`. +- An exhausted budget raises `RoadmapMcpUnavailableError` with the target URL and the last connection error as its cause. +- An authentication failure is not retried. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `roadmap-mcp-client`: The client retries a first connection that the policy start delay refuses. + +## Impact + +- Code: `src/devops_cli/config/constants.py`, `src/devops_cli/roadmap/mcp.py` +- Tests: `tests/roadmap/test_roadmap_mcp_connect_retry.py` + +## Feasibility + +- `route_with_jev` is unrelated; tenacity is already a dependency and the repository uses it. +- The MCP client is one `__aenter__`. +- Verification commands: `uv run devops ci test tests/roadmap/test_roadmap_mcp_connect_retry.py tests/roadmap/test_roadmap_mcp.py` and `uv run devops ci --check --only lint,format,typecheck`. + +## Existing Tool Considered + +tenacity 9.1.4 is already a dependency and covers a bounded async retry with exponential backoff and a predicate. No new library. diff --git a/openspec/changes/4372-mcp-retry/specs/roadmap-mcp-client/spec.md b/openspec/changes/4372-mcp-retry/specs/roadmap-mcp-client/spec.md new file mode 100644 index 0000000000..f76b86206b --- /dev/null +++ b/openspec/changes/4372-mcp-retry/specs/roadmap-mcp-client/spec.md @@ -0,0 +1,20 @@ +## ADDED Requirements + +### Requirement: First connection retry +`RoadmapMcpToolset.__aenter__` SHALL retry a refused first connection until it succeeds or `ROADMAP_MCP_CONNECT_RETRY_SECONDS` expires, with exponential delays from `ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS` capped at `ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS`. When the budget expires, it SHALL raise `RoadmapMcpUnavailableError` with the target URL and the last connection error as its cause. It SHALL NOT retry an authentication failure. + +#### Scenario: A refused attempt then a success +- **WHEN** the first two attempts raise `ConnectionRefusedError` and the third succeeds +- **THEN** `__aenter__` returns the toolset and no `RoadmapMcpUnavailableError` is raised + +#### Scenario: Every attempt is refused +- **WHEN** every attempt within the budget raises `ConnectionRefusedError` +- **THEN** `RoadmapMcpUnavailableError` names the target URL and its cause is the last `ConnectionRefusedError` + +#### Scenario: An authentication failure +- **WHEN** the first attempt raises an authentication error +- **THEN** the client makes one attempt and raises `RoadmapMcpUnavailableError` + +#### Scenario: The budget comes from constants +- **WHEN** the retry runs +- **THEN** the total budget is `ROADMAP_MCP_CONNECT_RETRY_SECONDS` from `src/devops_cli/config/constants.py`, and the initial and maximum delays are its two companions diff --git a/openspec/changes/4372-mcp-retry/tasks.md b/openspec/changes/4372-mcp-retry/tasks.md new file mode 100644 index 0000000000..eed44d6584 --- /dev/null +++ b/openspec/changes/4372-mcp-retry/tasks.md @@ -0,0 +1,10 @@ +# Tasks + +## 1. Retry the first MCP connection + +Reads: `src/devops_cli/roadmap/mcp.py`. Changes: the same file, `src/devops_cli/config/constants.py`, and `tests/roadmap/test_roadmap_mcp_connect_retry.py`. + +- [ ] 1.1 Add the three constants. +- [ ] 1.2 Retry a refused connection in `__aenter__` with tenacity. +- [ ] 1.3 Add the four tests. + - Verification: `$ uv run devops ci test tests/roadmap/test_roadmap_mcp_connect_retry.py tests/roadmap/test_roadmap_mcp.py` passes diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 8b49794323..15d6fc3146 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -3379,6 +3379,13 @@ class WebhookExposure(StrEnum): # characters of the answer of `read_spec`, which a whole requirement can pass the limit of the other # tools. The tool calls and the model requests of a run are settings (`roadmap.stage.max_tool_calls` # and `roadmap.stage.max_requests`, #5440). +# A new roadmap Job pod can fail its first MCP connection until kube-router programs the network +# policy of the pod. The client retries a refused connection for this total budget, with this +# initial delay and this cap between attempts (#4372). +ROADMAP_MCP_CONNECT_RETRY_SECONDS: Final[float] = 30.0 +ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS: Final[float] = 1.0 +ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS: Final[float] = 8.0 + CONST_ROADMAP_STAGE_LOG_MAX_COUNT: Final[int] = 40 CONST_ROADMAP_STAGE_MAP_MAX_FILES: Final[int] = 40 CONST_ROADMAP_STAGE_MAP_LINE_CHARS: Final[int] = 180 diff --git a/src/devops_cli/roadmap/mcp.py b/src/devops_cli/roadmap/mcp.py index c2a2c4a23e..35a6d95952 100644 --- a/src/devops_cli/roadmap/mcp.py +++ b/src/devops_cli/roadmap/mcp.py @@ -22,7 +22,9 @@ from pydantic_ai.mcp import MCPToolset from pydantic_ai.messages import ToolReturn from pydantic_ai.toolsets import ToolsetTool +from tenacity import AsyncRetrying, retry_if_exception, stop_after_delay, wait_exponential +from devops_cli.config import constants from devops_cli.config.settings import ( Settings, get_mcp_implement_token, @@ -35,6 +37,15 @@ logger = logging.getLogger(__name__) + +def _connection_refused(exc: BaseException) -> bool: + """Whether `exc` is a refused or failed connection that the start delay can cause (#4372).""" + return ( + isinstance(exc, (ConnectionRefusedError, OSError)) + or "connect" in type(exc).__name__.lower() + ) + + ROLE_PLANNING: Final[str] = "planning" ROLE_IMPLEMENTATION: Final[str] = "implementation" @@ -76,10 +87,26 @@ def __init__( self.tool_names: set[str] = set() async def __aenter__(self) -> Self: + """Enter the toolset, and retry a refused first connection for a short, bounded time + (#4372). A new Job pod can meet a network policy that kube-router has not programmed yet, + and the connection is refused at once. An authentication failure is not refused, so it + goes to `RoadmapMcpUnavailableError` at once.""" try: - return await super().__aenter__() + async for attempt in AsyncRetrying( + retry=retry_if_exception(_connection_refused), + stop=stop_after_delay(constants.ROADMAP_MCP_CONNECT_RETRY_SECONDS), + wait=wait_exponential( + multiplier=1, + min=constants.ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS, + max=constants.ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS, + ), + reraise=True, + ): + with attempt: + return await super().__aenter__() except Exception as exc: raise RoadmapMcpUnavailableError(self._target_url, message=str(exc)) from exc + raise RoadmapMcpUnavailableError(self._target_url, message="No connection attempt ran.") async def list_tools(self) -> list[mcp_types.Tool]: tools = await super().list_tools() diff --git a/tests/roadmap/test_roadmap_mcp_connect_retry.py b/tests/roadmap/test_roadmap_mcp_connect_retry.py new file mode 100644 index 0000000000..19df1b8657 --- /dev/null +++ b/tests/roadmap/test_roadmap_mcp_connect_retry.py @@ -0,0 +1,88 @@ +"""Tests for the first-connection retry of the roadmap MCP client (#4372).""" + +from __future__ import annotations + +from typing import Any + +import pytest +from pydantic_ai.mcp import MCPToolset + +from devops_cli.config import constants +from devops_cli.exceptions.roadmap import RoadmapMcpUnavailableError +from devops_cli.roadmap.mcp import RoadmapMcpToolset + + +def _budget(monkeypatch: pytest.MonkeyPatch, seconds: float = 0.05) -> None: + monkeypatch.setattr(constants, "ROADMAP_MCP_CONNECT_RETRY_SECONDS", seconds) + monkeypatch.setattr(constants, "ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS", 0.001) + monkeypatch.setattr(constants, "ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS", 0.001) + + +@pytest.mark.asyncio +async def test_a_refused_first_connection_is_retried_until_it_succeeds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + attempts: list[int] = [] + + async def flaky(self: Any) -> str: + attempts.append(len(attempts) + 1) + if len(attempts) < 3: + raise ConnectionRefusedError("Connection refused") + return "entered" + + monkeypatch.setattr(MCPToolset, "__aenter__", flaky) + _budget(monkeypatch) + + toolset = RoadmapMcpToolset("http://mcp.example.com") + + assert await toolset.__aenter__() == "entered" + assert len(attempts) == 3 + + +@pytest.mark.asyncio +async def test_an_exhausted_budget_raises_the_existing_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def refused(self: Any) -> str: + raise ConnectionRefusedError("Connection refused") + + monkeypatch.setattr(MCPToolset, "__aenter__", refused) + _budget(monkeypatch, 0.02) + + toolset = RoadmapMcpToolset("http://mcp.example.com", target_url="http://mcp.example.com") + + with pytest.raises(RoadmapMcpUnavailableError) as found: + await toolset.__aenter__() + + assert found.value.url == "http://mcp.example.com" + assert isinstance(found.value.__cause__, ConnectionRefusedError) + + +@pytest.mark.asyncio +async def test_an_authentication_failure_is_not_retried( + monkeypatch: pytest.MonkeyPatch, +) -> None: + calls: list[int] = [] + + class Unauthenticated(Exception): + pass + + async def unauthenticated(self: Any) -> str: + calls.append(1) + raise Unauthenticated("HTTP 401") + + monkeypatch.setattr(MCPToolset, "__aenter__", unauthenticated) + _budget(monkeypatch, 10.0) + + toolset = RoadmapMcpToolset("http://mcp.example.com") + + with pytest.raises(RoadmapMcpUnavailableError, match="HTTP 401"): + await toolset.__aenter__() + + assert len(calls) == 1 + + +def test_the_retry_budget_comes_from_the_constants_module() -> None: + assert constants.ROADMAP_MCP_CONNECT_RETRY_SECONDS == 30.0 + assert constants.ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS == 1.0 + assert constants.ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS == 8.0 From dcf4ad9ea7aa63f092a9bcc7c7f628e66c541096 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 14 Nov 2026 07:34:49 +0000 Subject: [PATCH 2/2] docs(openspec): archive #4372 retry the first mcp connection --- .../2026-11-14-4372-mcp-retry}/.openspec.yaml | 0 .../2026-11-14-4372-mcp-retry}/design.md | 0 .../2026-11-14-4372-mcp-retry}/proposal.md | 0 .../specs/roadmap-mcp-client/spec.md | 0 .../2026-11-14-4372-mcp-retry}/tasks.md | 6 +++--- openspec/specs/roadmap-mcp-client/spec.md | 19 +++++++++++++++++++ 6 files changed, 22 insertions(+), 3 deletions(-) rename openspec/changes/{4372-mcp-retry => archive/2026-11-14-4372-mcp-retry}/.openspec.yaml (100%) rename openspec/changes/{4372-mcp-retry => archive/2026-11-14-4372-mcp-retry}/design.md (100%) rename openspec/changes/{4372-mcp-retry => archive/2026-11-14-4372-mcp-retry}/proposal.md (100%) rename openspec/changes/{4372-mcp-retry => archive/2026-11-14-4372-mcp-retry}/specs/roadmap-mcp-client/spec.md (100%) rename openspec/changes/{4372-mcp-retry => archive/2026-11-14-4372-mcp-retry}/tasks.md (72%) diff --git a/openspec/changes/4372-mcp-retry/.openspec.yaml b/openspec/changes/archive/2026-11-14-4372-mcp-retry/.openspec.yaml similarity index 100% rename from openspec/changes/4372-mcp-retry/.openspec.yaml rename to openspec/changes/archive/2026-11-14-4372-mcp-retry/.openspec.yaml diff --git a/openspec/changes/4372-mcp-retry/design.md b/openspec/changes/archive/2026-11-14-4372-mcp-retry/design.md similarity index 100% rename from openspec/changes/4372-mcp-retry/design.md rename to openspec/changes/archive/2026-11-14-4372-mcp-retry/design.md diff --git a/openspec/changes/4372-mcp-retry/proposal.md b/openspec/changes/archive/2026-11-14-4372-mcp-retry/proposal.md similarity index 100% rename from openspec/changes/4372-mcp-retry/proposal.md rename to openspec/changes/archive/2026-11-14-4372-mcp-retry/proposal.md diff --git a/openspec/changes/4372-mcp-retry/specs/roadmap-mcp-client/spec.md b/openspec/changes/archive/2026-11-14-4372-mcp-retry/specs/roadmap-mcp-client/spec.md similarity index 100% rename from openspec/changes/4372-mcp-retry/specs/roadmap-mcp-client/spec.md rename to openspec/changes/archive/2026-11-14-4372-mcp-retry/specs/roadmap-mcp-client/spec.md diff --git a/openspec/changes/4372-mcp-retry/tasks.md b/openspec/changes/archive/2026-11-14-4372-mcp-retry/tasks.md similarity index 72% rename from openspec/changes/4372-mcp-retry/tasks.md rename to openspec/changes/archive/2026-11-14-4372-mcp-retry/tasks.md index eed44d6584..0e69a32be3 100644 --- a/openspec/changes/4372-mcp-retry/tasks.md +++ b/openspec/changes/archive/2026-11-14-4372-mcp-retry/tasks.md @@ -4,7 +4,7 @@ Reads: `src/devops_cli/roadmap/mcp.py`. Changes: the same file, `src/devops_cli/config/constants.py`, and `tests/roadmap/test_roadmap_mcp_connect_retry.py`. -- [ ] 1.1 Add the three constants. -- [ ] 1.2 Retry a refused connection in `__aenter__` with tenacity. -- [ ] 1.3 Add the four tests. +- [x] 1.1 Add the three constants. +- [x] 1.2 Retry a refused connection in `__aenter__` with tenacity. +- [x] 1.3 Add the four tests. - Verification: `$ uv run devops ci test tests/roadmap/test_roadmap_mcp_connect_retry.py tests/roadmap/test_roadmap_mcp.py` passes diff --git a/openspec/specs/roadmap-mcp-client/spec.md b/openspec/specs/roadmap-mcp-client/spec.md index 476d1f73be..1f3d5391db 100644 --- a/openspec/specs/roadmap-mcp-client/spec.md +++ b/openspec/specs/roadmap-mcp-client/spec.md @@ -74,3 +74,22 @@ The change MUST report the stage and implement eval scores with and without the #### Scenario: Eval comparison - **WHEN** The stage and implement evals run with MCP off and on. - **THEN** The change records both scores and the difference. + +### Requirement: First connection retry +`RoadmapMcpToolset.__aenter__` SHALL retry a refused first connection until it succeeds or `ROADMAP_MCP_CONNECT_RETRY_SECONDS` expires, with exponential delays from `ROADMAP_MCP_CONNECT_RETRY_INITIAL_SECONDS` capped at `ROADMAP_MCP_CONNECT_RETRY_MAX_SECONDS`. When the budget expires, it SHALL raise `RoadmapMcpUnavailableError` with the target URL and the last connection error as its cause. It SHALL NOT retry an authentication failure. + +#### Scenario: A refused attempt then a success +- **WHEN** the first two attempts raise `ConnectionRefusedError` and the third succeeds +- **THEN** `__aenter__` returns the toolset and no `RoadmapMcpUnavailableError` is raised + +#### Scenario: Every attempt is refused +- **WHEN** every attempt within the budget raises `ConnectionRefusedError` +- **THEN** `RoadmapMcpUnavailableError` names the target URL and its cause is the last `ConnectionRefusedError` + +#### Scenario: An authentication failure +- **WHEN** the first attempt raises an authentication error +- **THEN** the client makes one attempt and raises `RoadmapMcpUnavailableError` + +#### Scenario: The budget comes from constants +- **WHEN** the retry runs +- **THEN** the total budget is `ROADMAP_MCP_CONNECT_RETRY_SECONDS` from `src/devops_cli/config/constants.py`, and the initial and maximum delays are its two companions