Skip to content

Commit 08f1487

Browse files
committed
feat: Complete MCP v2.0 rewrite with real-world examples and enterprise support
- Rebuilt MCP implementation from scratch following JSON-RPC 2.0 specification - Added transport abstraction layer supporting stdio and SSE transports - Created production-ready Zerodha Kite MCP integration example (no mocks) - Implemented proper MCP initialization handshake and error handling - Added comprehensive README section documenting MCP v2.0 improvements - Fixed RegistryAgent initialization bug in discovery module - Enhanced FastMCPAgent with multi-server support and async operations - Added real portfolio analysis and trading assistant capabilities - Maintained backward compatibility with migration guide - Removed all mock data in favor of actual MCP server integrations
1 parent ee2fb20 commit 08f1487

File tree

12 files changed

+2738
-302
lines changed

12 files changed

+2738
-302
lines changed

README.md

Lines changed: 183 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ The A2A protocol establishes a standard communication format that enables AI age
2929

3030
## 📋 What's New in v0.5.X
3131

32+
- **🔌 MCP v2.0 Complete Rewrite**: Rebuilt MCP implementation from scratch following JSON-RPC 2.0 specification
33+
- **🚀 Real-World MCP Examples**: Production-ready examples with actual services (no mocks!) including Zerodha Kite integration
34+
- **🛡️ Enterprise MCP Support**: Robust transport abstraction supporting stdio and SSE for production deployments
35+
- **🔄 Backward Compatible Migration**: Seamless upgrade path from previous MCP implementations
3236
- **Agent Flow UI**: Visual workflow editor for building and managing agent networks with drag-and-drop interface
3337
- **Agent Discovery**: Built-in support for agent registry and discovery with full Google A2A protocol compatibility
3438
- **LangChain Integration**: Seamless integration with LangChain's tools and agents
@@ -780,15 +784,193 @@ Python A2A can be used to build a wide range of AI systems:
780784
- **Educational Workflows**: Design step-by-step learning processes with feedback loops
781785
- **Visual Learning**: Use the Agent Flow UI to teach agent concepts through interactive visualization
782786

