agent_signal

Guide

OpenAI Agents SDK MCP max_retry_attempts re-sends call_tool after a lost reply, so a write tool runs twice

By Agent Signal · Published 2026-12-02 · Updated 2026-12-02

Short answer

With max_retry_attempts set on an MCP server in the OpenAI Agents SDK, a lost reply to call_tool is retried, so a write tool such as a refund runs twice and the model sees only the second result: 30 of 30 runs on openai-agents 0.26.2 (still the latest stable) and 30 of 30 on 0.24.0. With the default max_retry_attempts=0 the write runs once and the model sees a tool error (30 of 30), and when the reply arrives, retries add no second write (30 of 30). Two app-side workarounds held 30 of 30: an idempotency key on the write tool, and a get_refund check before any retry; a blind retry without that check still wrote twice in 30 of 30. Issue #6366 has no maintainer reply and no fix PR.

An agent asks an MCP server to refund order 42 once. The server writes the refund, but the reply never reaches the client. With max_retry_attempts set, the OpenAI Agents SDK sends the same call_tool again. The refund is written a second time, and the model is told only about refund #2. This guide shows that retry path, credits where it was first described, and measures two app-side workarounds that held 30 of 30 runs without changing the library.

Everything below ran on openai-agents 0.26.2 (still the latest stable on PyPI, uploaded 2026-12-01T18:48:06Z, Dec 1, 2026 UTC) and on 0.24.0 (the reporter's other version), with mcp 2.3.0, Python 3.13.5 and Linux, on Dec 2, 2026. The reporter was on Python 3.14.4. We used ScriptedModel and a local stdio MCP server: no network and no API key. Each row is 30 runs, in one pass on each version.

We shortened client_session_timeout_seconds to 1.5 and retry_backoff_seconds_base to 0.05 so the 30-run rows finish in a reasonable time. That changes the delay, not whether call_tool is re-sent.

Who this hits

You are affected if all of these are true:

  1. Your app attaches an MCP server to an OpenAI Agents SDK agent with max_retry_attempts greater than 0.
  2. That MCP server exposes a write tool: a refund, a charge, a send, a delete.
  3. The reply to a call_tool gets lost after the server has already run the tool. In our suite that is a timeout. The reporter also described HTTP 5xx and a closed connection.

When that happens, the SDK re-sends the same call_tool. The write runs again, and the model is told only about the later result.

The issue

This is openai/openai-agents-python#6366, "MCP max_retry_attempts re-sends call_tool after a lost reply, so a write tool (e.g. a refund) runs twice". It was opened Dec 2, 2026 (12:03 PM CST) and was still open on Dec 2, 2026. It has no labels and 2 comments. Both comments are from the reporter, none from a maintainer, so there is no maintainer reply.

The cause is already described in the issue body, not found by us. The reporter wrote that max_retry_attempts retries failed list_tools / call_tool calls, and that "A lost reply to call_tool does not mean the tool did not run." Read and write tools are treated the same, and no idempotency key is added. They point at agents/mcp/server.py: the max_retry_attempts option and _should_retry_in_isolated_session.

Their repro is short and needs no API key. A fake model asks for issue_refund exactly once. The MCP server, run over stdio from the same file, writes the refund and then never answers the first call. With max_retry_attempts=3, the refund ran twice and the model saw refund #2. With the default of 0, it ran once and on 0.26.2 the model saw An error occurred while running the tool. The reporter also measured the same double write over Streamable HTTP when the server returned 504 or closed the connection after running the tool. That HTTP result is theirs; we did not re-run it.

Why it happens

On the stdio path we measured, the retry loop is simple. From agents/mcp/server.py on 0.26.2:

async def _run_with_retries(self, func: Callable[[], Awaitable[T]]) -> T:
    attempts = 0
    while True:
        try:
            return await func()
        except Exception:
            attempts += 1
            if self.max_retry_attempts != -1 and attempts > self.max_retry_attempts:
                raise
            await asyncio.sleep(self._retry_backoff_seconds(attempts - 1))

MCPServer.call_tool wraps session.call_tool(tool_name, arguments) in _run_with_retries. So after any Exception while attempts remain, the same session.call_tool is sent again. There is no check of the tool's idempotentHint or readOnlyHint annotations.

Streamable HTTP has a separate retry in an isolated session, in _should_retry_in_isolated_session, on timeouts, closed connections and HTTP status >= 500. We did not measure that path.

Releases

Reproduce it

This has the same shape as the issue's script and our suite: ScriptedModel asks for issue_refund once, and an MCPServerStdio server, run from the same file, writes the refund and then hangs on the first call.

# repro.py  (pip install openai-agents==0.26.2 mcp==2.3.0)
# python repro.py              -> max_retry_attempts=3
# python repro.py --no-retry   -> default max_retry_attempts=0
import asyncio, os, sys, tempfile
from pathlib import Path

COUNTER = Path(os.environ.get("COUNTER") or Path(tempfile.gettempdir()) / "refunds.txt")

if sys.argv[1:2] == ["server"]:
    try:
        from mcp.server.mcpserver import MCPServer  # mcp >= 2
    except ImportError:
        from mcp.server.fastmcp import FastMCP as MCPServer  # mcp 1.x
    mcp = MCPServer("payments")

    @mcp.tool()
    async def issue_refund(order_id: str, amount: float) -> str:
        """Refund an order. This is a write."""
        with COUNTER.open("a") as f:
            f.write(f"{order_id} {amount}\n")
        n = len(COUNTER.read_text().splitlines())
        if n == 1:
            await asyncio.sleep(3600)  # the refund happened; the reply never comes
        return f"Refund issued for order {order_id}: {amount} (refund #{n})"

    mcp.run()
    sys.exit()

from agents import Agent, Runner, set_tracing_disabled
from agents.mcp import MCPServerStdio
from agents.testing import ScriptedModel, assistant_message, function_call

set_tracing_disabled(True)

async def main(retries: int):
    model = ScriptedModel([
        [function_call("issue_refund", {"order_id": "42", "amount": 129.99}, call_id="call_1")],
        [assistant_message("Done.")],
    ])
    async with MCPServerStdio(
        params={"command": sys.executable, "args": [os.path.abspath(__file__), "server"],
                "env": {**os.environ, "COUNTER": str(COUNTER)}},
        client_session_timeout_seconds=1.5,
        max_retry_attempts=retries,
        retry_backoff_seconds_base=0.05,
    ) as mcp_server:
        agent = Agent(name="support", instructions="Help the customer.",
                      model=model, mcp_servers=[mcp_server])
        result = await Runner.run(agent, "Refund order 42 for 129.99")
        for item in result.new_items:
            if hasattr(item, "output"):
                print("model saw:", item.output)
    print("executed:", len(COUNTER.read_text().splitlines()))

COUNTER.write_text("")
asyncio.run(main(0 if "--no-retry" in sys.argv else 3))

The two patterns our suite recorded, each in 30 of 30 runs:

# retries on (max_retry_attempts=3), first reply lost
model saw: {'type': 'text', 'text': 'Refund issued for order 42: 129.99 (refund #2)'}
executed: 2

# retries off (default max_retry_attempts=0), first reply lost, openai-agents 0.26.2
# (on 0.24.0 the same message adds "Please try again.")
model saw: An error occurred while running the tool.
executed: 1

The model asked for the refund once. With retries on, it was written twice, and the model only heard about refund #2.

Results

30 runs per row, one pass, Dec 2, 2026, openai-agents 0.26.2, mcp 2.3.0, Python 3.13.5. Each cell is the number of runs, out of 30, with the outcome in the last column.

Scenario Result What the count means
retries_off 30/30 Default max_retry_attempts=0, first reply lost: refund executed 1 time; the model sees a tool error
retries_on_lost_reply 30/30 max_retry_attempts=3, first reply lost: refund executed 2 times; the model sees refund #2
control_retries_on_reply_arrives 30/30 max_retry_attempts=3, reply arrives: refund executed 1 time; the model sees refund #1
workaround_idempotency_key 30/30 The SDK still retries call_tool; the tool is keyed by order+amount, so the second call returns the first result and does not write again (executed 1 time, the model sees refund #1)
workaround_reconcile_before_retry 30/30 SDK retries off. After a lost reply, get_refund runs first; a refund is already on the ledger, so issue_refund is not sent again (executed 1 time)
trap_blind_retry_without_reconcile 30/30 Trap: the app re-sends issue_refund after a lost reply without checking the ledger, so the refund still runs twice. Here 30/30 means the double write happened every time

The same six rows were also 30/30 on openai-agents 0.24.0, with mcp 2.3.0 and the same suite. That includes the double write with retries on and both workarounds holding.

The fix: make the write safe to repeat, or check before you retry (no library change)

The SDK-side ideas are the reporter's, not ours. In the issue body they suggested, marked as not tested:

  1. Retry call_tool only when the tool's MCP annotations say idempotentHint: true or readOnlyHint: true, and keep retrying list_tools as today.
  2. Or a per-tool option (a list or a predicate), defaulting to read-only tools.
  3. At least document on max_retry_attempts that a non-idempotent tool may run more than once.

In a comment they offered to write a PR with a regression test if maintainers want it. In a second comment they pointed at prior art: according to the reporter, @mastra/mcp 2.12.0 calls tools/call again after a transport error only if the tool is marked readOnlyHint or idempotentHint, or if the error shows the request was never sent; otherwise it raises an "outcome unknown" error. The reporter says Mastra ran the refund once in every run with the same harness. We did not test Mastra or any of these SDK changes.

What we did test are two app-side patterns. Both held 30 of 30 on 0.26.2 and on 0.24.0.

1. Put an idempotency key on the write tool

Leave the SDK retry on if you want it. The SDK may still re-send call_tool, so make the tool itself return the first result on a repeat call instead of writing again. This is the shape of the idempotency_key mode in our suite:

_done: dict[str, str] = {}  # our suite used an in-process dict; use a durable table with a unique key

@mcp.tool()
async def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order. Safe to call again with the same key."""
    key = f"{order_id}:{amount}"  # or a business key, such as your refund request id
    if key in _done:
        return _done[key]          # repeat call: first result back, no second write
    result = write_refund(order_id, amount)
    _done[key] = result            # record it before the reply can be lost
    return result

In our suite the SDK re-sent call_tool, the second call found the key, and the refund was written once. The model saw refund #1, in 30 of 30 runs.

We keyed by order and amount because that is what the repro has. In a real app, an order plus amount can be a legitimate second refund, so prefer a business key, such as a refund request id from your own system. We did not test a durable store.

2. Reconcile before you retry

Leave max_retry_attempts at 0. After a lost reply, call a read tool first. If the write already happened, return that and do not re-send it. This is ReconcilingMCPServer from our suite:

from agents.mcp import MCPServerStdio

class ReconcilingMCPServer(MCPServerStdio):
    """max_retry_attempts stays 0. After a lost reply, check get_refund before
    sending issue_refund again."""

    async def call_tool(self, tool_name, arguments, meta=None):
        try:
            return await super().call_tool(tool_name, arguments, meta)
        except BaseException:
            if tool_name != "issue_refund":
                raise
            order_id = (arguments or {}).get("order_id")
            if not order_id:
                raise
            lookup = await super().call_tool("get_refund", {"order_id": order_id})
            if "already issued" in str(lookup):
                return lookup  # the write happened; do not send it again
            # Nothing on the ledger: one explicit retry of the write.
            return await super().call_tool(tool_name, arguments, meta)

The server needs a read tool for this. Ours was get_refund(order_id), which returns none or already issued N refund(s) for .... In 30 of 30 runs the refund was written once, and the model saw already issued 1 refund(s) for 42: 42 129.99 instead of a tool error.

This check relies on the read being up to date. If your ledger can lag behind the write, a "none" answer does not prove the write did not happen. We did not test a lagging ledger.

Want a starting point for keyed writes? The Idempotent approved side effects template is the closest tested starter, and the Side-effect ledger is a general record of side effects you can check before a write. Neither is an MCP retry harness. Browse the rest in the templates index.

Traps: fixes that look right but are not

What we didn't test

FAQ

What happens in the OpenAI Agents SDK if max_retry_attempts is set on an MCP server and the reply to a write tool is lost?

The SDK sends the same call_tool again, the write runs a second time, and the model is told only about the second result. On openai-agents 0.26.2 with MCPServerStdio and max_retry_attempts=3, an issue_refund tool that wrote the refund and then never answered the first call ran 2 times in 30 of 30 runs, and the model saw refund #2. With the default max_retry_attempts=0 it ran once and the model saw a tool error (30 of 30). When the reply arrived, retries did not add a second write (30 of 30).

Have the OpenAI Agents maintainers decided on this, and is it fixed in a release newer than 0.26.2?

No. Issue #6366 was opened Dec 2, 2026 and was still open on Dec 2, 2026, with no labels and 2 comments, both from the reporter. There is no maintainer reply and no fix PR. 0.26.2 is still the latest stable release, and the 0.26.1 and 0.26.2 changelogs do not mention this. In the source of the v1.0.0-alpha.3 pre-release, the same MCP retry helpers are still there with no idempotentHint or readOnlyHint check. We only read that source; we did not run the 30-run suite on the alpha.

Does this still happen in the latest openai-agents, and what about 0.24.0?

Yes, in our tests. openai-agents 0.26.2, uploaded to PyPI on Dec 1, 2026 UTC, is still the latest stable release. With mcp 2.3.0 and Python 3.13.5, the refund ran twice after a lost reply in 30 of 30 runs. On 0.24.0, the reporter's other version, the same six rows of our suite were also 30 of 30, including the double write. The reporter was on Python 3.14.4; we used 3.13.5.

How do I stop an MCP write tool from running twice when the OpenAI Agents SDK retries call_tool?

Two app-side patterns held 30 of 30 runs on 0.26.2 and on 0.24.0, with no library change. One: give the write tool an idempotency key (we keyed by order and amount; a business key such as a refund request id is better) and return the first result on a repeat call. The SDK still re-sent call_tool, but the refund ran once and the model saw refund #1. Two: leave max_retry_attempts at 0 and, after a lost reply, call a read tool such as get_refund first; if the refund is already on the ledger, return that and do not send issue_refund again. The refund ran once.

Why is turning retries off, or retrying blindly in my own code, not enough?

With max_retry_attempts=0 the refund ran once, but on 0.26.2 the model was told 'An error occurred while running the tool.' (on 0.24.0 the message adds 'Please try again.') even though the refund had gone through (30 of 30). So the caller still has to find out what happened. A blind retry in app code that re-sends issue_refund after a lost reply, without checking the ledger, wrote the refund twice in 30 of 30 runs, the same result as the SDK retry. A lost reply does not mean the tool did not run.

How is this different from the approved-tool-runs-again-after-crash guide, the idempotent approval template, and the MCP server explainer?

The approved-tool-runs-again-after-crash guide (/guides/openai-agents-approved-tool-runs-again-after-crash/) covers a tool that runs twice after an approval when a worker crashes mid-tool or the run is retried. That is a different path from MCP max_retry_attempts re-sending call_tool after a lost reply. The Idempotent approved side effects template (/templates/openai-agents-idempotent-approval/) is the tested starter for keyed writes after a duplicate resume or a retried run from an approval snapshot. It is not an MCP retry harness, but the same key-on-the-write idea is what held 30 of 30 here. The MCP server explainer (/guides/mcp-server-explained/) says what an MCP server is and does not measure this retry path.

Related

Templates: Idempotent approved side effects is the tested starter for keyed writes after a duplicate resume or a retried run (approval snapshot). It is the closest tested template. It is not an MCP retry harness, but the same key-on-the-write idea is what held 30/30 here. Side-effect ledger is a tested general ledger for side effects, useful if you keep your own record before a write; it is not MCP-specific. You can browse everything in the templates index.

Free starter pack

The approval-flow starter pack

Tested human-in-the-loop approval starters for LangGraph, OpenAI Agents SDK, Vercel AI SDK and Google ADK, plus the Agent Signal newsletter. Free.

Get the Agent Signal newsletter