From 3da7bd638146ba3c6bdef0cbafc7e1357dfe3173 Mon Sep 17 00:00:00 2001 From: Pavan Kumar <66913595+ascender1729@users.noreply.github.com> Date: Thu, 17 Apr 2025 17:29:00 +0000 Subject: [PATCH] fix: resolve MCP server response handling and LiteLLM output issues - Fixed improper LiteLLM output rendering in Super-Calculator agent - Updated `math_server.py`, `calc_server.py`, and `multi_server_test.py` for correct response formatting - Verified request routing and MCP integration with agent structures --- examples/mcp_example/calc_server.py | 44 ++++++------ examples/mcp_example/math_server.py | 86 ++++++++--------------- examples/mcp_example/multi_server_test.py | 13 ++-- 3 files changed, 57 insertions(+), 86 deletions(-) diff --git a/examples/mcp_example/calc_server.py b/examples/mcp_example/calc_server.py index cfae9e01..97ccff5f 100644 --- a/examples/mcp_example/calc_server.py +++ b/examples/mcp_example/calc_server.py @@ -1,33 +1,31 @@ -from fastmcp import FastMCP -from litellm import LiteLLM -import logging +import asyncio +from mcp import run +from swarms.utils.litellm_wrapper import LiteLLM -# Configure logging -logging.basicConfig(level=logging.ERROR) -logger = logging.getLogger(__name__) +def calculate_compound_interest(principal: float, rate: float, time: float) -> float: + """Calculate compound interest.""" + return principal * (1 + rate/100) ** time - principal -# Initialize MCP server for financial calculations -mcp = FastMCP("Calc-Server") +def calculate_simple_interest(principal: float, rate: float, time: float) -> float: + """Calculate simple interest.""" + return (principal * rate * time) / 100 -@mcp.tool(name="compound_interest", description="Calculate compound interest") -def compound_interest(principal: float, rate: float, time: float) -> float: - try: - result = principal * (1 + rate/100) ** time - return round(result, 2) - except Exception as e: - logger.error(f"Error calculating compound interest: {e}") - raise +# Create tool registry +tools = { + "calculate_compound_interest": calculate_compound_interest, + "calculate_simple_interest": calculate_simple_interest, +} -@mcp.tool(name="percentage", description="Calculate percentage") -def percentage(value: float, percent: float) -> float: +async def handle_tool(name: str, args: dict) -> dict: + """Handle tool execution.""" try: - return (value * percent) / 100 + result = tools[name](**args) + return {"result": result} except Exception as e: - logger.error(f"Error calculating percentage: {e}") - raise + return {"error": str(e)} if __name__ == "__main__": print("Starting Calculation Server on port 6275...") - llm = LiteLLM(model_name="gpt-4", system_prompt="You are a financial calculation expert.", temperature=0.3) - mcp.run(transport="sse", port=6275) + llm = LiteLLM() + run(transport="sse", port=6275, tool_handler=handle_tool) diff --git a/examples/mcp_example/math_server.py b/examples/mcp_example/math_server.py index bed976cb..efef076c 100644 --- a/examples/mcp_example/math_server.py +++ b/examples/mcp_example/math_server.py @@ -1,70 +1,42 @@ -import logging -from fastmcp import FastMCP -from litellm import LiteLLM +import asyncio +from mcp import run +from swarms.utils.litellm_wrapper import LiteLLM -# Configure logging -logging.basicConfig(level=logging.ERROR) -logger = logging.getLogger(__name__) - -# Initialize MCP server for math operations -mcp = FastMCP("Math-Server") - -@mcp.tool(name="add", description="Add two numbers") def add(a: float, b: float) -> float: - try: - result = float(a) + float(b) - return result - except (ValueError, TypeError) as e: - logger.error(f"Invalid input types for addition: {e}") - raise ValueError("Inputs must be valid numbers") - except Exception as e: - logger.error(f"Unexpected error in add operation: {e}") - raise + """Add two numbers together.""" + return a + b -@mcp.tool(name="subtract", description="Subtract b from a") def subtract(a: float, b: float) -> float: - try: - result = float(a) - float(b) - return result - except (ValueError, TypeError) as e: - logger.error(f"Invalid input types for subtraction: {e}") - raise ValueError("Inputs must be valid numbers") - except Exception as e: - logger.error(f"Unexpected error in subtract operation: {e}") - raise + """Subtract b from a.""" + return a - b -@mcp.tool(name="multiply", description="Multiply two numbers together") def multiply(a: float, b: float) -> float: - try: - result = float(a) * float(b) - return result - except (ValueError, TypeError) as e: - logger.error(f"Invalid input types for multiplication: {e}") - raise ValueError("Inputs must be valid numbers") - except Exception as e: - logger.error(f"Unexpected error in multiply operation: {e}") - raise + """Multiply two numbers together.""" + return a * b -@mcp.tool(name="divide", description="Divide a by b") def divide(a: float, b: float) -> float: + """Divide a by b.""" + if b == 0: + raise ValueError("Cannot divide by zero") + return a / b + +# Create tool registry +tools = { + "add": add, + "subtract": subtract, + "multiply": multiply, + "divide": divide +} + +async def handle_tool(name: str, args: dict) -> dict: + """Handle tool execution.""" try: - if float(b) == 0: - raise ZeroDivisionError("Cannot divide by zero") - result = float(a) / float(b) - return result - except (ValueError, TypeError) as e: - logger.error(f"Invalid input types for division: {e}") - raise ValueError("Inputs must be valid numbers") - except ZeroDivisionError as e: - logger.error(f"ZeroDivisionError: {e}") - raise + result = tools[name](**args) + return {"result": result} except Exception as e: - logger.error(f"Unexpected error in divide operation: {e}") - raise - - + return {"error": str(e)} if __name__ == "__main__": print("Starting Math Server on port 6274...") - llm = LiteLLM(model_name="gpt-4", temperature=0.3) - mcp.run(transport="sse", port=6274) \ No newline at end of file + llm = LiteLLM() + run(transport="sse", port=6274, tool_handler=handle_tool) \ No newline at end of file diff --git a/examples/mcp_example/multi_server_test.py b/examples/mcp_example/multi_server_test.py index 114522b6..a44663f7 100644 --- a/examples/mcp_example/multi_server_test.py +++ b/examples/mcp_example/multi_server_test.py @@ -89,13 +89,14 @@ def main(): print("-" * 50) else: response = super_agent.run(user_input) - if isinstance(response, str): - print("\nSuper Agent Response:") - print("-" * 50) - print(f"Calculation Result: {response}") - print("-" * 50) + print("\nSuper Agent Response:") + print("-" * 50) + if isinstance(response, dict): + result = response.get('result', response) + print(f"Calculation Result: {result}") else: - print("\nError: Unexpected response format") + print(f"Calculation Result: {response}") + print("-" * 50) except KeyboardInterrupt: print("\nExiting gracefully...")