fix(mcp): update architecture to initialize agents on the client side, not the server

pull/819/head
Pavan Kumar 3 months ago committed by ascender1729
parent 2cdf71e746
commit cc56f433a8

@ -98,4 +98,4 @@ args = "sleep 2"
[[workflows.workflow.tasks]]
task = "shell.exec"
args = "python examples/mcp_example/mock_multi_agent.py"
args = "python examples/mcp_example/mcp_client.py"

@ -1,8 +1,10 @@
from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams
from swarms.prompts.agent_prompts import FINANCE_AGENT_PROMPT, MATH_AGENT_PROMPT
def main():
# Configure MCP server connection
# Configure MCP server connections
math_server = MCPServerSseParams(
url="http://0.0.0.0:8000/mcp",
headers={"Content-Type": "application/json"},
@ -10,40 +12,52 @@ def main():
sse_read_timeout=30.0
)
# Initialize agent with MCP server
agent = Agent(
stock_server = MCPServerSseParams(
url="http://0.0.0.0:8001/mcp",
headers={"Content-Type": "application/json"},
timeout=5.0,
sse_read_timeout=30.0
)
# Initialize math agent
math_agent = Agent(
agent_name="Math Agent",
agent_description="Agent for performing mathematical operations",
system_prompt="""You are a mathematical computation specialist. Use the available MCP server tools to:
- Add numbers
- Multiply numbers
- Divide numbers
Always:
1. Use only tools available from the MCP server
2. Explain your mathematical approach
3. Show your work step by step""",
agent_description="Specialized agent for mathematical computations",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[math_server],
streaming_on=True,
model_name="gpt-4o-mini"
)
print("\nMath Agent initialized with MCP capabilities")
print("Available operations:")
print("- Addition")
print("- Multiplication")
print("- Division")
# Initialize stock agent
stock_agent = Agent(
agent_name="Stock Agent",
agent_description="Specialized agent for stock analysis",
system_prompt=FINANCE_AGENT_PROMPT,
max_loops=1,
mcp_servers=[stock_server],
streaming_on=True,
model_name="gpt-4o-mini"
)
print("\nMulti-Agent System Initialized")
print("\nAvailable operations:")
print("Math Agent: add, multiply, divide")
print("Stock Agent: get stock price, calculate moving average")
while True:
query = input("\nEnter a math problem (or 'exit' to quit): ")
query = input("\nEnter your query (or 'exit' to quit): ")
if query.lower() == 'exit':
break
# Process query through agent
result = agent.run(query)
print("\nResult:", result)
# Process with both agents
math_result = math_agent.run(query)
stock_result = stock_agent.run(query)
print("\nMath Agent Response:", math_result)
print("Stock Agent Response:", stock_result)
if __name__ == "__main__":
main()

@ -1,44 +1,23 @@
from fastmcp import FastMCP
from typing import Dict, Any
import time
# Initialize MCP server
mcp = FastMCP("Math-Mock-Server")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers together"""
try:
print(f"MCP Server: Processing addition request for {a} + {b}")
time.sleep(0.1) # Simulate processing time
result = a + b
print(f"MCP Server: Returning result {result}")
return result
except Exception as e:
error_msg = f"Error adding numbers: {str(e)}"
print(f"MCP Server: {error_msg}")
return {"error": error_msg}
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers together"""
try:
time.sleep(0.1) # Simulate processing time
return a * b
except Exception as e:
return {"error": f"Error multiplying numbers: {str(e)}"}
return a * b
@mcp.tool()
def divide(a: int, b: int) -> float:
"""Divide two numbers"""
try:
if b == 0:
return {"error": "Cannot divide by zero"}
time.sleep(0.1) # Simulate processing time
return a / b
except Exception as e:
return {"error": f"Error dividing numbers: {str(e)}"}
if b == 0:
return {"error": "Cannot divide by zero"}
return a / b
if __name__ == "__main__":
print("Starting Mock Math Server on port 8000...")

@ -2,7 +2,6 @@
from fastmcp import FastMCP
from typing import Dict, Union
# Create FastMCP server
mcp = FastMCP("Stock-Mock-Server")
@mcp.tool()
@ -21,13 +20,8 @@ def get_stock_price(symbol: str) -> Dict[str, Union[float, str]]:
@mcp.tool()
def calculate_moving_average(prices: list[float], window: int) -> Dict[str, Union[list[float], str]]:
"""Calculate moving average of stock prices"""
if not isinstance(prices, list) or not all(isinstance(x, (int, float)) for x in prices):
return {"error": "Invalid price data"}
if not isinstance(window, int) or window <= 0:
return {"error": "Invalid window size"}
if len(prices) < window:
return {"error": "Not enough price points"}
avgs = []
for i in range(len(prices) - window + 1):
avg = sum(prices[i:i+window]) / window
@ -36,4 +30,4 @@ def calculate_moving_average(prices: list[float], window: int) -> Dict[str, Unio
if __name__ == "__main__":
print("Starting Mock Stock Server on port 8001...")
mcp.run(transport="sse", transport_kwargs={"host": "0.0.0.0", "port": 8001})
mcp.run(transport="sse", host="0.0.0.0", port=8001)

Loading…
Cancel
Save