Skip to content

Commit c665262

Browse files
committed
Update MCP integration with improved error handling and testing
1 parent cd121c4 commit c665262

File tree

4 files changed

+112
-115
lines changed

4 files changed

+112
-115
lines changed

examples/mcp_example/mcp_client.py

+52-50
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,62 @@
1-
from swarms import Agent
2-
from loguru import logger
1+
import os
32
import sys
4-
from swarms.prompts.agent_prompts import MATH_PROMPT
5-
# Configure logging
6-
logger.remove()
7-
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")
3+
from loguru import logger
4+
from swarms import Agent
5+
from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
6+
from swarms.tools.mcp_integration import MCPServerSseParams
87

9-
# Math prompt for testing MCP integration
8+
# Configure API key
109

10+
# Configure logging
11+
logger.remove()
12+
logger.add(sys.stdout, level="DEBUG", format="{time} | {level} | {message}")
13+
14+
# Define a simpler prompt that focuses on math operations
15+
SIMPLE_MATH_PROMPT = """
16+
You are a math calculator assistant that uses external tools.
17+
When asked for calculations, extract the numbers and use the appropriate tool.
18+
Available tools:
19+
- add: For addition
20+
- multiply: For multiplication
21+
- divide: For division
22+
Keep your responses concise and focused on the calculation.
23+
"""
1124

1225
def main():
13-
"""Test MCP integration with Agent."""
1426
print("=== MINIMAL MCP AGENT INTEGRATION TEST ===")
15-
16-
try:
17-
# Create the MCP server parameters as a dictionary
18-
mcp_server = {
19-
"url": "http://0.0.0.0:8000",
20-
"headers": {
21-
"Content-Type": "application/json",
22-
"Accept": "text/event-stream"
23-
},
24-
"timeout": 10.0,
25-
"sse_read_timeout": 30.0
26-
}
27-
28-
# Create agent with minimal configuration
29-
agent = Agent(
30-
agent_name="MCP Test Agent",
31-
system_prompt=MATH_PROMPT,
32-
mcp_servers=[mcp_server], # Pass as a list of dictionaries
33-
model_name="gpt-4o-mini",
34-
verbose=False # Reduce verbosity to focus on errors
35-
)
36-
37-
print("\nAgent created successfully!")
38-
print("Enter a math query or 'exit' to quit")
39-
40-
# Simple interaction loop
41-
while True:
42-
query = input("\nMath query: ").strip()
43-
if query.lower() == 'exit':
44-
break
45-
46-
# Run the agent
47-
print(f"\nProcessing: {query}")
27+
28+
# Properly configured MCP parameters
29+
mcp_params = MCPServerSseParams(
30+
url="http://127.0.0.1:8000",
31+
headers={
32+
"Content-Type": "application/json",
33+
"Accept": "text/event-stream"
34+
},
35+
timeout=30.0, # Increased timeout
36+
sse_read_timeout=60.0
37+
)
38+
39+
agent = Agent(
40+
agent_name="MCP Test Agent",
41+
system_prompt=SIMPLE_MATH_PROMPT, # Using simpler prompt
42+
mcp_servers=[mcp_params],
43+
model_name="gpt-4o-mini",
44+
max_loops=2, # Allow for retry
45+
verbose=True
46+
)
47+
48+
print("\nAgent created successfully! Type 'exit' to quit.")
49+
while True:
50+
query = input("\nMath query: ").strip()
51+
if query.lower() == "exit":
52+
break
53+
54+
print(f"\nProcessing: {query}")
55+
try:
4856
result = agent.run(query)
49-
50-
# Display result
5157
print(f"\nResult: {result}")
52-
53-
except Exception as e:
54-
logger.error(f"Error: {str(e)}")
55-
import traceback
56-
traceback.print_exc()
57-
58+
except Exception as e:
59+
print(f"\nError processing query: {str(e)}")
5860

5961
if __name__ == "__main__":
60-
main()
62+
main()
+34-64
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,56 @@
11
from fastmcp import FastMCP
22
from loguru import logger
3+
import sys
34
import time
45

5-
# Create the MCP server with all interfaces binding
6+
# Configure detailed logging
7+
logger.remove()
8+
logger.add(sys.stdout, level="DEBUG", format="{time} | {level} | {message}")
9+
10+
# Create MCP server with fixed configuration
611
mcp = FastMCP(
7-
host=
8-
"0.0.0.0", # Bind to all interfaces to be accessible from other contexts
12+
host="127.0.0.1", # Bind to localhost only
913
port=8000,
1014
transport="sse",
1115
require_session_id=False,
12-
cors_allowed_origins=["*"], # Allow all origins for testing
13-
debug=True # Enable debug mode
16+
cors_allowed_origins=["*"],
17+
debug=True
1418
)
1519

