updated example

pull/819/head
Pavan Kumar 3 months ago committed by ascender1729
parent 51bb308c45
commit e8912f3c83

@ -0,0 +1,59 @@
=== MINIMAL MCP AGENT INTEGRATION TEST ===
Agent created successfully!
Enter a math query or 'exit' to quit
Math query: add 2 and 2
Processing: add 2 and 2
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
│ MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2} │
╰────────────────────────────────────────────────────────────────────────────────╯
2025-04-21T06:57:50.226670+0000 | ERROR | Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
2025-04-21T06:57:50.226857+0000 | ERROR | Error in abatch_mcp_flow: unhandled errors in a TaskGroup (1 sub-exception)
╭────────── Agent Name MCP Test Agent - Tool Executor [Max Loops: 1 ] ───────────╮
│ MCP Test Agent - Tool Executor: Error in batch operation: unhandled errors in │
│ a TaskGroup (1 sub-exception) │
╰────────────────────────────────────────────────────────────────────────────────╯
╭────────── Agent Name MCP Test Agent - Agent Analysis [Max Loops: 1 ] ──────────╮
│ MCP Test Agent - Agent Analysis: {"tool_name": "add", "a": 1, "b": 1} │
╰────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: MCP Test Agent
Your Description: None
You are a math calculator assistant.
When asked for calculations:
1. Determine the operation (add, multiply, or divide)
2. Extract the numbers
3. Return the JSON format of the calculation
For example:
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
Human:: add 2 and 2
MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2}
assistant: Tool execution result: ['Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)']
Tool Executor: Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)
MCP Test Agent: {"tool_name": "add", "a": 1, "b": 1}
Math query:

@ -0,0 +1,59 @@
=== MINIMAL MCP AGENT INTEGRATION TEST ===
Agent created successfully!
Enter a math query or 'exit' to quit
Math query: add 2 and 2
Processing: add 2 and 2
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
│ MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2} │
╰────────────────────────────────────────────────────────────────────────────────╯
2025-04-21T06:57:50.226670+0000 | ERROR | Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
2025-04-21T06:57:50.226857+0000 | ERROR | Error in abatch_mcp_flow: unhandled errors in a TaskGroup (1 sub-exception)
╭────────── Agent Name MCP Test Agent - Tool Executor [Max Loops: 1 ] ───────────╮
│ MCP Test Agent - Tool Executor: Error in batch operation: unhandled errors in │
│ a TaskGroup (1 sub-exception) │
╰────────────────────────────────────────────────────────────────────────────────╯
╭────────── Agent Name MCP Test Agent - Agent Analysis [Max Loops: 1 ] ──────────╮
│ MCP Test Agent - Agent Analysis: {"tool_name": "add", "a": 1, "b": 1} │
╰────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: MCP Test Agent
Your Description: None
You are a math calculator assistant.
When asked for calculations:
1. Determine the operation (add, multiply, or divide)
2. Extract the numbers
3. Return the JSON format of the calculation
For example:
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
Human:: add 2 and 2
MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2}
assistant: Tool execution result: ['Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)']
Tool Executor: Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)
MCP Test Agent: {"tool_name": "add", "a": 1, "b": 1}
Math query:

@ -0,0 +1,59 @@
=== MINIMAL MCP AGENT INTEGRATION TEST ===
Agent created successfully!
Enter a math query or 'exit' to quit
Math query: add 2 and 3
Processing: add 2 and 3
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
│ MCP Test Agent: {"tool_name": "add", "a": 2, "b": 3} │
╰────────────────────────────────────────────────────────────────────────────────╯
2025-04-21T07:36:01.678279+0000 | ERROR | Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
2025-04-21T07:36:01.678457+0000 | ERROR | Error in abatch_mcp_flow: unhandled errors in a TaskGroup (1 sub-exception)
╭────────── Agent Name MCP Test Agent - Tool Executor [Max Loops: 1 ] ───────────╮
│ MCP Test Agent - Tool Executor: Error in batch operation: unhandled errors in │
│ a TaskGroup (1 sub-exception) │
╰────────────────────────────────────────────────────────────────────────────────╯
╭────────── Agent Name MCP Test Agent - Agent Analysis [Max Loops: 1 ] ──────────╮
│ MCP Test Agent - Agent Analysis: {"tool_name": "add", "a": 1, "b": 1} │
╰────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: MCP Test Agent
Your Description: None
You are a math calculator assistant.
When asked for calculations:
1. Determine the operation (add, multiply, or divide)
2. Extract the numbers
3. Return the JSON format of the calculation
For example:
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
Human:: add 2 and 3
MCP Test Agent: {"tool_name": "add", "a": 2, "b": 3}
assistant: Tool execution result: ['Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)']
Tool Executor: Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)
MCP Test Agent: {"tool_name": "add", "a": 1, "b": 1}
Math query:

