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
pull/819/head
Pavan Kumar 6 days ago committed by ascender1729
parent 885a50c985
commit 3da7bd6381

@ -1,33 +1,31 @@
from fastmcp import FastMCP import asyncio
from litellm import LiteLLM from mcp import run
import logging from swarms.utils.litellm_wrapper import LiteLLM
# Configure logging def calculate_compound_interest(principal: float, rate: float, time: float) -> float:
logging.basicConfig(level=logging.ERROR) """Calculate compound interest."""
logger = logging.getLogger(__name__) return principal * (1 + rate/100) ** time - principal
# Initialize MCP server for financial calculations def calculate_simple_interest(principal: float, rate: float, time: float) -> float:
mcp = FastMCP("Calc-Server") """Calculate simple interest."""
return (principal * rate * time) / 100
@mcp.tool(name="compound_interest", description="Calculate compound interest") # Create tool registry
def compound_interest(principal: float, rate: float, time: float) -> float: tools = {
try: "calculate_compound_interest": calculate_compound_interest,
result = principal * (1 + rate/100) ** time "calculate_simple_interest": calculate_simple_interest,
return round(result, 2) }
except Exception as e:
logger.error(f"Error calculating compound interest: {e}")
raise
@mcp.tool(name="percentage", description="Calculate percentage") async def handle_tool(name: str, args: dict) -> dict:
def percentage(value: float, percent: float) -> float: """Handle tool execution."""
try: try:
return (value * percent) / 100 result = tools[name](**args)
return {"result": result}
except Exception as e: except Exception as e:
logger.error(f"Error calculating percentage: {e}") return {"error": str(e)}
raise
if __name__ == "__main__": if __name__ == "__main__":
print("Starting Calculation Server on port 6275...") print("Starting Calculation Server on port 6275...")
llm = LiteLLM(model_name="gpt-4", system_prompt="You are a financial calculation expert.", temperature=0.3) llm = LiteLLM()
mcp.run(transport="sse", port=6275) run(transport="sse", port=6275, tool_handler=handle_tool)

@ -1,70 +1,42 @@
import logging import asyncio
from fastmcp import FastMCP from mcp import run
from litellm import LiteLLM 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: def add(a: float, b: float) -> float:
try: """Add two numbers together."""
result = float(a) + float(b) return a + 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
@mcp.tool(name="subtract", description="Subtract b from a")
def subtract(a: float, b: float) -> float: def subtract(a: float, b: float) -> float:
try: """Subtract b from a."""
result = float(a) - float(b) return a - 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
@mcp.tool(name="multiply", description="Multiply two numbers together")
def multiply(a: float, b: float) -> float: def multiply(a: float, b: float) -> float:
try: """Multiply two numbers together."""
result = float(a) * float(b) return a * 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
@mcp.tool(name="divide", description="Divide a by b")
def divide(a: float, b: float) -> float: 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: try:
if float(b) == 0: result = tools[name](**args)
raise ZeroDivisionError("Cannot divide by zero") return {"result": result}
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
except Exception as e: except Exception as e:
logger.error(f"Unexpected error in divide operation: {e}") return {"error": str(e)}
raise
if __name__ == "__main__": if __name__ == "__main__":
print("Starting Math Server on port 6274...") print("Starting Math Server on port 6274...")
llm = LiteLLM(model_name="gpt-4", temperature=0.3) llm = LiteLLM()
mcp.run(transport="sse", port=6274) run(transport="sse", port=6274, tool_handler=handle_tool)

@ -89,13 +89,14 @@ def main():
print("-" * 50) print("-" * 50)
else: else:
response = super_agent.run(user_input) response = super_agent.run(user_input)
if isinstance(response, str):
print("\nSuper Agent Response:") print("\nSuper Agent Response:")
print("-" * 50) print("-" * 50)
if isinstance(response, dict):
result = response.get('result', response)
print(f"Calculation Result: {result}")
else:
print(f"Calculation Result: {response}") print(f"Calculation Result: {response}")
print("-" * 50) print("-" * 50)
else:
print("\nError: Unexpected response format")
except KeyboardInterrupt: except KeyboardInterrupt:
print("\nExiting gracefully...") print("\nExiting gracefully...")

Loading…
Cancel
Save