787+
## 🔌 Enhanced MCP (Model Context Protocol) Support
788+
789+
Python A2A features a completely redesigned MCP implementation that provides robust, production-ready integration with MCP servers and tools. Our MCP support has been rebuilt from the ground up to follow the official JSON-RPC 2.0 specification.
790+
791+
### 🚀 What's New in MCP v2.0
792+
793+
- **Proper JSON-RPC 2.0 Implementation**: Complete rewrite to follow the official MCP specification
794+
- **Transport Abstraction**: Support for both stdio and Server-Sent Events (SSE) transports
795+
- **Backward Compatibility**: Seamless migration from previous MCP implementations
796+
- **Real-World Examples**: Production-ready examples with actual services (no mocks!)
797+
- **Enterprise Integration**: Support for external MCP servers like Zerodha Kite MCP
798+
799+
### 🏗️ Architecture Overview
800+
801+
```python
802+
from python_a2a.mcp import MCPClient, FastMCPAgent
803+
804+
# The new MCPClient follows JSON-RPC 2.0 specification
805+
client = MCPClient(
806+
url="https://mcp-server.example.com/sse", # SSE transport
807+
transport="sse"
808+
)
809+
810+
# Or use stdio transport for local servers
811+
client = MCPClient(
812+
command=["python", "local_mcp_server.py"],
813+
transport="stdio"
814+
)
815+
816+
# FastMCPAgent provides easy integration with A2A agents
817+
class MyAgent(A2AServer, FastMCPAgent):
818+
def __init__(self):
819+
# Agent setup
820+
super().__init__(agent_card=my_card)
821+
822+
# MCP server configuration
823+
mcp_config = {
824+
"tools_server": {
825+
"url": "https://tools.example.com/sse",
826+
"transport": "sse"
827+
},
828+
"data_server": {
829+
"command": ["python", "data_server.py"],
830+
"transport": "stdio"
831+
}
832+
}
833+
FastMCPAgent.__init__(self, mcp_servers=mcp_config)
834+
```
835+
836+
### 🌟 Key Improvements
837+
838+
#### 1. **Proper Protocol Implementation**
839+
- **JSON-RPC 2.0 Compliant**: Full implementation of the official MCP specification
840+
- **Initialization Handshake**: Proper `initialize``initialized` flow
841+
- **Error Handling**: Comprehensive error handling following JSON-RPC standards
842+
- **Request/Response Mapping**: Accurate message correlation and response handling
843+
844+
#### 2. **Transport Layer Abstraction**
845+
```python
846+
# Support for multiple transport mechanisms
847+
from python_a2a.mcp.client_transport import StdioTransport, SSETransport
848+
849+
# Stdio transport for local processes
850+
stdio_transport = StdioTransport(command=["go", "run", "server.go"])
851+
852+
# SSE transport for remote servers
853+
sse_transport = SSETransport(
854+
url="https://api.example.com/mcp/sse",
855+
headers={"Authorization": "Bearer token"}
856+
)
857+
```
858+
859+
#### 3. **Real-World Integration Examples**
860+
- **Zerodha Kite MCP**: Complete trading assistant with real portfolio analysis
861+
- **No Mock Data**: All examples use actual MCP servers and real data
862+
- **Production Ready**: Examples designed for real-world deployment
863+
864+
### 📈 Zerodha Kite MCP Integration
865+
866+
Our flagship MCP example integrates with Zerodha's official Kite MCP server for real trading analysis:
867+
868+
```python
869+
# examples/mcp/kite_mcp_example.py
870+
from python_a2a.mcp import FastMCPAgent
871+
872+
class KiteTradingAssistant(A2AServer, FastMCPAgent):
873+
def __init__(self):
874+
# Setup with official Zerodha Kite MCP server
875+
kite_config = {
876+
"kite": {
877+
"url": "https://mcp.kite.trade/sse",
878+
"transport": "sse"
879+
}
880+
}
881+
FastMCPAgent.__init__(self, mcp_servers=kite_config)
882+
883+
def handle_message(self, message):
884+
# Real portfolio analysis using live Kite data
885+
if "portfolio" in message.content.text.lower():
886+
holdings = asyncio.run(self.call_mcp_tool("kite", "get_holdings"))
887+
return self._analyze_portfolio(holdings) # Real data analysis
888+
```
889+
890+
**Features:**
891+
- 📊 Real-time portfolio analysis
892+
- 📈 Live market data integration
893+
- 💡 Personalized investment insights
894+
- 🔒 Read-only access for security
895+
- 🌐 Official Zerodha MCP server support
896+
897+
### 🛠️ Migration Guide
898+
899+
#### From Old MCP Implementation:
900+
```python
901+
# Old way (REST-based, deprecated)
902+
client = MCPClient("http://localhost:8000")
903+
result = client.call_tool("my_tool", param="value")
904+
905+
# New way (JSON-RPC 2.0 compliant)
906+
client = MCPClient(
907+
url="http://localhost:8000/sse",
908+
transport="sse"
909+
)
910+
async with client:
911+
result = await client.call_tool("my_tool", param="value")
912+
```
913+
914+
#### Key Changes:
915+
- **Async/Await**: All MCP operations are now async for better performance
916+
- **Context Managers**: Proper resource management with async context managers
917+
- **Transport Specification**: Explicit transport configuration required
918+
- **Error Handling**: Enhanced error handling with specific MCP exception types
919+
920+
### 🔧 Advanced MCP Features
921+
922+
#### Tool Discovery and Validation
923+
```python
924+
# Discover available tools from MCP server
925+
tools = await client.list_tools()
926+
for tool in tools:
927+
print(f"Tool: {tool['name']} - {tool['description']}")
928+
929+
# Validate tool parameters before calling
930+
tool_info = await client.get_tool_info("calculator")
931+
required_params = tool_info["inputSchema"]["required"]
932+
```
933+
934+
#### Multi-Server Management
935+
```python
936+
# Connect to multiple MCP servers simultaneously
937+
mcp_config = {
938+
"calculator": {"command": ["python", "calc_server.py"]},
939+
"database": {"url": "https://db.example.com/mcp/sse"},
940+
"files": {"command": ["node", "file_server.js"]}
941+
}
942+
943+
class MultiToolAgent(A2AServer, FastMCPAgent):
944+
def __init__(self):
945+
FastMCPAgent.__init__(self, mcp_servers=mcp_config)
946+
947+
async def solve_complex_task(self, query):
948+
# Use tools from different servers
949+
calc_result = await self.call_mcp_tool("calculator", "add", a=5, b=3)
950+
data = await self.call_mcp_tool("database", "query", sql="SELECT * FROM users")
951+
file_content = await self.call_mcp_tool("files", "read", path="/config.json")
952+
953+
return self._combine_results(calc_result, data, file_content)
954+
```
955+
956+
### 📚 Additional Resources
957+
958+
- **[MCP Examples Directory](examples/mcp/)**: Complete examples including Kite integration
959+
- **[MCP Documentation](docs/guides/mcp.rst)**: Comprehensive MCP implementation guide
960+
- **[Migration Guide](docs/migration/mcp_v2.md)**: Step-by-step migration from v1 to v2
961+
- **[Best Practices](docs/best_practices/mcp.md)**: Production deployment guidelines
962+
783963
## 🛠️ Real-World Examples
784964

