Skip to content

disallow_transfer_to_peers=True can be bypassed #3850

Closed

Description

@AriYusa

When using LlmAgent with disallow_transfer_to_peers=True, sub-agents are still able to transfer tasks directly to sibling agents using transfer_to_agent, even though such transfers should be disallowed.

The disallow_transfer_to_peers=True flag only influences the prompt given to the agent. But in the deafult mode each sub-agent has access to the full conversation history, including all previous transfers and agent names mentioned. So a sub-agent can still infer the names of sibling agents from the history and explicitly call transfer_to_agent with a sibling's name, bypassing the intended restriction. Since a sibling's name exists in the agent tree no error is raised.

To Reproduce

git clone https://github.com/google/adk-python.git
cd adk-python
uv sync --all-extras
from __future__ import annotations

from unittest.mock import AsyncMock

from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.genai import types  
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService


def create_mock_llm_with_transfer(agent_name: str) -> BaseLlm:
  """Create a mock LLM that returns a transfer_to_agent call."""
  mock_llm = AsyncMock(spec=BaseLlm)
  mock_llm.model = 'mock-model'
  
  # This simulates an LLM that has inferred sibling names from history
  async def mock_generate(*args, **kwargs):
    yield LlmResponse(
        content=types.Content(
            role='model',
            parts=[
                types.Part.from_function_call(
                    name='transfer_to_agent',
                    args={'agent_name': agent_name}
                )
            ],
        ),
        usage_metadata=None,
    )
  
  mock_llm.generate_content_async.side_effect = mock_generate
  
  return mock_llm


async def test_disallow_transfer_to_peers_bypass():
  """Test that demonstrates the bug.
  
  Expected: sub_agent_1 cannot transfer to sub_agent_2 (sibling)
  Actual: sub_agent_1 can transfer to sub_agent_2 by calling transfer_to_agent
  """
  
  # Create mock LLMs
  # root_agent's LLM transfers to sub_agent_1
  root_mock_llm = create_mock_llm_with_transfer('sub_agent_1')
  
  # sub_agent_1's LLM transfers to sub_agent_2 (its sibling) - THIS SHOULD FAIL
  sub_agent_1_mock_llm = create_mock_llm_with_transfer('sub_agent_2')
  
  # sub_agent_2 just responds normally
  sub_agent_2_mock_llm = AsyncMock(spec=BaseLlm)
  sub_agent_2_mock_llm.model = 'mock-model'

  async def mock_sub_agent_2_generate(*args, **kwargs):
    yield LlmResponse(
        content=types.Content(
            role='model',
            parts=[types.Part(text='Hello from sub_agent_2')],
        ),
        usage_metadata=None,
    )
  sub_agent_2_mock_llm.generate_content_async.side_effect = mock_sub_agent_2_generate
  
  # root_agent
  #   ├── sub_agent_1 (disallow_transfer_to_peers=True)
  #   └── sub_agent_2 (disallow_transfer_to_peers=True)
  
  sub_agent_1 = Agent(
      name='sub_agent_1',
      model=sub_agent_1_mock_llm,
      description='Sub agent 1',
      disallow_transfer_to_peers=True,  # Should prevent transfer to sub_agent_2
  )
  
  sub_agent_2 = Agent(
      name='sub_agent_2',
      model=sub_agent_2_mock_llm,
      description='Sub agent 2',
      disallow_transfer_to_peers=True,  # Should prevent transfer to sub_agent_1
  )
  
  root_agent = Agent(
      name='root_agent',
      model=root_mock_llm,
      sub_agents=[sub_agent_1, sub_agent_2],
  )
  
  app = App(name='test_app', root_agent=root_agent)
  
  session_service = InMemorySessionService()
  
  runner = Runner(
      app=app,
      session_service=session_service,
      artifact_service=InMemoryArtifactService(),
      memory_service=InMemoryMemoryService(),
  )
  
  # Create session
  session = await session_service.create_session(
      app_name='test_app',
      user_id='test_user'
  )
  
  events = []
  async for event in runner.run_async(
      user_id=session.user_id,
      session_id=session.id,
      new_message=types.Content(
          role='user',
          parts=[types.Part.from_text(text='test')]
      )
  ):
    events.append(event)
  
  for i, event in enumerate(events):
    print(f"Event {i + 1}:")
    print(f"  Author: {event.author}")
    print(f"  Content: {event.content}")
    if event.actions and event.actions.transfer_to_agent:
      print(f"  Transfer to: {event.actions.transfer_to_agent}")
    print()
  
  # Check if transfer to sibling happened
  transfer_to_sibling_events = [
      e for e in events 
      if e.actions and e.actions.transfer_to_agent == 'sub_agent_2'
      and e.author == 'sub_agent_1'
  ]
  
  assert not transfer_to_sibling_events, "BUG: Transfer to sibling agent should be disallowed but occurred."


if __name__ == '__main__':
  import asyncio
  
  asyncio.run(test_disallow_transfer_to_peers_bypass())

Expected behavior
When disallow_transfer_to_peers=True is set on a sub-agent, the agent should not be able to transfer to sibling agents. The restriction should be enforced at runtime, not just in the prompt/enum constraint

There are a few alternatives of handling:

  • An error is raised when attempting to transfer to a disallowed agent (the same now happens if agent tries to transfer to non-existing agent)
  • No error is raised, the transfer target is explicitly changed from peer agent to parent agent

