From cc56f433a8d53db5e31f74ec65d20d83b3171be7 Mon Sep 17 00:00:00 2001 From: Pavan Kumar <66913595+ascender1729@users.noreply.github.com> Date: Sat, 19 Apr 2025 09:11:09 +0000 Subject: [PATCH] fix(mcp): update architecture to initialize agents on the client side, not the server --- .replit | 2 +- examples/mcp_example/mcp_client.py | 64 ++++++++++++++--------- examples/mcp_example/mock_math_server.py | 33 +++--------- examples/mcp_example/mock_stock_server.py | 8 +-- 4 files changed, 47 insertions(+), 60 deletions(-) diff --git a/.replit b/.replit index 228543a4..b3910d43 100644 --- a/.replit +++ b/.replit @@ -98,4 +98,4 @@ args = "sleep 2" [[workflows.workflow.tasks]] task = "shell.exec" -args = "python examples/mcp_example/mock_multi_agent.py" +args = "python examples/mcp_example/mcp_client.py" diff --git a/examples/mcp_example/mcp_client.py b/examples/mcp_example/mcp_client.py index 96d73b51..70330b30 100644 --- a/examples/mcp_example/mcp_client.py +++ b/examples/mcp_example/mcp_client.py @@ -1,49 +1,63 @@ + from swarms import Agent from swarms.tools.mcp_integration import MCPServerSseParams +from swarms.prompts.agent_prompts import FINANCE_AGENT_PROMPT, MATH_AGENT_PROMPT def main(): - # Configure MCP server connection + # Configure MCP server connections math_server = MCPServerSseParams( url="http://0.0.0.0:8000/mcp", headers={"Content-Type": "application/json"}, - timeout=5.0, + timeout=5.0, + sse_read_timeout=30.0 + ) + + stock_server = MCPServerSseParams( + url="http://0.0.0.0:8001/mcp", + headers={"Content-Type": "application/json"}, + timeout=5.0, sse_read_timeout=30.0 ) - # Initialize agent with MCP server - agent = Agent( + # Initialize math agent + math_agent = Agent( agent_name="Math Agent", - agent_description="Agent for performing mathematical operations", - system_prompt="""You are a mathematical computation specialist. Use the available MCP server tools to: - - Add numbers - - Multiply numbers - - Divide numbers - - Always: - 1. Use only tools available from the MCP server - 2. Explain your mathematical approach - 3. Show your work step by step""", + agent_description="Specialized agent for mathematical computations", + system_prompt=MATH_AGENT_PROMPT, max_loops=1, mcp_servers=[math_server], streaming_on=True, model_name="gpt-4o-mini" ) - print("\nMath Agent initialized with MCP capabilities") - print("Available operations:") - print("- Addition") - print("- Multiplication") - print("- Division") + # Initialize stock agent + stock_agent = Agent( + agent_name="Stock Agent", + agent_description="Specialized agent for stock analysis", + system_prompt=FINANCE_AGENT_PROMPT, + max_loops=1, + mcp_servers=[stock_server], + streaming_on=True, + model_name="gpt-4o-mini" + ) - while True: - query = input("\nEnter a math problem (or 'exit' to quit): ") + print("\nMulti-Agent System Initialized") + print("\nAvailable operations:") + print("Math Agent: add, multiply, divide") + print("Stock Agent: get stock price, calculate moving average") + while True: + query = input("\nEnter your query (or 'exit' to quit): ") + if query.lower() == 'exit': break - # Process query through agent - result = agent.run(query) - print("\nResult:", result) + # Process with both agents + math_result = math_agent.run(query) + stock_result = stock_agent.run(query) + + print("\nMath Agent Response:", math_result) + print("Stock Agent Response:", stock_result) if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/examples/mcp_example/mock_math_server.py b/examples/mcp_example/mock_math_server.py index e49368a2..c5f51d90 100644 --- a/examples/mcp_example/mock_math_server.py +++ b/examples/mcp_example/mock_math_server.py @@ -1,45 +1,24 @@ - from fastmcp import FastMCP -from typing import Dict, Any -import time -# Initialize MCP server mcp = FastMCP("Math-Mock-Server") @mcp.tool() def add(a: int, b: int) -> int: """Add two numbers together""" - try: - print(f"MCP Server: Processing addition request for {a} + {b}") - time.sleep(0.1) # Simulate processing time - result = a + b - print(f"MCP Server: Returning result {result}") - return result - except Exception as e: - error_msg = f"Error adding numbers: {str(e)}" - print(f"MCP Server: {error_msg}") - return {"error": error_msg} + return a + b @mcp.tool() def multiply(a: int, b: int) -> int: """Multiply two numbers together""" - try: - time.sleep(0.1) # Simulate processing time - return a * b - except Exception as e: - return {"error": f"Error multiplying numbers: {str(e)}"} + return a * b @mcp.tool() def divide(a: int, b: int) -> float: """Divide two numbers""" - try: - if b == 0: - return {"error": "Cannot divide by zero"} - time.sleep(0.1) # Simulate processing time - return a / b - except Exception as e: - return {"error": f"Error dividing numbers: {str(e)}"} + if b == 0: + return {"error": "Cannot divide by zero"} + return a / b if __name__ == "__main__": print("Starting Mock Math Server on port 8000...") - mcp.run(transport="sse", host="0.0.0.0", port=8000) + mcp.run(transport="sse", host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/examples/mcp_example/mock_stock_server.py b/examples/mcp_example/mock_stock_server.py index 3bbd6c76..2ea64f93 100644 --- a/examples/mcp_example/mock_stock_server.py +++ b/examples/mcp_example/mock_stock_server.py @@ -2,7 +2,6 @@ from fastmcp import FastMCP from typing import Dict, Union -# Create FastMCP server mcp = FastMCP("Stock-Mock-Server") @mcp.tool() @@ -21,13 +20,8 @@ def get_stock_price(symbol: str) -> Dict[str, Union[float, str]]: @mcp.tool() def calculate_moving_average(prices: list[float], window: int) -> Dict[str, Union[list[float], str]]: """Calculate moving average of stock prices""" - if not isinstance(prices, list) or not all(isinstance(x, (int, float)) for x in prices): - return {"error": "Invalid price data"} - if not isinstance(window, int) or window <= 0: - return {"error": "Invalid window size"} if len(prices) < window: return {"error": "Not enough price points"} - avgs = [] for i in range(len(prices) - window + 1): avg = sum(prices[i:i+window]) / window @@ -36,4 +30,4 @@ def calculate_moving_average(prices: list[float], window: int) -> Dict[str, Unio if __name__ == "__main__": print("Starting Mock Stock Server on port 8001...") - mcp.run(transport="sse", transport_kwargs={"host": "0.0.0.0", "port": 8001}) + mcp.run(transport="sse", host="0.0.0.0", port=8001)