From c4c81a47670fb11f1fe691ef20f6507ba4431898 Mon Sep 17 00:00:00 2001 From: Pavan Kumar <66913595+ascender1729@users.noreply.github.com> Date: Thu, 17 Apr 2025 16:32:41 +0000 Subject: [PATCH] feat: set up interactive multi-agent MCP test environment with multi-server coordination --- .replit | 2 +- examples/mcp_example/calc_server.py | 29 ++++--- examples/mcp_example/math_server.py | 45 +++++----- examples/mcp_example/test_integration.py | 105 +++++++++++++---------- 4 files changed, 105 insertions(+), 76 deletions(-) diff --git a/.replit b/.replit index a1c69739..e3a29fb7 100644 --- a/.replit +++ b/.replit @@ -4,7 +4,7 @@ modules = ["python-3.10", "bash"] channel = "stable-24_05" [workflows] -runButton = "Run MCP Server" +runButton = "Run Multiple MCP" [[workflows.workflow]] name = "Run MCP Tests" diff --git a/examples/mcp_example/calc_server.py b/examples/mcp_example/calc_server.py index acc3a425..9cb006d4 100644 --- a/examples/mcp_example/calc_server.py +++ b/examples/mcp_example/calc_server.py @@ -1,27 +1,36 @@ from fastmcp import FastMCP from typing import Dict, Any -import math -# Initialize MCP server +# Initialize MCP server for business calculations mcp = FastMCP("Calc-Server") @mcp.tool() -def square_root(x: float) -> float: - """Calculate square root of a number""" +def profit_margin(revenue: float, cost: float) -> Dict[str, Any]: + """Calculate profit margin from revenue and cost""" try: - return math.sqrt(x) + profit = revenue - cost + margin = (profit / revenue) * 100 + return { + "profit": profit, + "margin_percentage": margin, + "summary": f"On revenue of ${revenue:.2f} and costs of ${cost:.2f}, profit is ${profit:.2f} with a margin of {margin:.1f}%" + } except Exception as e: return {"error": str(e)} @mcp.tool() -def power(base: float, exponent: float) -> float: - """Raise a number to a power""" +def break_even_point(fixed_costs: float, price_per_unit: float, cost_per_unit: float) -> Dict[str, Any]: + """Calculate break-even point""" try: - return math.pow(base, exponent) + bep = fixed_costs / (price_per_unit - cost_per_unit) + return { + "break_even_units": bep, + "summary": f"You need to sell {bep:.0f} units to break even" + } except Exception as e: return {"error": str(e)} if __name__ == "__main__": - print("Starting Calc Server on port 6275...") - mcp.run(transport="sse", host="0.0.0.0", port=6275) + print("Starting Business Calculator Server on port 6275...") + mcp.run(transport="sse") diff --git a/examples/mcp_example/math_server.py b/examples/mcp_example/math_server.py index 5257f84b..4957b3ea 100644 --- a/examples/mcp_example/math_server.py +++ b/examples/mcp_example/math_server.py @@ -2,33 +2,38 @@ from fastmcp import FastMCP from typing import Dict, Any -# Initialize MCP server +# Initialize MCP server for math operations mcp = FastMCP("Math-Server") @mcp.tool() -def add(a: int, b: int) -> int: - """Add two numbers together""" - try: - return a + b - except Exception as e: - return {"error": str(e)} +def add(a: float, b: float) -> float: + """Add two numbers""" + return a + b @mcp.tool() -def multiply(a: int, b: int) -> int: - """Multiply two numbers together""" - try: - return a * b - except Exception as e: - return {"error": str(e)} +def subtract(a: float, b: float) -> float: + """Subtract b from a""" + return a - b @mcp.tool() -def subtract(a: int, b: int) -> int: - """Subtract two numbers""" - try: - return a - b - except Exception as e: - return {"error": str(e)} +def multiply(a: float, b: float) -> float: + """Multiply two numbers""" + return a * b + +@mcp.tool() +def divide(a: float, b: float) -> float: + """Divide a by b""" + if b == 0: + return {"error": "Cannot divide by zero"} + return a / b + +@mcp.tool() +def calculate_percentage(part: float, whole: float) -> float: + """Calculate percentage""" + if whole == 0: + return {"error": "Cannot calculate percentage with zero total"} + return (part / whole) * 100 if __name__ == "__main__": print("Starting Math Server on port 6274...") - mcp.run(transport="sse", host="0.0.0.0", port=6274) + mcp.run(transport="sse") diff --git a/examples/mcp_example/test_integration.py b/examples/mcp_example/test_integration.py index fc22a71d..d49e9887 100644 --- a/examples/mcp_example/test_integration.py +++ b/examples/mcp_example/test_integration.py @@ -1,69 +1,84 @@ from swarms import Agent -from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT +from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT from swarms.tools.mcp_integration import MCPServerSseParams import logging +import time + +def setup_agent(name: str, description: str, servers: list) -> Agent: + """Setup an agent with MCP server connections""" + return Agent( + agent_name=name, + agent_description=description, + system_prompt=FINANCIAL_AGENT_SYS_PROMPT, + max_loops=1, + mcp_servers=servers, + streaming_on=True + ) def main(): - # Configure multiple MCP server connections + # Configure MCP server connections math_server = MCPServerSseParams( url="http://0.0.0.0:6274", headers={"Content-Type": "application/json"}, - timeout=10.0, - sse_read_timeout=300.0 + timeout=10.0 ) - + calc_server = MCPServerSseParams( - url="http://0.0.0.0:6275", + url="http://0.0.0.0:6275", headers={"Content-Type": "application/json"}, - timeout=10.0, - sse_read_timeout=300.0 + timeout=10.0 ) - # Initialize multiple agents with different MCP capabilities - math_agent = Agent( - agent_name="Math-Agent", - agent_description="Agent that performs math operations", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT, - max_loops=1, - mcp_servers=[math_server], - streaming_on=True + # Initialize specialized agents + coordinator = setup_agent( + "Coordinator", + "Analyzes tasks and coordinates between specialized agents", + [math_server, calc_server] ) - - calc_agent = Agent( - agent_name="Calc-Agent", - agent_description="Agent that performs calculations", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT, - max_loops=1, - mcp_servers=[calc_server], - streaming_on=True + + math_agent = setup_agent( + "Math-Agent", + "Handles mathematical calculations", + [math_server] + ) + + business_agent = setup_agent( + "Business-Agent", + "Handles business calculations", + [calc_server] ) - agents = [math_agent, calc_agent] + print("\nMulti-Agent MCP Test Environment") + print("Type 'exit' to quit\n") - try: - # Test each agent - for agent in agents: - print(f"\nTesting {agent.agent_name}...") - print("\nDiscovering available tools from MCP server...") - tools = agent.mcp_tool_handling() - print(f"\nAvailable tools for {agent.agent_name}:", tools) + while True: + try: + user_input = input("\nEnter your request: ") - while True: - user_input = input(f"\nEnter a math operation for {agent.agent_name} (or 'exit' to switch agent): ") + if user_input.lower() == 'exit': + break - if user_input.lower() == 'exit': - break - - try: - result = agent.run(user_input) - print(f"\nResult from {agent.agent_name}:", result) - except Exception as e: - print(f"Error processing request: {e}") + # Coordinator analyzes task + print("\nCoordinator analyzing task...") + coordinator_response = coordinator.run( + f"Analyze this task and determine required calculations: {user_input}" + ) + print(f"\nCoordinator's plan: {coordinator_response}") + + # Route to appropriate agent(s) + if "profit" in user_input.lower() or "margin" in user_input.lower(): + print("\nRouting to Business Agent...") + result = business_agent.run(user_input) + print(f"\nBusiness calculation result: {result}") + + if any(op in user_input.lower() for op in ['add', 'subtract', 'multiply', 'divide']): + print("\nRouting to Math Agent...") + result = math_agent.run(user_input) + print(f"\nMath calculation result: {result}") - except Exception as e: - logging.error(f"Test failed: {e}") - raise + except Exception as e: + print(f"Error processing request: {e}") if __name__ == "__main__": logging.basicConfig(level=logging.INFO)