parent
e8912f3c83
commit
ee9230f819
@ -1,60 +1,62 @@
|
||||
from swarms import Agent
|
||||
from loguru import logger
|
||||
import os
|
||||
import sys
|
||||
from swarms.prompts.agent_prompts import MATH_PROMPT
|
||||
# Configure logging
|
||||
logger.remove()
|
||||
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")
|
||||
from loguru import logger
|
||||
from swarms import Agent
|
||||
from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
|
||||
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():
|
||||
"""Test MCP integration with Agent."""
|
||||
print("=== MINIMAL MCP AGENT INTEGRATION TEST ===")
|
||||
|
||||
try:
|
||||
# Create the MCP server parameters as a dictionary
|
||||
mcp_server = {
|
||||
"url": "http://0.0.0.0:8000",
|
||||
"headers": {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "text/event-stream"
|
||||
},
|
||||
"timeout": 10.0,
|
||||
"sse_read_timeout": 30.0
|
||||
}
|
||||
|
||||
# Create agent with minimal configuration
|
||||
agent = Agent(
|
||||
agent_name="MCP Test Agent",
|
||||
system_prompt=MATH_PROMPT,
|
||||
mcp_servers=[mcp_server], # Pass as a list of dictionaries
|
||||
model_name="gpt-4o-mini",
|
||||
verbose=False # Reduce verbosity to focus on errors
|
||||
)
|
||||
|
||||
print("\nAgent created successfully!")
|
||||
print("Enter a math query or 'exit' to quit")
|
||||
|
||||
# Simple interaction loop
|
||||
while True:
|
||||
query = input("\nMath query: ").strip()
|
||||
if query.lower() == 'exit':
|
||||
break
|
||||
|
||||
# Run the agent
|
||||
print(f"\nProcessing: {query}")
|
||||
# Properly configured MCP parameters
|
||||
mcp_params = MCPServerSseParams(
|
||||
url="http://127.0.0.1:8000",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "text/event-stream"
|
||||
},
|
||||
timeout=30.0, # Increased timeout
|
||||
sse_read_timeout=60.0
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
agent_name="MCP Test Agent",
|
||||
system_prompt=SIMPLE_MATH_PROMPT, # Using simpler prompt
|
||||
mcp_servers=[mcp_params],
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=2, # Allow for retry
|
||||
verbose=True
|
||||
)
|
||||
|
||||
print("\nAgent created successfully! Type 'exit' to quit.")
|
||||
while True:
|
||||
query = input("\nMath query: ").strip()
|
||||
if query.lower() == "exit":
|
||||
break
|
||||
|
||||
print(f"\nProcessing: {query}")
|
||||
try:
|
||||
result = agent.run(query)
|
||||
|
||||
# Display result
|
||||
print(f"\nResult: {result}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nError processing query: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,86 +1,56 @@
|
||||
from fastmcp import FastMCP
|
||||
from loguru import logger
|
||||
import sys
|
||||
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(
|
||||
host=
|
||||
"0.0.0.0", # Bind to all interfaces to be accessible from other contexts
|
||||
host="127.0.0.1", # Bind to localhost only
|
||||
port=8000,
|
||||
transport="sse",
|
||||
require_session_id=False,
|
||||
cors_allowed_origins=["*"], # Allow all origins for testing
|
||||
debug=True # Enable debug mode
|
||||
cors_allowed_origins=["*"],
|
||||
debug=True
|
||||
)
|
||||
|
||||
|
||||
# Define tools
|
||||
# Define tools with proper return format
|
||||
@mcp.tool()
|
||||
def add(a: int, b: int) -> str:
|
||||
"""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}")
|
||||
def add(a: int, b: int) -> int:
|
||||
"""Add two numbers."""
|
||||
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()
|
||||
def multiply(a: int, b: int) -> str:
|
||||
"""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}")
|
||||
def multiply(a: int, b: int) -> int:
|
||||
"""Multiply two numbers."""
|
||||
result = a * b
|
||||
return f"The product of {a} and {b} is {result}"
|
||||
|
||||
logger.info(f"Multiplying {a} * {b} = {result}")
|
||||
return result
|
||||
|
||||
@mcp.tool()
|
||||
def divide(a: int, b: int) -> str:
|
||||
"""Divide two numbers.
|
||||
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}")
|
||||
def divide(a: int, b: int) -> float:
|
||||
"""Divide the first number by the second."""
|
||||
if b == 0:
|
||||
logger.warning("Division by zero attempted")
|
||||
return "Cannot divide by zero"
|
||||
raise ValueError("Cannot divide by zero")
|
||||
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:
|
||||
# Log server details
|
||||
logger.info("Starting math server on http://0.0.0.0:8000")
|
||||
print("Math MCP Server is running on http://0.0.0.0:8000")
|
||||
print("Press Ctrl+C to stop.")
|
||||
|
||||
# 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...")
|
||||
logger.info("Starting mock math server on http://127.0.0.1:8000")
|
||||
print("Math MCP Server running on http://127.0.0.1:8000 (SSE)\n")
|
||||
print("Available tools:\n - add\n - multiply\n - divide\n")
|
||||
mcp.run() # This runs the server in a blocking mode
|
||||
except Exception as e:
|
||||
logger.error(f"Server error: {e}")
|
||||
raise
|
||||
logger.error(f"Error starting server: {e}")
|
||||
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()
|
Loading…
Reference in new issue