785965
Check out the [`examples/`](https://github.com/themanojdesai/python-a2a/tree/main/examples) directory for real-world examples, including:
786966

967+
- **[Zerodha Kite MCP Integration](examples/mcp/kite_mcp_example.py)**: Real trading assistant with live portfolio analysis
968+
- **[Advanced MCP Client](examples/mcp/mcp_client_example.py)**: Feature-rich MCP client with built-in tools and natural language processing
969+
- **[MCP Agent Integration](examples/mcp/agent_with_mcp_tools.py)**: Seamlessly attach MCP servers to A2A agents
787970
- Multi-agent customer support systems
788971
- LLM-powered research assistants with tool access
789972
- Real-time streaming implementations
790973
- LangChain integration examples
791-
- MCP server implementations for various tools
792974
- Workflow orchestration examples
793975
- Agent network management
794976

docs/guides/mcp.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,46 @@ The Model Context Protocol (MCP) is a standardized way for AI agents to access e
1414

1515
Python A2A provides comprehensive support for MCP through the ``FastMCP`` implementation and the ``A2AMCPAgent`` class.
1616

17+
Key Feature: Easy MCP Attachment
18+
-------------------------------
19+
20+
**One of the unique features of python-a2a is the ability to easily attach any MCP server to agents**, giving them instant access to tools and capabilities. This works with:
21+
22+
- Remote MCP servers (via SSE/HTTP transport)
23+
- Local MCP servers (via stdio transport)
24+
- FastMCP servers (in-process Python tools)
25+
- Any standard MCP-compliant server
26+
27+
Quick Example
28+
~~~~~~~~~~~~
29+
30+
.. code-block:: python
31+
32+
from python_a2a.mcp import A2AMCPAgent
33+
34+
# Create an agent with multiple MCP servers attached
35+
agent = A2AMCPAgent(
36+
name="Super Assistant",
37+
description="An AI assistant with many tools",
38+
mcp_servers={
39+
# Remote MCP server (SSE transport)
40+
"weather": "https://weather-mcp.example.com",
41+
42+
# Local command-based MCP server (stdio transport)
43+
"filesystem": {
44+
"command": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/home"]
45+
},
46+
47+
# Another stdio server
48+
"database": {
49+
"command": ["mcp-server-sqlite", "mydata.db"]
50+
}
51+
}
52+
)
53+
54+
# The agent now has access to all tools from these MCP servers!
55+
# Tools are automatically discovered and can be called by the agent
56+
1757
Creating an MCP Server
1858
--------------------
1959

0 commit comments

Comments
 (0)