16-
17-
# Define tools
20+
# Define tools with proper return format
1821
@mcp.tool()
19-
def add(a: int, b: int) -> str:
20-
"""Add two numbers.
21-
Args:
22-
a (int): First number
23-
b (int): Second number
24-
Returns:
25-
str: A message containing the sum
26-
"""
27-
logger.info(f"Adding {a} and {b}")
22+
def add(a: int, b: int) -> int:
23+
"""Add two numbers."""
2824
result = a + b
29-
return f"The sum of {a} and {b} is {result}"
30-
25+
logger.info(f"Adding {a} + {b} = {result}")
26+
return result # Let FastMCP handle the response formatting
3127

3228
@mcp.tool()
33-
def multiply(a: int, b: int) -> str:
34-
"""Multiply two numbers.
35-
Args:
36-
a (int): First number
37-
b (int): Second number
38-
Returns:
39-
str: A message containing the product
40-
"""
41-
logger.info(f"Multiplying {a} and {b}")
29+
def multiply(a: int, b: int) -> int:
30+
"""Multiply two numbers."""
4231
result = a * b
43-
return f"The product of {a} and {b} is {result}"
44-
32+
logger.info(f"Multiplying {a} * {b} = {result}")
33+
return result
4534

4635
@mcp.tool()
47-
def divide(a: int, b: int) -> str:
48-
"""Divide two numbers.
49-
Args:
50-
a (int): Numerator
51-
b (int): Denominator
52-
Returns:
53-
str: A message containing the division result or an error message
54-
"""
55-
logger.info(f"Dividing {a} by {b}")
36+
def divide(a: int, b: int) -> float:
37+
"""Divide the first number by the second."""
5638
if b == 0:
57-
logger.warning("Division by zero attempted")
58-
return "Cannot divide by zero"
39+
raise ValueError("Cannot divide by zero")
5940
result = a / b
60-
return f"{a} divided by {b} is {result}"
61-
41+
logger.info(f"Dividing {a} / {b} = {result}")
42+
return result
6243

63-
if __name__ == "__main__":
44+
def main():
6445
try:
65-
# Log server details
66-
logger.info("Starting math server on http://0.0.0.0:8000")
67-
print("Math MCP Server is running on http://0.0.0.0:8000")
68-
print("Press Ctrl+C to stop.")
69-
70-
# List available tools
71-
print("\nAvailable tools:")
72-
print("- add: Add two numbers")
73-
print("- multiply: Multiply two numbers")
74-
print("- divide: Divide first number by second number")
75-
76-
# Add a small delay to ensure logging is complete
77-
time.sleep(0.5)
78-
79-
# Run the MCP server
80-
mcp.run()
81-
except KeyboardInterrupt:
82-
logger.info("Server shutdown requested")
83-
print("\nShutting down server...")
46+
logger.info("Starting mock math server on http://127.0.0.1:8000")
47+
print("Math MCP Server running on http://127.0.0.1:8000 (SSE)\n")
48+
print("Available tools:\n - add\n - multiply\n - divide\n")
49+
mcp.run() # This runs the server in a blocking mode
8450
except Exception as e:
85-
logger.error(f"Server error: {e}")
86-
raise
51+
logger.error(f"Error starting server: {e}")
52+
import traceback
53+
traceback.print_exc()
54+
55+
if __name__ == "__main__":
56+
main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import requests
2+
import time
3+
import sys
4+
from loguru import logger
5+
6+
# Configure logger
7+
logger.remove()
8+
logger.add(sys.stdout, level="DEBUG")
9+
10+
def test_server_connection():
11+
"""Simple test to see if server responds at all."""
12+
url = "http://localhost:8000"
13+
14+
try:
15+
logger.debug(f"Testing connection to {url}")
16+
response = requests.get(url)
17+
logger.debug(f"Response status: {response.status_code}")
18+
logger.debug(f"Response content: {response.text[:100]}...")
19+
return True
20+
except Exception as e:
21+
logger.error(f"Connection failed: {str(e)}")
22+
return False
23+
24+
if __name__ == "__main__":
25+
test_server_connection()

swarms/prompts/agent_prompts.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Agent prompts for MCP testing and interactions
22

3-
MATH_PROMPT = """
3+
MATH_AGENT_PROMPT = """
44
You are a math calculator assistant.
55
66
When asked for calculations:

0 commit comments

Comments
 (0)