@ -1,57 +1,38 @@
from swarms import Agent from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams
from loguru import logger from loguru import logger
import sys import sys
from swarms.prompts.agent_prompts import MATH_PROMPT
# Configure logging # Configure logging
logger.remove() logger.remove()
logger.add(sys.stdout, logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")
level="INFO",
format="{time} | {level} | {module}:{function}:{line} - {message}")
# Math prompt for testing MCP integration # Math prompt for testing MCP integration
MATH_PROMPT = """
You are a math calculator assistant that uses tools to perform calculations.
When asked for calculations, determine the operation and numbers, then use one of these tools:
- add: Add two numbers
- multiply: Multiply two numbers
- divide: Divide first number by second
FORMAT as JSON:
{"tool_name": "add", "a": 5, "b": 10}
"""
def main(): def main():
"""Main function to test MCP integration with Agent.""" """Test MCP integration with Agent."""
print("=== MINIMAL MCP AGENT INTEGRATION TEST ===") print("=== MINIMAL MCP AGENT INTEGRATION TEST ===")
print("Testing only the core MCP integration with Agent")
try: try:
# Create the server parameters correctly # Create the MCP server parameters as a dictionary
logger.info("Creating MCP server parameters...") mcp_server = {
mcp_server = MCPServerSseParams( "url": "http://0.0.0.0:8000",
url="http://0.0.0.0:8000", "headers": {
headers={
"Content-Type": "application/json", "Content-Type": "application/json",
"Accept": "text/event-stream" "Accept": "text/event-stream"
}, },
timeout=10.0, "timeout": 10.0,
sse_read_timeout=30.0 "sse_read_timeout": 30.0
) }
# Log the server params to verify they're correct
logger.info(f"MCP Server URL: {mcp_server.url}")
logger.info("MCP Headers configured")
# Create agent with minimal configuration # Create agent with minimal configuration
logger.info("Creating Agent with MCP integration...")
agent = Agent( agent = Agent(
agent_name="MCP Test Agent", agent_name="MCP Test Agent",
system_prompt=MATH_PROMPT, system_prompt=MATH_PROMPT,
mcp_servers=[mcp_server], # Pass server params object mcp_servers=[mcp_server], # Pass as a list of dictionaries
verbose=True) model_name="gpt-4o-mini",
verbose=False # Reduce verbosity to focus on errors
)
print("\nAgent created successfully!") print("\nAgent created successfully!")
print("Enter a math query or 'exit' to quit") print("Enter a math query or 'exit' to quit")
@ -62,16 +43,17 @@ def main():
if query.lower() == 'exit': if query.lower() == 'exit':
break break
# Run the agent, which should use the MCP server # Run the agent
logger.info(f"Processing query: {query}") print(f"\nProcessing: {query}")
result = agent.run(query) result = agent.run(query)
# Display result # Display result
print(f"\nResult: {result}") print(f"\nResult: {result}")
except Exception as e: except Exception as e:
logger.error(f"Error during MCP integration test: {e}", exc_info=True) logger.error(f"Error: {str(e)}")
print(f"\nERROR: {type(e).__name__}: {str(e)}") import traceback
traceback.print_exc()
if __name__ == "__main__": if __name__ == "__main__":

