Update MCP integration with improved error handling and testing

pull/819/head
ascender1729 3 months ago
parent e8912f3c83
commit ee9230f819

@ -1,60 +1,62 @@
from swarms import Agent import os
from loguru import logger
import sys import sys
from swarms.prompts.agent_prompts import MATH_PROMPT from loguru import logger
# Configure logging from swarms import Agent
logger.remove() from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}") from swarms.tools.mcp_integration import MCPServerSseParams
# Math prompt for testing MCP integration # Configure API key
# Configure logging
logger.remove()
logger.add(sys.stdout, level="DEBUG", format="{time} | {level} | {message}")
# Define a simpler prompt that focuses on math operations
SIMPLE_MATH_PROMPT = """
You are a math calculator assistant that uses external tools.
When asked for calculations, extract the numbers and use the appropriate tool.
Available tools:
- add: For addition
- multiply: For multiplication
- divide: For division
Keep your responses concise and focused on the calculation.
"""
def main(): def main():
"""Test MCP integration with Agent."""
print("=== MINIMAL MCP AGENT INTEGRATION TEST ===") print("=== MINIMAL MCP AGENT INTEGRATION TEST ===")
try: # Properly configured MCP parameters
# Create the MCP server parameters as a dictionary mcp_params = MCPServerSseParams(
mcp_server = { url="http://127.0.0.1:8000",
"url": "http://0.0.0.0:8000", headers={
"headers": { "Content-Type": "application/json",
"Content-Type": "application/json", "Accept": "text/event-stream"
"Accept": "text/event-stream" },
}, timeout=30.0, # Increased timeout
"timeout": 10.0, sse_read_timeout=60.0
"sse_read_timeout": 30.0 )
}
agent = Agent(
# Create agent with minimal configuration agent_name="MCP Test Agent",
agent = Agent( system_prompt=SIMPLE_MATH_PROMPT, # Using simpler prompt
agent_name="MCP Test Agent", mcp_servers=[mcp_params],
system_prompt=MATH_PROMPT, model_name="gpt-4o-mini",
mcp_servers=[mcp_server], # Pass as a list of dictionaries max_loops=2, # Allow for retry
model_name="gpt-4o-mini", verbose=True
verbose=False # Reduce verbosity to focus on errors )
)
print("\nAgent created successfully! Type 'exit' to quit.")
print("\nAgent created successfully!") while True:
print("Enter a math query or 'exit' to quit") query = input("\nMath query: ").strip()
if query.lower() == "exit":
# Simple interaction loop break
while True:
query = input("\nMath query: ").strip() print(f"\nProcessing: {query}")
if query.lower() == 'exit': try:
break
# Run the agent
print(f"\nProcessing: {query}")
result = agent.run(query) result = agent.run(query)
# Display result
print(f"\nResult: {result}") print(f"\nResult: {result}")
except Exception as e:
except Exception as e: print(f"\nError processing query: {str(e)}")
logger.error(f"Error: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

@ -1,86 +1,56 @@
from fastmcp import FastMCP from fastmcp import FastMCP
from loguru import logger from loguru import logger
import sys
import time import time
# Create the MCP server with all interfaces binding # Configure detailed logging
logger.remove()
logger.add(sys.stdout, level="DEBUG", format="{time} | {level} | {message}")
# Create MCP server with fixed configuration
mcp = FastMCP( mcp = FastMCP(
host= host="127.0.0.1", # Bind to localhost only
"0.0.0.0", # Bind to all interfaces to be accessible from other contexts
port=8000, port=8000,
transport="sse", transport="sse",
require_session_id=False, require_session_id=False,
cors_allowed_origins=["*"], # Allow all origins for testing cors_allowed_origins=["*"],
debug=True # Enable debug mode debug=True
) )
# Define tools with proper return format
# Define tools
@mcp.tool() @mcp.tool()
def add(a: int, b: int) -> str: def add(a: int, b: int) -> int:
"""Add two numbers. """Add two numbers."""
Args:
a (int): First number
b (int): Second number
Returns:
str: A message containing the sum
"""
logger.info(f"Adding {a} and {b}")
result = a + b result = a + b
return f"The sum of {a} and {b} is {result}" logger.info(f"Adding {a} + {b} = {result}")
return result # Let FastMCP handle the response formatting
@mcp.tool() @mcp.tool()
def multiply(a: int, b: int) -> str: def multiply(a: int, b: int) -> int:
"""Multiply two numbers. """Multiply two numbers."""
Args:
a (int): First number
b (int): Second number
Returns:
str: A message containing the product
"""
logger.info(f"Multiplying {a} and {b}")
result = a * b result = a * b
return f"The product of {a} and {b} is {result}" logger.info(f"Multiplying {a} * {b} = {result}")
return result
@mcp.tool() @mcp.tool()
def divide(a: int, b: int) -> str: def divide(a: int, b: int) -> float:
"""Divide two numbers. """Divide the first number by the second."""
Args:
a (int): Numerator
b (int): Denominator
Returns:
str: A message containing the division result or an error message
"""
logger.info(f"Dividing {a} by {b}")
if b == 0: if b == 0:
logger.warning("Division by zero attempted") raise ValueError("Cannot divide by zero")
return "Cannot divide by zero"
result = a / b result = a / b
return f"{a} divided by {b} is {result}" logger.info(f"Dividing {a} / {b} = {result}")
return result
if __name__ == "__main__": def main():
try: try:
# Log server details logger.info("Starting mock math server on http://127.0.0.1:8000")
logger.info("Starting math server on http://0.0.0.0:8000") print("Math MCP Server running on http://127.0.0.1:8000 (SSE)\n")
print("Math MCP Server is running on http://0.0.0.0:8000") print("Available tools:\n - add\n - multiply\n - divide\n")
print("Press Ctrl+C to stop.") mcp.run() # This runs the server in a blocking mode
# List available tools
print("\nAvailable tools:")
print("- add: Add two numbers")
print("- multiply: Multiply two numbers")
print("- divide: Divide first number by second number")
# Add a small delay to ensure logging is complete
time.sleep(0.5)
# Run the MCP server
mcp.run()
except KeyboardInterrupt:
logger.info("Server shutdown requested")
print("\nShutting down server...")
except Exception as e: except Exception as e:
logger.error(f"Server error: {e}") logger.error(f"Error starting server: {e}")
raise import traceback
traceback.print_exc()
if __name__ == "__main__":
main()

@ -0,0 +1,25 @@
import requests
import time
import sys
from loguru import logger
# Configure logger
logger.remove()
logger.add(sys.stdout, level="DEBUG")
def test_server_connection():
"""Simple test to see if server responds at all."""
url = "http://localhost:8000"
try:
logger.debug(f"Testing connection to {url}")
response = requests.get(url)
logger.debug(f"Response status: {response.status_code}")
logger.debug(f"Response content: {response.text[:100]}...")
return True
except Exception as e:
logger.error(f"Connection failed: {str(e)}")
return False
if __name__ == "__main__":
test_server_connection()

@ -1,6 +1,6 @@
# Agent prompts for MCP testing and interactions # Agent prompts for MCP testing and interactions
MATH_PROMPT = """ MATH_AGENT_PROMPT = """
You are a math calculator assistant. You are a math calculator assistant.
When asked for calculations: When asked for calculations:

Loading…
Cancel
Save