Desktop

  • OS: Windows 11 (WSL Ubuntu)
  • Python version: Python 3.11.10
  • ADK version: 1.20.0

Activity

  1. added
    a2a[Component] This issue is related a2a support inside ADK.
    on Dec 6, 2025
  2. added theissue type on Dec 6, 2025
  3. self-assigned this
    on Dec 11, 2025
  4. rohityan commented on Dec 11, 2025

    @rohityan
    Collaborator

    Hi @AriYusa , thank you for providing the detailed, reproducible test case.
    The disallow_transfer_to_peers=True flag affects more than just the instruction prompt; it also enforces constraints at the tool definition (schema) level.
    As your test case demonstrated, this schema-level defense can be bypassed. A mock LLM or a non-compliant model can inject a FunctionCall directly into the system. The core issue is that the ADK lacks a secondary, runtime-level check to validate that the calling agent has permission to transfer to the target agent.

  5. rohityan commented on Dec 11, 2025

    @rohityan
    Collaborator

    Hi @seanzhougoogle , can you please look into this. I have reproduced it and can confirm the bug.
    An agent with disallow_transfer_to_peers=True should never be able to transfer to its sibling. I suspect the ADK runtime is not enforcing this rule.

  6. added
    needs review[Status] The PR/issue is awaiting review from the maintainer
    on Dec 11, 2025
  7. adk-bot commented on Dec 18, 2025

    @adk-bot
    Collaborator

    This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.

  8. added
    stale[Status] Issues which have been marked inactive since there is no user response
    request clarification[Status] The maintainer need clarification or more information from the author
    on Dec 18, 2025
  9. AriYusa commented on Dec 25, 2025

    @AriYusa
    ContributorAuthor

    Hi, @ryanaiagent, @seanzhougoogle! Any updates on it? The PR was updated

  10. removed
    stale[Status] Issues which have been marked inactive since there is no user response
    on Dec 26, 2025
  11. added
    core[Component] This issue is related to the core interface and implementation
    and removed
    a2a[Component] This issue is related a2a support inside ADK.
    on Feb 13, 2026
  12. self-assigned this
    on Feb 13, 2026
  13. added a commit that references this issue on Jun 18, 2026
    fa18d26
  14. added a commit that references this issue on Aug 11, 2026
    9007631
  15. rafaelasor commented on Aug 26, 2026

    @rafaelasor

    Thanks for the fix in fa18d26 — _get_agent_to_run now raises on a disallowed sibling transfer on the flows/llm_flows
    path. On 2.7.1 the 2.x workflow path still lets it through, because workflow/utils/_transfer_utils.py
    (resolve_and_derive_transfer_context, "Case 3: SIBLING") resolves the target without reading
    disallow_transfer_to_peers. Minimal repro (scripted model, no API key):

    import asyncio
    from google.adk.agents.llm_agent import LlmAgent
    from google.adk.apps.app import App
    from google.adk.runners import Runner
    from google.adk.sessions.in_memory_session_service import InMemorySessionService
    from google.adk.models.base_llm import BaseLlm
    from google.adk.models.llm_response import LlmResponse
    from google.genai import types
    
    class Scripted(BaseLlm):
        model: str = "scripted"
        script: dict = {}
        async def generate_content_async(self, req, stream=False):
            agent = (req.config.labels or {}).get("adk_agent_name") if req.config else None
            q = self.script.get(agent) or []
            part = q.pop(0) if q else types.Part.from_text(text="done")
            yield LlmResponse(content=types.Content(role="model", parts=[part]))
    
    fc = lambda name, **a: types.Part.from_function_call(name=name, args=a)
    ran = []
    def export(destination: str) -> dict:
        ran.append(destination); return {"ok": True}
    
    model = Scripted(script={"root": [fc("transfer_to_agent", agent_name="analyst")],
                             "analyst": [fc("transfer_to_agent", agent_name="exporter")],   # peer, though disallowed
                             "exporter": [fc("export", destination="x")]})
    analyst = LlmAgent(name="analyst", model=model, description="a", disallow_transfer_to_peers=True)
    exporter = LlmAgent(name="exporter", model=model, description="e", tools=[export])
    root = LlmAgent(name="root", model=model, description="r", sub_agents=[analyst, exporter])
    
    async def main():
        s = InMemorySessionService(); app = App(name="repro", root_agent=root)
        sess = await s.create_session(app_name="repro", user_id="u")
        events = [e async for e in Runner(app=app, session_service=s).run_async(
            user_id="u", session_id=sess.id, new_message=types.Content(role="user", parts=[types.Part.from_text(text="go")]))]
        print("transferred to peer:", any(e.actions.transfer_to_agent == "exporter" for e in events), "| export ran:", ran)
    asyncio.run(main())

    Observed on google-adk==2.7.1: transferred to peer: True | export ran: ['x']. Expected: the same ValueError the
    llm_flows path raises. A check equivalent to _get_agent_to_run's at the sibling case in
    resolve_and_derive_transfer_context would close the gap on this path; happy to send a PR if that shape is right.

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

Metadata

Metadata

Labels

core[Component] This issue is related to the core interface and implementationneeds review[Status] The PR/issue is awaiting review from the maintainerrequest clarification[Status] The maintainer need clarification or more information from the author

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions