multi_server.py
1 """ 2 Multi-Server MCP Example. 3 4 This example demonstrates how to use multiple MCP servers with PraisonAI Agents, 5 including mixing MCP tools with regular Python function tools. 6 7 Requirements: 8 - Node.js and npx installed (or uvx for Python-based servers) 9 - pip install praisonaiagents[mcp] 10 - OPENAI_API_KEY environment variable set 11 12 Usage: 13 python multi_server.py 14 """ 15 16 from praisonaiagents import Agent, MCP 17 import os 18 19 20 def calculate(expression: str) -> str: 21 """ 22 A simple calculator tool that evaluates mathematical expressions. 23 24 Args: 25 expression: A mathematical expression to evaluate (e.g., "2 + 2") 26 27 Returns: 28 The result of the calculation 29 """ 30 try: 31 # Safe evaluation of mathematical expressions 32 allowed_chars = set("0123456789+-*/.() ") 33 if not all(c in allowed_chars for c in expression): 34 return "Error: Invalid characters in expression" 35 result = eval(expression) 36 return f"Result: {result}" 37 except Exception as e: 38 return f"Error: {str(e)}" 39 40 41 def main(): 42 # Check for API key 43 if not os.environ.get("OPENAI_API_KEY"): 44 print("Please set OPENAI_API_KEY environment variable") 45 return 46 47 print("=" * 60) 48 print("Multi-Server MCP Example") 49 print("=" * 60) 50 51 # Create MCP instance with Time server 52 print("\nInitializing MCP servers...") 53 try: 54 time_mcp = MCP("uvx mcp-server-time", timeout=30) 55 print("✓ Time MCP server initialized") 56 except Exception as e: 57 print(f"✗ Time MCP server failed: {e}") 58 return 59 60 # Create an agent with multiple tool sources 61 agent = Agent( 62 name="MultiToolAgent", 63 instructions="""You are a helpful assistant with access to multiple tools: 64 1. Time tools - for getting current time in different timezones 65 2. Calculator - for mathematical calculations 66 67 Use the appropriate tool based on the user's request.""", 68 llm="openai/gpt-4o-mini", 69 tools=[time_mcp, calculate] # Mix MCP and regular tools 70 ) 71 72 # Show available tools 73 print("\nAvailable tools:") 74 formatted_tools = agent._format_tools_for_completion(agent.tools) 75 for tool in formatted_tools: 76 print(f" - {tool['function']['name']}: {tool['function']['description'][:50]}...") 77 78 # Example queries 79 queries = [ 80 "What time is it in Tokyo?", 81 "Calculate 15 * 7 + 23", 82 "What's the current time in New York and London?" 83 ] 84 85 print("\n" + "=" * 60) 86 print("Running queries...") 87 print("=" * 60) 88 89 for i, query in enumerate(queries, 1): 90 print(f"\n--- Query {i} ---") 91 print(f"Question: {query}\n") 92 93 try: 94 response = agent.chat(query) 95 print(f"Response:\n{response}") 96 except Exception as e: 97 print(f"Error: {e}") 98 99 print("-" * 40) 100 101 # Clean up 102 time_mcp.shutdown() 103 print("\nDone!") 104 105 106 def demo_multiple_mcp_servers(): 107 """ 108 Demonstrate using multiple MCP servers simultaneously. 109 110 This function shows how to create agents with multiple MCP servers, 111 each providing different capabilities. 112 """ 113 print("\n" + "=" * 60) 114 print("Multiple MCP Servers Demo") 115 print("=" * 60) 116 117 # Initialize multiple MCP servers 118 servers = {} 119 120 try: 121 servers['time'] = MCP("uvx mcp-server-time", timeout=30) 122 print("✓ Time server initialized") 123 except Exception as e: 124 print(f"✗ Time server failed: {e}") 125 126 # Create agent with all available servers 127 available_tools = list(servers.values()) 128 129 if not available_tools: 130 print("No MCP servers available") 131 return 132 133 agent = Agent( 134 name="MultiServerAgent", 135 instructions="You have access to multiple MCP servers. Use the appropriate tools.", 136 llm="openai/gpt-4o-mini", 137 tools=available_tools 138 ) 139 140 print(f"\nAgent created with {len(available_tools)} MCP server(s)") 141 142 # Clean up 143 for server in servers.values(): 144 server.shutdown() 145 146 147 if __name__ == "__main__": 148 main()