Skip to content

[Bug] openai_agents: stateless_mcp_server() and stateful_mcp_server() can't require tool approval #219

Closed

Description

@campoy

Package: temporalio-openai-agents 1.1.0 and main (c664a34); also temporalio.contrib.openai_agents in temporalio 1.33.0 and 1.34.0.

What happens

The OpenAI Agents SDK lets a local MCP server require approval before a tool runs:
MCPServerStdio(..., require_approval="always") pauses the run with an interruption, and the
tool runs only after the call is approved.

Through the deprecated stateless_mcp_server() and stateful_mcp_server() there is no way to
get that pause:

  • The helpers take no require_approval option.
  • A require_approval set on the server that the StatelessMCPServerProvider or
    StatefulMCPServerProvider factory returns is ignored. The tool runs at once, the run completes,
    and nothing fails or warns.

temporal_mcp_server(name, require_approval=...) works, and the README says to set approval
there. But stateful_mcp_server() is still the only route with a persistent MCP session, and the
deprecated helpers are the only ones that run with MCP Python SDK v1. The README says they
"remain supported".

Cause: the agent reads the approval policy from the MCPServer it holds. In a Workflow that is
the plugin's reference (_StatelessMCPServerReference or _StatefulMCPServerReference), which
calls MCPServer.__init__() with no policy. The factory's server is only used inside the
list-tools and call-tool Activities, where its policy is never read.

Reproduction

One file, no network or API key: an in-process MCP server with one wire tool and a scripted
model that calls it. It runs the agent natively, then in Workflows on a local dev server started
by WorkflowEnvironment.start_local(). It exits 1 while either helper lacks the option.

"""stateless_mcp_server() and stateful_mcp_server() cannot require tool approval.

python issue_repro.py    (starts a local Temporal dev server; no API key needed)

An MCP server whose require_approval="always" pauses a native run before its tool
runs. temporal_mcp_server(require_approval=...) does the same in a Workflow. The
deprecated helpers have no such option, and the policy set on the factory's
server is ignored, so the tool runs with no approval. Exits 1 while either helper
lacks the option.
"""

import asyncio
import inspect
import json
import sys
import uuid
from datetime import timedelta
from typing import Any

from temporalio import workflow
from temporalio.client import Client
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

with workflow.unsafe.imports_passed_through():
    from agents import Agent, AgentBase, Model, RunConfig, RunContextWrapper, Runner
    from agents.mcp import MCPServer
    from mcp import GetPromptResult, ListPromptsResult
    from mcp import Tool as MCPTool
    from mcp.types import CallToolResult, TextContent
    from temporalio.openai_agents import (
        OpenAIAgentsPlugin,
        StatefulMCPServerProvider,
        StatelessMCPServerProvider,
    )
    from temporalio.openai_agents.testing import ResponseBuilders, TestModelProvider
    from temporalio.openai_agents.workflow import (
        stateful_mcp_server,
        stateless_mcp_server,
        temporal_mcp_server,
    )

WIRES: list[str] = []  # one entry per call of the MCP tool


class BankServer(MCPServer):
    """An in-process MCP server with one tool, `wire`."""

    def __init__(self, name: str, **options: Any) -> None:
        self._name = name
        super().__init__(**options)

    @property
    def name(self) -> str:
        return self._name

    async def connect(self) -> None:
        pass

    async def cleanup(self) -> None:
        pass

    async def list_tools(self, run_context: RunContextWrapper[Any] | None = None,
                         agent: AgentBase | None = None) -> list[MCPTool]:
        return [MCPTool.model_validate({"name": "wire", "inputSchema": {
            "type": "object", "properties": {"amount": {"type": "integer"}}, "required": ["amount"]}})]

    async def call_tool(self, tool_name: str, arguments: dict[str, Any] | None,
                        meta: dict[str, Any] | None = None) -> CallToolResult:
        WIRES.append(json.dumps(arguments))
        return CallToolResult(content=[TextContent(type="text", text="wired")])

    async def list_prompts(self) -> ListPromptsResult:
        raise NotImplementedError

    async def get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult:
        raise NotImplementedError


class WireModel(Model):
    """Calls `wire` until it sees the tool's output, then answers."""

    async def get_response(self, system_instructions, input, model_settings, tools, *args, **kwargs):
        items = [] if isinstance(input, str) else input
        if any(isinstance(i, dict) and i.get("type") == "function_call_output" for i in items):
            return ResponseBuilders.output_message("done")
        return ResponseBuilders.tool_call('{"amount": 5}', "wire")

    def stream_response(self, *args, **kwargs):
        raise NotImplementedError