@ -17,70 +17,70 @@ mcp = FastMCP(
# Define tools # Define tools
@mcp.tool() @mcp.tool()
def add(a: int, b: int) -> str: def add(a: int, b: int) -> str:
"""Add two numbers. """Add two numbers.
Args: Args:
a (int): First number a (int): First number
b (int): Second number b (int): Second number
Returns: Returns:
str: A message containing the sum str: A message containing the sum
""" """
logger.info(f"Adding {a} and {b}") logger.info(f"Adding {a} and {b}")
result = a + b result = a + b
return f"The sum of {a} and {b} is {result}" return f"The sum of {a} and {b} is {result}"
@mcp.tool() @mcp.tool()
def multiply(a: int, b: int) -> str: def multiply(a: int, b: int) -> str:
"""Multiply two numbers. """Multiply two numbers.
Args: Args:
a (int): First number a (int): First number
b (int): Second number b (int): Second number
Returns: Returns:
str: A message containing the product str: A message containing the product
""" """
logger.info(f"Multiplying {a} and {b}") logger.info(f"Multiplying {a} and {b}")
result = a * b result = a * b
return f"The product of {a} and {b} is {result}" return f"The product of {a} and {b} is {result}"
@mcp.tool() @mcp.tool()
def divide(a: int, b: int) -> str: def divide(a: int, b: int) -> str:
"""Divide two numbers. """Divide two numbers.
Args: Args:
a (int): Numerator a (int): Numerator
b (int): Denominator b (int): Denominator
Returns: Returns:
str: A message containing the division result or an error message str: A message containing the division result or an error message
""" """
logger.info(f"Dividing {a} by {b}") logger.info(f"Dividing {a} by {b}")
if b == 0: if b == 0:
logger.warning("Division by zero attempted") logger.warning("Division by zero attempted")
return "Cannot divide by zero" return "Cannot divide by zero"
result = a / b result = a / b
return f"{a} divided by {b} is {result}" return f"{a} divided by {b} is {result}"
if __name__ == "__main__": if __name__ == "__main__":
try: try:
# Log server details # Log server details
logger.info("Starting math server on http://0.0.0.0:8000") 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("Math MCP Server is running on http://0.0.0.0:8000")
print("Press Ctrl+C to stop.") print("Press Ctrl+C to stop.")
# List available tools # List available tools
print("\nAvailable tools:") print("\nAvailable tools:")
print("- add: Add two numbers") print("- add: Add two numbers")
print("- multiply: Multiply two numbers") print("- multiply: Multiply two numbers")
print("- divide: Divide first number by second number") print("- divide: Divide first number by second number")
# Add a small delay to ensure logging is complete # Add a small delay to ensure logging is complete
time.sleep(0.5) time.sleep(0.5)
# Run the MCP server # Run the MCP server
mcp.run() mcp.run()
except KeyboardInterrupt: except KeyboardInterrupt:
logger.info("Server shutdown requested") logger.info("Server shutdown requested")
print("\nShutting down server...") print("\nShutting down server...")
except Exception as e: except Exception as e:
logger.error(f"Server error: {e}") logger.error(f"Server error: {e}")
raise raise

@ -1,24 +1,19 @@
# Agent prompts for MCP testing and interactions # Agent prompts for MCP testing and interactions
MATH_AGENT_PROMPT = """ MATH_PROMPT = """
You are a helpful math calculator assistant. You are a math calculator assistant.
Your role is to understand natural language math requests and perform calculations.
When asked to perform calculations:
When asked for calculations:
1. Determine the operation (add, multiply, or divide) 1. Determine the operation (add, multiply, or divide)
2. Extract the numbers from the request 2. Extract the numbers
3. Call the appropriate operation 3. Return the JSON format of the calculation
You can use these tools:
- add: Add two numbers together
- multiply: Multiply two numbers together
- divide: Divide the first number by the second number
If the user asks for a list of available tools or functions, tell them about the above operations. For example:
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
Just tell me which operation to perform and what numbers to use in natural language. When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
No need for strict JSON formatting - I'll handle the tool calling for you.
""" """
FINANCE_AGENT_PROMPT = """You are a financial analysis agent with access to stock market data services. FINANCE_AGENT_PROMPT = """You are a financial analysis agent with access to stock market data services.
Key responsibilities: Key responsibilities:

Loading…
Cancel
Save