Skip to content

[Bug] openai_agents: a require_approval policy on the MCP factory's server is silently ignored #274

Closed

Description

@campoy

Package: temporalio-openai-agents 1.1.0 and main (69db660, with #220).

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 plugin, the policy works only when Workflow code sets it: on
temporal_mcp_server(require_approval=...), or, since #220, on stateless_mcp_server() and
stateful_mcp_server(). A require_approval set on the server that the Worker's factory returns
is ignored on all three routes. The tool runs at once, the run completes, and nothing fails or
warns.

The README says to set approval on temporal_mcp_server(), but a policy left on the factory's
server still looks like it works. That is easy to hit when one factory also serves code outside
Temporal, or when code moves from the native SDK to the plugin. The plugin already rejects a
callable tool_filter on the factory's server with a non-retryable error that points to
temporal_mcp_server(). A require_approval there gets no such check.

Cause: the agent reads the approval policy from the MCPServer it holds. In a Workflow that is
the plugin's Workflow-side server. The factory's server is used only inside the MCP 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 a policy on the factory's server lets the
tool run.

"""A require_approval policy on the factory's MCP server is silently ignored.

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. Set on the server that the Worker's factory returns, the policy is
ignored on all three routes: the tool runs with no approval, and nothing fails
or warns. Exits 1 while a policy on the factory's server lets the tool run.
"""

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

from temporalio import workflow
from temporalio.client import Client, WorkflowFailureError
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]:
        if case == "temporal_mcp_server(require_approval=)":
            server = temporal_mcp_server("bank", require_approval="always")
        elif case == "temporal_mcp_server(), policy on factory":
            server = temporal_mcp_server("bank-policy")
        elif case == "stateless_mcp_server(), policy on factory":
            server = stateless_mcp_server("bank-policy")
        else:
            async with stateful_mcp_server("bank-policy") 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]


def policy_server(name: str) -> BankServer:
    return BankServer(name, require_approval="always")


async def main() -> int:
    server = policy_server("bank")
    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"), "bank-policy": lambda: policy_server("bank-policy")},
        mcp_server_providers=[
            StatelessMCPServerProvider("bank-policy", lambda: policy_server("bank-policy")),
            StatefulMCPServerProvider("bank-policy", lambda _: policy_server("bank-policy")),
        ],
    )
    unapproved = 0
    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=)",
                         "temporal_mcp_server(), policy on factory",
                         "stateless_mcp_server(), policy on factory",
                         "stateful_mcp_server(), policy on factory"):
                before = len(WIRES)
                try:
                    interruptions = await client.execute_workflow(
                        WireWorkflow.run, case, id=f"wire-{uuid.uuid4()}", task_queue="bank",
                        execution_timeout=timedelta(seconds=60))
                    outcome = f"interruptions={interruptions}"
                except WorkflowFailureError as err:
                    cause: BaseException = err
                    while getattr(cause, "cause", None) is not None:
                        cause = cause.cause  # type: ignore[attr-defined]
                    outcome = f"failed: {cause}"
                calls = len(WIRES) - before
                if "policy on factory" in case and calls:
                    unapproved += 1
                print(f"{case:45} {outcome} wire_calls={calls}")
    return 1 if unapproved else 0


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

Output on main at 69db660 (temporalio 1.34.0, openai-agents 0.22.0, mcp 2.2.0,
Python 3.13.16); temporalio-openai-agents 1.1.0 (temporalio 1.35.0, openai-agents 0.22.3,
mcp 2.3.0) gives the same lines:

native MCPServer(require_approval=)           interruptions=['wire'] wire_calls=0
temporal_mcp_server(require_approval=)        interruptions=['wire'] wire_calls=0
temporal_mcp_server(), policy on factory      interruptions=[] wire_calls=1
stateless_mcp_server(), policy on factory     interruptions=[] wire_calls=1
stateful_mcp_server(), policy on factory      interruptions=[] wire_calls=1
exit=1

The first two lines are the controls: the native run and temporal_mcp_server(require_approval=...)
pause before the tool runs. The last three set the same policy on the factory's server, and the
tool runs with no approval.

Expected

A run should not call a tool that its configuration says needs approval. If the plugin cannot use
the factory's policy, it should reject it, as it rejects a callable tool_filter there.

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

Reject a require_approval policy on the factory's server where the plugin creates that server,
on all three routes, with the same kind of non-retryable error as the tool_filter check. The
message says to pass the policy to temporal_mcp_server(), or to the deprecated helpers' option.
A policy that never asks for approval, such as "never", has the same effect as no policy, so it
can stay.

Using the factory's policy instead would mean sending it to the Workflow, and a callable policy
cannot be sent there.

Runs that complete today with such a policy would fail, so this is a breaking change. A PR
follows.

A tool_meta_resolver set on the factory's server is ignored the same way. It is left out here:
setting one on the Workflow side already works.

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