chore(mcp): update server/client implementations and configure workflows

pull/819/head
Pavan Kumar 3 months ago committed by ascender1729
parent d75bbed8ee
commit 1a84b24394

@ -15,3 +15,24 @@ mode = "sequential"
[[workflows.workflow.tasks]] [[workflows.workflow.tasks]]
task = "shell.exec" task = "shell.exec"
args = "python -m unittest tests/test_basic_example.py -v" args = "python -m unittest tests/test_basic_example.py -v"
[[workflows.workflow.tasks]]
task = "shell.exec"
args = "python -m unittest tests/tools/test_mcp_integration.py -v"
[[workflows.workflow]]
name = "Run MCP Demo"
author = 13983571
mode = "sequential"
[[workflows.workflow.tasks]]
task = "shell.exec"
args = "python examples/mcp_example/mock_math_server.py & "
[[workflows.workflow.tasks]]
task = "shell.exec"
args = "sleep 2"
[[workflows.workflow.tasks]]
task = "shell.exec"
args = "python examples/mcp_example/mcp_client.py"

@ -1,62 +1,35 @@
import os
from swarms import Agent from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams from swarms.tools.mcp_integration import MCPServerSseParams
from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
from loguru import logger from loguru import logger
# Set OpenAI API key
def initialize_math_system(): def initialize_math_system():
"""Initialize the math agent with MCP server configuration.""" """Initialize the math agent with MCP server configuration."""
# Configure MCP server connection with SSE transport
math_server = MCPServerSseParams( math_server = MCPServerSseParams(
url="http://localhost:8000", url="http://0.0.0.0:8000",
headers={ headers={"Content-Type": "application/json"},
"Content-Type": "application/json",
"Accept": "text/event-stream"
},
timeout=5.0, timeout=5.0,
sse_read_timeout=30.0) sse_read_timeout=30.0
)
# Initialize math agent with specific model
math_agent = Agent( math_agent = Agent(
agent_name="Math Agent", agent_name="Math Agent",
agent_description="Basic math calculator", agent_description="Basic math calculator",
system_prompt=MATH_AGENT_PROMPT, system_prompt=MATH_AGENT_PROMPT,
max_loops=1, max_loops=1,
mcp_servers=[math_server], mcp_servers=[math_server]
streaming_on=False, )
model_name="gpt-4o-mini",
temperature=0.1)
return math_agent return math_agent
def process_query(math_agent, query):
"""Process a single math query."""
try:
result = math_agent.run(query)
# Clean up the result to show only the number or error message
if isinstance(result, (int, float)):
return result
elif "error" in result.lower():
return result
else:
# Try to extract just the number from the result
try:
return float(result)
except:
return "Error: Invalid result format"
except Exception as e:
return f"Error: {str(e)}"
def main(): def main():
# Initialize the math system
math_agent = initialize_math_system() math_agent = initialize_math_system()
print("\nMath Calculator Ready!") print("\nMath Calculator Ready!")
print("Available operations: add, multiply, divide") print("Available operations: add, multiply, divide")
print("Example: 'add 5 and 3' or 'multiply 4 by 6'") print("Example: 'add 5 and 3' or 'multiply 4 by 6'")
print("Type 'exit' to quit\n") print("Type 'exit' to quit\n")
while True: while True:
try: try:
query = input("Enter math operation: ").strip() query = input("Enter math operation: ").strip()
@ -65,14 +38,14 @@ def main():
if query.lower() == 'exit': if query.lower() == 'exit':
break break
result = process_query(math_agent, query) result = math_agent.run(query)
print(f"Result: {result}") print(f"Result: {result}")
except KeyboardInterrupt: except KeyboardInterrupt:
print("\nExiting...") print("\nExiting...")
break break
except Exception as e: except Exception as e:
print(f"Error: {e}") logger.error(f"Error: {e}")
if __name__ == "__main__": if __name__ == "__main__":
main() main()

@ -1,11 +1,8 @@
from fastmcp import FastMCP from fastmcp import FastMCP
from typing import Dict, Any
import asyncio
from loguru import logger from loguru import logger
# Create FastMCP instance with SSE transport
mcp = FastMCP( mcp = FastMCP(
host="0.0.0.0", host="0.0.0.0",
port=8000, port=8000,
transport="sse", transport="sse",
require_session_id=False, require_session_id=False,
@ -17,7 +14,7 @@ def add(a: int, b: int) -> int:
"""Add two numbers.""" """Add two numbers."""
return a + b return a + b
@mcp.tool() @mcp.tool()
def multiply(a: int, b: int) -> int: def multiply(a: int, b: int) -> int:
"""Multiply two numbers.""" """Multiply two numbers."""
return a * b return a * b
@ -29,22 +26,10 @@ def divide(a: int, b: int) -> float:
raise ValueError("Cannot divide by zero") raise ValueError("Cannot divide by zero")
return a / b return a / b
async def run_server(): if __name__ == "__main__":
"""Run the server with proper error handling."""
try: try:
logger.info("Starting math server on http://0.0.0.0:8000") logger.info("Starting math server on http://0.0.0.0:8000")
await mcp.run_async() mcp.run()
except Exception as e: except Exception as e:
logger.error(f"Server error: {e}") logger.error(f"Server error: {e}")
raise raise
finally:
await mcp.cleanup()
if __name__ == "__main__":
try:
asyncio.run(run_server())
except KeyboardInterrupt:
logger.info("Server stopped by user")
except Exception as e:
logger.error(f"Fatal error: {e}")
raise
Loading…
Cancel
Save