Skip to content

Implement A2A protocol support for recursive agent invocation #2901

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

devin-ai-integration[bot]
Copy link
Contributor

Implement A2A protocol support for recursive agent invocation

Description

This PR implements full A2A (Agent-to-Agent) protocol support in CrewAI by enabling recursive agent invocation. Previously, when an agent was invoked by another agent through delegation tools, the invoked agent couldn't recursively invoke other agents because tools weren't preserved during the delegation process.

Changes

  • Modified BaseAgentTool._execute to accept and pass tools parameter
  • Updated DelegateWorkTool and AskQuestionTool to pass agent tools
  • Modified AgentTools to inject tools into delegation tools
  • Added test cases to verify recursive agent invocation works

Testing

  • Added unit tests that verify tools are properly passed between agents
  • Verified all existing tests pass with the new implementation
  • Tested that tools are correctly injected into delegation tools

Related Issues

Fixes #2900

Link to Devin run

https://app.devin.ai/sessions/3259726787a8459cb24632ab74e549e9

Requested by

Joe Moura (joao@crewai.com)

- Modified BaseAgentTool._execute to accept and pass tools parameter
- Updated DelegateWorkTool and AskQuestionTool to pass agent tools
- Modified AgentTools to inject tools into delegation tools
- Added test cases to verify recursive agent invocation works

Fixes #2900

Co-Authored-By: Joe Moura <joao@crewai.com>
Copy link
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@joaomdmoura
Copy link
Collaborator

Disclaimer: This review was made by a crew of AI Agents.

Code Review Comment: A2A Protocol Implementation

Overview

The implementation of the Agent-to-Agent (A2A) protocol enhances recursive agent invocation by modifying the tool execution chain. This adjustment promotes better flexibility in agent communication and delegation. Overall, the changes reflect an understanding of the core principles of tool management within an agent framework.

Strengths

  • The separation of concerns is effectively achieved in the agent_tools.py through methods like _get_all_agent_tools(), which enhances readability.
  • The test cases provide good coverage and demonstrate a clear understanding of how tools need to be passed correctly in the agent invocation process.

Areas for Improvement

1. Type Hinting

Explicitly identify types for the _agent_tools attribute:

delegate_tool._agent_tools: List[BaseTool] = self._get_all_agent_tools()

Adding type hints not only improves readability but also helps in maintaining type checks across the implementation.

2. Deduplication Logic

The _get_all_agent_tools() function currently allows duplicate tools. Implement a deduplication mechanism to ensure unique tools are retrieved:

seen_tools = set()
unique_tools = []
for agent in self.agents:
    if agent.tools:
        for tool in agent.tools:
            tool_id = id(tool)
            if tool_id not in seen_tools:
                seen_tools.add(tool_id)
                unique_tools.append(tool)

3. Consistent Tool Retrieval

Standardize the retrieval of tools across different modules (e.g., ask_question_tool.py and delegate_work_tool.py) with a helper function:

def _get_tools(self, **kwargs) -> Optional[List[BaseTool]]:
    """Get tools from instance or kwargs."""
    return getattr(self, '_agent_tools', None) or kwargs.get('tools')

4. Validation Checks

Enhance the code by including validation for the tools parameter to prevent invalid tool inputs:

if tools is not None and not all(isinstance(tool, BaseTool) for tool in tools):
    raise ValueError("All tools must inherit from BaseTool")

5. Logging Enhancements

Add logging to observe the execution of tasks with tools, which will aid in debugging and monitoring tool usage:

logger.debug(f"Executing task with {len(tools) if tools else 0} tools")

6. Test Enhancements

  • Tool Deduplication Test: Ensure that your tests include scenarios where duplicate tools are present to validate the deduplication logic.
  • Invalid Tool Cases: Write tests to check that the system raises errors when invalid tools are passed to methods like _execute.

General Recommendations

  1. Documentation: Enhance code documentation to explain the A2A protocol in detail, including how tool inheritance functions.
  2. Error Handling: Implement robust error handling for scenarios involving recursive tool invocation.
  3. Performance Optimizations: Consider caching the tools list when the agent and tools remain unchanged to improve performance.
  4. Integration Testing: Incorporate integration tests that simulate deep recursion cases to ensure stability.
  5. Type Safety: Thoroughly review the entire implementation for comprehensive type hinting.

Security Considerations

  • To prevent infinite recursion during tool delegation, implement safeguards that check and limit the depth of recursion.
  • Add mechanisms to manage permissions on tool execution to prevent unauthorized access between agents.

In summary, the implementation is sound with solid foundations. However, the suggested improvements will contribute significantly to code quality, maintainability, and robustness. Addressing these will lead to a more reliable system capable of handling the complexities of the Agent-to-Agent protocol.

devin-ai-integration bot and others added 8 commits May 25, 2025 04:20
- Remove unused imports and variables in test files
- Replace bare except with specific exception in structured_output_converter.py
- Fix None comparison in llm_test.py
- Update agent.execute_task to accept recursion_depth parameter

Resolves all remaining lint issues for A2A protocol implementation.

Co-Authored-By: Joe Moura <joao@crewai.com>
…ariables

Co-Authored-By: Joe Moura <joao@crewai.com>
- Add tool deduplication logic in agent_tools.py
- Re-implement recursion depth limits and validation in base_agent_tools.py
- Add proper type hinting for _agent_tools attributes
- Add consistent tool retrieval method across delegation tools
- Enhance logging for debugging recursive agent invocations

Addresses all remaining PR review comments for full A2A protocol support.

Co-Authored-By: Joe Moura <joao@crewai.com>
Co-Authored-By: Joe Moura <joao@crewai.com>
- Update BaseAgent.execute_task signature to include recursion_depth parameter
- Fix variable reference in base_agent_tools.py (agent -> matching_agents)
- Remove type annotations in assignment to non-self attributes in agent_tools.py

Co-Authored-By: Joe Moura <joao@crewai.com>
Co-Authored-By: Joe Moura <joao@crewai.com>
Co-Authored-By: Joe Moura <joao@crewai.com>
- Remove race condition in FilteredStream.write() method
- Remove class-level _lock = None that caused threading issues
- Ensures proper lock initialization in __init__ only

Fixes Python 3.10 CI test failures with exit code 139

Co-Authored-By: Joe Moura <joao@crewai.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[FEATURE] Complete Support for A2A protocols
1 participant