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]] [[workflows.workflow.tasks]]
task = "shell.exec" task = "shell.exec"
args = "python examples/mcp_example/mock_multi_agent.py" args = "python examples/mcp_example/mcp_client.py"

@ -1,49 +1,63 @@
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 FINANCE_AGENT_PROMPT, MATH_AGENT_PROMPT
def main(): def main():
# Configure MCP server connection # Configure MCP server connections
math_server = MCPServerSseParams( math_server = MCPServerSseParams(
url="http://0.0.0.0:8000/mcp", url="http://0.0.0.0:8000/mcp",
headers={"Content-Type": "application/json"}, headers={"Content-Type": "application/json"},
timeout=5.0, timeout=5.0,
sse_read_timeout=30.0
)
stock_server = MCPServerSseParams(
url="http://0.0.0.0:8001/mcp",
headers={"Content-Type": "application/json"},
timeout=5.0,
sse_read_timeout=30.0 sse_read_timeout=30.0
) )
# Initialize agent with MCP server # Initialize math agent
agent = Agent( math_agent = Agent(
agent_name="Math Agent", agent_name="Math Agent",
agent_description="Agent for performing mathematical operations", agent_description="Specialized agent for mathematical computations",
system_prompt="""You are a mathematical computation specialist. Use the available MCP server tools to: system_prompt=MATH_AGENT_PROMPT,
- 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""",
max_loops=1, max_loops=1,
mcp_servers=[math_server], mcp_servers=[math_server],
streaming_on=True, streaming_on=True,
model_name="gpt-4o-mini" model_name="gpt-4o-mini"
) )
print("\nMath Agent initialized with MCP capabilities") # Initialize stock agent
print("Available operations:") stock_agent = Agent(
print("- Addition") agent_name="Stock Agent",
print("- Multiplication") agent_description="Specialized agent for stock analysis",
print("- Division") system_prompt=FINANCE_AGENT_PROMPT,
max_loops=1,
mcp_servers=[stock_server],
streaming_on=True,
model_name="gpt-4o-mini"
)
while True: print("\nMulti-Agent System Initialized")
query = input("\nEnter a math problem (or 'exit' to quit): ") print("\nAvailable operations:")
print("Math Agent: add, multiply, divide")
print("Stock Agent: get stock price, calculate moving average")
while True:
query = input("\nEnter your query (or 'exit' to quit): ")
if query.lower() == 'exit': if query.lower() == 'exit':
break break
# Process query through agent # Process with both agents
result = agent.run(query) math_result = math_agent.run(query)
print("\nResult:", result) stock_result = stock_agent.run(query)
print("\nMath Agent Response:", math_result)
print("Stock Agent Response:", stock_result)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

@ -1,45 +1,24 @@
from fastmcp import FastMCP from fastmcp import FastMCP
from typing import Dict, Any
import time
# Initialize MCP server
mcp = FastMCP("Math-Mock-Server") mcp = FastMCP("Math-Mock-Server")
@mcp.tool() @mcp.tool()
def add(a: int, b: int) -> int: def add(a: int, b: int) -> int:
"""Add two numbers together""" """Add two numbers together"""
try: return a + b
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}
@mcp.tool() @mcp.tool()
def multiply(a: int, b: int) -> int: def multiply(a: int, b: int) -> int:
"""Multiply two numbers together""" """Multiply two numbers together"""
try: return a * b
time.sleep(0.1) # Simulate processing time
return a * b
except Exception as e:
return {"error": f"Error multiplying numbers: {str(e)}"}
@mcp.tool() @mcp.tool()
def divide(a: int, b: int) -> float: def divide(a: int, b: int) -> float:
"""Divide two numbers""" """Divide two numbers"""
try: if b == 0:
if b == 0: return {"error": "Cannot divide by zero"}
return {"error": "Cannot divide by zero"} return a / b
time.sleep(0.1) # Simulate processing time
return a / b
except Exception as e:
return {"error": f"Error dividing numbers: {str(e)}"}
if __name__ == "__main__": if __name__ == "__main__":
print("Starting Mock Math Server on port 8000...") print("Starting Mock Math Server on port 8000...")
mcp.run(transport="sse", host="0.0.0.0", port=8000) mcp.run(transport="sse", host="0.0.0.0", port=8000)

@ -2,7 +2,6 @@
from fastmcp import FastMCP from fastmcp import FastMCP
from typing import Dict, Union from typing import Dict, Union
# Create FastMCP server
mcp = FastMCP("Stock-Mock-Server") mcp = FastMCP("Stock-Mock-Server")
@mcp.tool() @mcp.tool()
@ -21,13 +20,8 @@ def get_stock_price(symbol: str) -> Dict[str, Union[float, str]]:
@mcp.tool() @mcp.tool()
def calculate_moving_average(prices: list[float], window: int) -> Dict[str, Union[list[float], str]]: def calculate_moving_average(prices: list[float], window: int) -> Dict[str, Union[list[float], str]]:
"""Calculate moving average of stock prices""" """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: if len(prices) < window:
return {"error": "Not enough price points"} return {"error": "Not enough price points"}
avgs = [] avgs = []
for i in range(len(prices) - window + 1): for i in range(len(prices) - window + 1):
avg = sum(prices[i:i+window]) / window 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__": if __name__ == "__main__":
print("Starting Mock Stock Server on port 8001...") 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