@workflow.defn
class WireWorkflow:
    @workflow.run
    async def run(self, case: str) -> list[str]:
        approval: dict[str, Any] = {"require_approval": "always"}
        if case == "temporal_mcp_server(require_approval=)":
            server = temporal_mcp_server("bank", **approval)
        elif case == "stateless_mcp_server(), policy on factory":
            server = stateless_mcp_server("bank-policy")
        elif case == "stateless_mcp_server(require_approval=)":
            server = stateless_mcp_server("bank", **approval)
        else:
            async with stateful_mcp_server(
                "bank-policy" if case == "stateful_mcp_server(), policy on factory" else "bank",
                **({} if "policy on factory" in case else approval),
            ) as stateful:
                result = await Runner.run(Agent(name="bank", mcp_servers=[stateful]), "Wire 5.")
            return [i.tool_name or "" for i in result.interruptions]
        result = await Runner.run(Agent(name="bank", mcp_servers=[server]), "Wire 5.")
        return [i.tool_name or "" for i in result.interruptions]


async def main() -> int:
    server = BankServer("bank", require_approval="always")
    result = await Runner.run(Agent(name="bank", mcp_servers=[server]), "Wire 5.",
                              run_config=RunConfig(model_provider=TestModelProvider(WireModel())))
    print(f"{'native MCPServer(require_approval=)':45} interruptions={[i.tool_name for i in result.interruptions]} "
          f"wire_calls={len(WIRES)}")

    plugin = OpenAIAgentsPlugin(
        model_provider=TestModelProvider(WireModel()),
        mcp_servers={"bank": lambda: BankServer("bank")},
        mcp_server_providers=[
            StatelessMCPServerProvider("bank", lambda: BankServer("bank")),
            StatelessMCPServerProvider("bank-policy", lambda: BankServer("bank-policy", require_approval="always")),
            StatefulMCPServerProvider("bank", lambda _: BankServer("bank")),
            StatefulMCPServerProvider("bank-policy",
                                      lambda _: BankServer("bank-policy", require_approval="always")),
        ],
    )
    missing = [f.__name__ for f in (stateless_mcp_server, stateful_mcp_server)
               if "require_approval" not in inspect.signature(f).parameters]
    async with await WorkflowEnvironment.start_local() as env:
        client = Client(**{**env.client.config(), "plugins": [plugin]})
        async with Worker(client, task_queue="bank", workflows=[WireWorkflow]):
            for case in ("temporal_mcp_server(require_approval=)",
                         "stateless_mcp_server(), policy on factory",
                         "stateful_mcp_server(), policy on factory",
                         "stateless_mcp_server(require_approval=)",
                         "stateful_mcp_server(require_approval=)"):
                if case.split("(")[0] in missing and "require_approval=" in case:
                    print(f"{case:45} not possible: {case.split('(')[0]}() has no require_approval option")
                    continue
                before = len(WIRES)
                interruptions = await client.execute_workflow(
                    WireWorkflow.run, case, id=f"wire-{uuid.uuid4()}", task_queue="bank",
                    execution_timeout=timedelta(seconds=30))
                print(f"{case:45} interruptions={interruptions} wire_calls={len(WIRES) - before}")
    return 1 if missing else 0


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))

Output with temporalio-openai-agents 1.1.0 (temporalio 1.34.0, openai-agents 0.22.3,
mcp 2.3.0, Python 3.13.16); main at c664a34 gives the same lines:

native MCPServer(require_approval=)           interruptions=['wire'] wire_calls=0
temporal_mcp_server(require_approval=)        interruptions=['wire'] wire_calls=0
stateless_mcp_server(), policy on factory     interruptions=[] wire_calls=1
stateful_mcp_server(), policy on factory      interruptions=[] wire_calls=1
stateless_mcp_server(require_approval=)       not possible: stateless_mcp_server() has no require_approval option
stateful_mcp_server(require_approval=)        not possible: stateful_mcp_server() has no require_approval option
exit=1

The first two lines are the controls: the native run and temporal_mcp_server() pause before
the tool runs. The same happens with MCPServerStdio over a real stdio server, and with
mcp 1.x for the deprecated helpers.

Expected

A way to require approval on the deprecated helpers' tools, as on temporal_mcp_server().

Impact

An MCP tool the caller meant to gate behind a person's approval, such as a payment or a delete,
runs without one, and the run looks normal.

Proposed fix

Add require_approval to stateless_mcp_server() and stateful_mcp_server() and pass it to the
reference's MCPServer.__init__(), as temporal_mcp_server() does with its server options.
Callers that don't pass it are unchanged, so recorded histories replay as before.

A tool_meta_resolver set on the factory's server is ignored the same way, but assigning one to
the returned reference's public tool_meta_resolver attribute already works, so it needs no new
option.

A PR follows.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions