Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-14
27 changes: 27 additions & 0 deletions openspec/changes/archive/2026-11-14-4372-mcp-retry/design.md
Original file line number Diff line number Diff line change
@@ -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.
37 changes: 37 additions & 0 deletions openspec/changes/archive/2026-11-14-4372-mcp-retry/proposal.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions openspec/changes/archive/2026-11-14-4372-mcp-retry/tasks.md
Original file line number Diff line number Diff line change
@@ -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`.

- [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
19 changes: 19 additions & 0 deletions openspec/specs/roadmap-mcp-client/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 28 additions & 1 deletion src/devops_cli/roadmap/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"

Expand Down Expand Up @@ -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()
Expand Down
88 changes: 88 additions & 0 deletions tests/roadmap/test_roadmap_mcp_connect_retry.py
Original file line number Diff line number Diff line change
@@ -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