mcp-agents-framework
Language:
Python
Stars:
0
Forks:
0
MCP-Agents Framework: Detailed Instructions
Introduction
The MCP-Agents Framework is a lightweight implementation designed to demonstrate how to build AI agent systems based on Anthropic's Model Context Protocol (MCP). This framework illustrates the key architectural concepts of MCP and provides a simplified implementation for educational purposes.
This document provides detailed instructions on how to use, customize, and extend the framework for your own AI agent applications.
Installation and Setup
Prerequisites
- Python 3.7 or higher
- asyncio knowledge (framework uses async/await patterns)
- Basic understanding of AI agents and the Model Context Protocol
Installation
- Clone the repository:
git clone https://github.com/stagsz/mcp-agents-framework.git
cd mcp-agents-framework
- Set up a virtual environment (optional but recommended):
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies (if any are added in the future):
pip install -r requirements.txt # Note: currently no external dependencies
Framework Components
The MCP-Agents Framework consists of two main components:
- MCPAgent: Represents an individual specialized agent with a specific role and capabilities
- MCPOrchestrator: Manages multiple agents and coordinates their execution for complex tasks
Additionally, the framework includes simulated connections to MCP servers which provide tools and capabilities to the agents.
Creating Specialized Agents
Each agent in the framework is designed for a specific role, such as research, fact-checking, or report writing. To create a new agent:
from mcp_agent_framework import MCPAgent
my_agent = MCPAgent(
name="my_specialized_agent", # Unique identifier
role="Expert in data analysis", # Agent's specialization
system_message="You are an expert at analyzing and interpreting complex datasets.", # Instructions
mcp_servers=["data_tools", "file_system"] # Required MCP servers
)
Agent Parameters Explained
- name: A unique identifier for the agent (used by the orchestrator)
- role: Description of the agent's specialization (affects automatic planning)
- system_message: Detailed instructions for the agent's behavior (would be passed to an LLM in a real implementation)
- mcp_servers: List of MCP server names this agent needs to connect to
Design Principles for Effective Agents
- Specialization: Each agent should have a clear, focused role
- Independence: Agents should be able to execute their part of a task without requiring continuous guidance
- Clear Instructions: The system_message should provide comprehensive guidance on how the agent should behave
- Minimal Capability Set: Only request connections to MCP servers the agent actually needs
Setting up the Orchestrator
The orchestrator manages multiple agents and coordinates their execution. To create an orchestrator:
from mcp_agent_framework import MCPOrchestrator
orchestrator = MCPOrchestrator(
name="my_orchestrator",
system_message="Coordinate multiple agents to accomplish complex data analysis tasks."
)
# Register agents with the orchestrator
orchestrator.register_agent(data_analysis_agent)
orchestrator.register_agent(visualization_agent)
orchestrator.register_agent(report_agent)
Orchestrator Strategy
The orchestrator can determine the optimal agent sequence automatically based on the task and available agents, or you can specify the sequence explicitly:
# Let the orchestrator determine the agent sequence
result = await orchestrator.execute_task(
task="Analyze the Q1 sales data and create a comprehensive report with visualizations.",
context={"data_path": "data/q1_sales.csv", "output_path": "reports/q1_analysis.md"}
)
# Specify the agent sequence explicitly
result = await orchestrator.execute_task(
task="Analyze the Q1 sales data and create a comprehensive report with visualizations.",
agent_sequence=["data_analysis_agent", "visualization_agent", "report_agent"],
context={"data_path": "data/q1_sales.csv", "output_path": "reports/q1_analysis.md"}
)
Defining Tasks and Execution Plans
Each agent automatically creates an execution plan based on its role and the available tools. The planning logic in _create_plan()
method uses simple heuristics in this implementation, but in a production system, this would likely involve an LLM call.
The default plans are:
- For research agents: Search for information → Extract and synthesize findings
- For fact-checking agents: Review findings → Verify against trusted sources → Document verification
- For report/writing agents: Read research → Read fact-checking → Generate report
- For other agents: Analyze requirements → Search for information → Document results
You can customize the planning logic by subclassing MCPAgent
and overriding the _create_plan()
method:
class CustomAgent(MCPAgent):
async def _create_plan(self, task, servers, context):
# Custom planning logic here
return [
{"step": 1, "action": "Custom step 1", "tool": "custom_tool", "server": "server_name"},
{"step": 2, "action": "Custom step 2", "internal": True},
# More steps...
]
Running the Framework
The framework uses asyncio, so you need to run it within an async context:
import asyncio
from mcp_agent_framework import MCPAgent, MCPOrchestrator
async def main():
# Create agents
agent1 = MCPAgent(...)
agent2 = MCPAgent(...)
# Create orchestrator
orchestrator = MCPOrchestrator(...)
orchestrator.register_agent(agent1)
orchestrator.register_agent(agent2)
# Execute task
result = await orchestrator.execute_task(
task="Your task description here",
context={"key": "value"}
)
print(result)
# Run the async function
if __name__ == "__main__":
asyncio.run(main())
See example_task.py
for a complete example of how to set up and run a multi-agent task.
Customization and Extension
Adding New MCP Servers
In this implementation, MCP servers are simulated. To add a new server type, modify the _get_server_tools()
method in the MCPAgent
class:
def _get_server_tools(self, server_name):
tools_map = {
# Existing servers...
"my_new_server": [
{"name": "new_tool_1", "description": "Description of new tool 1"},
{"name": "new_tool_2", "description": "Description of new tool 2"},
]
}
return tools_map.get(server_name, [])
Implementing Actual Tool Execution
To replace the simulated tool execution with actual implementation, modify the _simulate_tool_execution()
method:
async def _simulate_tool_execution(self, server_name, tool_name, step, context):
# Real implementation would call the actual MCP server
if server_name == "my_server" and tool_name == "my_tool":
# Actual tool implementation
result = await actual_tool_function(context)
return {"status": "completed", "output": result}
# Fall back to simulation for other tools
# ...
Connecting to Real MCP Servers
In a production implementation, you would replace the simulated server connections with actual MCP client SDK calls. This would involve modifying the _connect_to_servers()
method to establish real connections.
Best Practices and Tips
-
Agent Specialization: Design agents with clear, focused roles rather than creating general-purpose agents
2. **Context Passing**: Use the context dictionary to pass information between agents in the sequence
-
Error Handling: In a production implementation, add proper error handling for each step
-
System Messages: Write detailed system messages that clearly define each agent's role and responsibilities
-
Task Decomposition: Break complex tasks into subtasks that can be handled by specialized agents
-
Testing: Test each agent individually before combining them in an orchestrator
-
Logging: Add detailed logging to track the execution flow and debug issues
Troubleshooting
Common Issues
-
Agent Cannot Find Tools: Check that the correct MCP servers are specified in the agent's initialization
-
Orchestrator Cannot Find Agent: Ensure the agent is registered with the orchestrator before executing tasks
-
Execution Plan Issues: If using a custom agent, make sure the execution plan format matches what the framework expects
-
Asyncio Errors: The framework uses asyncio, so make sure all async functions are properly awaited
Extending the Framework for Production
To adapt this framework for production use, consider these extensions:
-
Real MCP Client Integration: Replace the simulated servers with connections to actual MCP servers
-
LLM Integration: Add actual LLM calls for task planning and execution
-
Persistent Memory: Implement persistent storage for agent memory and task history
-
Error Recovery: Add mechanisms for handling failures and retrying steps
-
Monitoring and Observability: Add telemetry to track agent performance and behavior
-
Security Controls: Implement proper authentication and access controls for MCP server connections
-
Resource Management: Add controls for managing computational and token budget resources
Conclusion
The MCP-Agents Framework provides a conceptual foundation for building AI agent systems based on the Model Context Protocol. While this implementation is simplified for educational purposes, it demonstrates the key architectural patterns that would be used in a production system.
By understanding these concepts and extending the framework with real implementations, you can build powerful AI agent systems that leverage the full capabilities of the Model Context Protocol.