Skip to content

Commit e8912f3

Browse files
committed
updated example
1 parent 51bb308 commit e8912f3

6 files changed

+242
-88
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
=== MINIMAL MCP AGENT INTEGRATION TEST ===
2+
3+
Agent created successfully!
4+
Enter a math query or 'exit' to quit
5+
6+
Math query: add 2 and 2
7+
8+
Processing: add 2 and 2
9+
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
10+
│ MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2} │
11+
╰────────────────────────────────────────────────────────────────────────────────╯
12+
2025-04-21T06:57:50.226670+0000 | ERROR | Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
13+
2025-04-21T06:57:50.226857+0000 | ERROR | Error in abatch_mcp_flow: unhandled errors in a TaskGroup (1 sub-exception)
14+
╭────────── Agent Name MCP Test Agent - Tool Executor [Max Loops: 1 ] ───────────╮
15+
│ MCP Test Agent - Tool Executor: Error in batch operation: unhandled errors in │
16+
│ a TaskGroup (1 sub-exception) │
17+
╰────────────────────────────────────────────────────────────────────────────────╯
18+
╭────────── Agent Name MCP Test Agent - Agent Analysis [Max Loops: 1 ] ──────────╮
19+
│ MCP Test Agent - Agent Analysis: {"tool_name": "add", "a": 1, "b": 1} │
20+
╰────────────────────────────────────────────────────────────────────────────────╯
21+
22+
Result: System: : Your Name: MCP Test Agent
23+
24+
Your Description: None
25+
26+
27+
You are a math calculator assistant.
28+
29+
When asked for calculations:
30+
1. Determine the operation (add, multiply, or divide)
31+
2. Extract the numbers
32+
3. Return the JSON format of the calculation
33+
34+
For example:
35+
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
36+
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
37+
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
38+
39+
When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
40+
41+
42+
43+
Human:: add 2 and 2
44+
45+
46+
MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2}
47+
48+
49+
assistant: Tool execution result: ['Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)']
50+
51+
52+
Tool Executor: Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)
53+
54+
55+
MCP Test Agent: {"tool_name": "add", "a": 1, "b": 1}
56+
57+
58+
59+
Math query:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
=== MINIMAL MCP AGENT INTEGRATION TEST ===
2+
3+
Agent created successfully!
4+
Enter a math query or 'exit' to quit
5+
6+
Math query: add 2 and 2
7+
8+
Processing: add 2 and 2
9+
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
10+
│ MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2} │
11+
╰────────────────────────────────────────────────────────────────────────────────╯
12+
2025-04-21T06:57:50.226670+0000 | ERROR | Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
13+
2025-04-21T06:57:50.226857+0000 | ERROR | Error in abatch_mcp_flow: unhandled errors in a TaskGroup (1 sub-exception)
14+
╭────────── Agent Name MCP Test Agent - Tool Executor [Max Loops: 1 ] ───────────╮
15+
│ MCP Test Agent - Tool Executor: Error in batch operation: unhandled errors in │
16+
│ a TaskGroup (1 sub-exception) │
17+
╰────────────────────────────────────────────────────────────────────────────────╯
18+
╭────────── Agent Name MCP Test Agent - Agent Analysis [Max Loops: 1 ] ──────────╮
19+
│ MCP Test Agent - Agent Analysis: {"tool_name": "add", "a": 1, "b": 1} │
20+
╰────────────────────────────────────────────────────────────────────────────────╯
21+
22+
Result: System: : Your Name: MCP Test Agent
23+
24+
Your Description: None
25+
26+
27+
You are a math calculator assistant.
28+
29+
When asked for calculations:
30+
1. Determine the operation (add, multiply, or divide)
31+
2. Extract the numbers
32+
3. Return the JSON format of the calculation
33+
34+
For example:
35+
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
36+
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
37+
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
38+
39+
When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
40+
41+
42+
43+
Human:: add 2 and 2
44+
45+
46+
MCP Test Agent: {"tool_name": "add", "a": 2, "b": 2}
47+
48+
49+
assistant: Tool execution result: ['Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)']
50+
51+
52+
Tool Executor: Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)
53+
54+
55+
MCP Test Agent: {"tool_name": "add", "a": 1, "b": 1}
56+
57+
58+
59+
Math query:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
=== MINIMAL MCP AGENT INTEGRATION TEST ===
2+
3+
Agent created successfully!
4+
Enter a math query or 'exit' to quit
5+
6+
Math query: add 2 and 3
7+
8+
Processing: add 2 and 3
9+
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
10+
│ MCP Test Agent: {"tool_name": "add", "a": 2, "b": 3} │
11+
╰────────────────────────────────────────────────────────────────────────────────╯
12+
2025-04-21T07:36:01.678279+0000 | ERROR | Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
13+
2025-04-21T07:36:01.678457+0000 | ERROR | Error in abatch_mcp_flow: unhandled errors in a TaskGroup (1 sub-exception)
14+
╭────────── Agent Name MCP Test Agent - Tool Executor [Max Loops: 1 ] ───────────╮
15+
│ MCP Test Agent - Tool Executor: Error in batch operation: unhandled errors in │
16+
│ a TaskGroup (1 sub-exception) │
17+
╰────────────────────────────────────────────────────────────────────────────────╯
18+
╭────────── Agent Name MCP Test Agent - Agent Analysis [Max Loops: 1 ] ──────────╮
19+
│ MCP Test Agent - Agent Analysis: {"tool_name": "add", "a": 1, "b": 1} │
20+
╰────────────────────────────────────────────────────────────────────────────────╯
21+
22+
Result: System: : Your Name: MCP Test Agent
23+
24+
Your Description: None
25+
26+
27+
You are a math calculator assistant.
28+
29+
When asked for calculations:
30+
1. Determine the operation (add, multiply, or divide)
31+
2. Extract the numbers
32+
3. Return the JSON format of the calculation
33+
34+
For example:
35+
- For "add 5 and 3", respond with: {"tool_name": "add", "a": 5, "b": 3}
36+
- For "multiply 7 by 4", respond with: {"tool_name": "multiply", "a": 7, "b": 4}
37+
- For "divide 10 by 2", respond with: {"tool_name": "divide", "a": 10, "b": 2}
38+
39+
When asked about your capabilities, respond with: {"tool_name": "add", "a": 1, "b": 1}
40+
41+
42+
43+
Human:: add 2 and 3
44+
45+
46+
MCP Test Agent: {"tool_name": "add", "a": 2, "b": 3}
47+
48+
49+
assistant: Tool execution result: ['Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)']
50+
51+
52+
Tool Executor: Error in batch operation: unhandled errors in a TaskGroup (1 sub-exception)
53+
54+
55+
MCP Test Agent: {"tool_name": "add", "a": 1, "b": 1}
56+
57+
58+
59+
Math query:

examples/mcp_example/mcp_client.py

+20-38
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,38 @@
11
from swarms import Agent
2-
from swarms.tools.mcp_integration import MCPServerSseParams
32
from loguru import logger
43
import sys
5-
4+
from swarms.prompts.agent_prompts import MATH_PROMPT
65
# Configure logging
76
logger.remove()
8-
logger.add(sys.stdout,
9-
level="INFO",
10-
format="{time} | {level} | {module}:{function}:{line} - {message}")
7+
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")
118

129
# Math prompt for testing MCP integration
13-
MATH_PROMPT = """
14-
You are a math calculator assistant that uses tools to perform calculations.
15-
16-
When asked for calculations, determine the operation and numbers, then use one of these tools:
17-
- add: Add two numbers
18-
- multiply: Multiply two numbers
19-
- divide: Divide first number by second
20-
21-
FORMAT as JSON:
22-
{"tool_name": "add", "a": 5, "b": 10}
23-
"""
2410

2511

2612
def main():
27-
"""Main function to test MCP integration with Agent."""
13+
"""Test MCP integration with Agent."""
2814
print("=== MINIMAL MCP AGENT INTEGRATION TEST ===")
29-
print("Testing only the core MCP integration with Agent")
3015

3116
try:
32-
# Create the server parameters correctly
33-
logger.info("Creating MCP server parameters...")
34-
mcp_server = MCPServerSseParams(
35-
url="http://0.0.0.0:8000",
36-
headers={
17+
# Create the MCP server parameters as a dictionary
18+
mcp_server = {
19+
"url": "http://0.0.0.0:8000",
20+
"headers": {
3721
"Content-Type": "application/json",
3822
"Accept": "text/event-stream"
3923
},
40-
timeout=10.0,
41-
sse_read_timeout=30.0
42-
)
43-
44-
# Log the server params to verify they're correct
45-
logger.info(f"MCP Server URL: {mcp_server.url}")
46-
logger.info("MCP Headers configured")
24+
"timeout": 10.0,
25+
"sse_read_timeout": 30.0
26+
}
4727

4828
# Create agent with minimal configuration
49-
logger.info("Creating Agent with MCP integration...")
5029
agent = Agent(
5130
agent_name="MCP Test Agent",
5231
system_prompt=MATH_PROMPT,
53-
mcp_servers=[mcp_server], # Pass server params object
54-
verbose=True)
32+
mcp_servers=[mcp_server], # Pass as a list of dictionaries
33+
model_name="gpt-4o-mini",
34+
verbose=False # Reduce verbosity to focus on errors
35+
)
5536

5637
print("\nAgent created successfully!")
5738
print("Enter a math query or 'exit' to quit")
@@ -62,17 +43,18 @@ def main():
6243
if query.lower() == 'exit':
6344
break
6445

65-
# Run the agent, which should use the MCP server
66-
logger.info(f"Processing query: {query}")
46+
# Run the agent
47+
print(f"\nProcessing: {query}")
6748
result = agent.run(query)
6849

6950
# Display result
7051
print(f"\nResult: {result}")
7152

7253
except Exception as e:
73-
logger.error(f"Error during MCP integration test: {e}", exc_info=True)
74-
print(f"\nERROR: {type(e).__name__}: {str(e)}")
54+
logger.error(f"Error: {str(e)}")
55+
import traceback
56+
traceback.print_exc()
7557

7658

7759
if __name__ == "__main__":
78-
main()
60+
main()

examples/mcp_example/mock_math_server.py

+35-35
Original file line numberDiff line numberDiff line change
@@ -17,70 +17,70 @@
1717
# Define tools
1818
@mcp.tool()
1919
def add(a: int, b: int) -> str:
20-
"""Add two numbers.
20+
"""Add two numbers.
2121
Args:
2222
a (int): First number
2323
b (int): Second number
2424
Returns:
2525
str: A message containing the sum
2626
"""
27-
logger.info(f"Adding {a} and {b}")
28-
result = a + b
29-
return f"The sum of {a} and {b} is {result}"
27+
logger.info(f"Adding {a} and {b}")
28+
result = a + b
29+
return f"The sum of {a} and {b} is {result}"
3030

3131

3232
@mcp.tool()
3333
def multiply(a: int, b: int) -> str:
34-
"""Multiply two numbers.
34+
"""Multiply two numbers.
3535
Args:
3636
a (int): First number
3737
b (int): Second number
3838
Returns:
3939
str: A message containing the product
4040
"""
41-
logger.info(f"Multiplying {a} and {b}")
42-
result = a * b
43-
return f"The product of {a} and {b} is {result}"
41+
logger.info(f"Multiplying {a} and {b}")
42+
result = a * b
43+
return f"The product of {a} and {b} is {result}"
4444

4545

4646
@mcp.tool()
4747
def divide(a: int, b: int) -> str:
48-
"""Divide two numbers.
48+
"""Divide two numbers.
4949
Args:
5050
a (int): Numerator
5151
b (int): Denominator
5252
Returns:
5353
str: A message containing the division result or an error message
5454
"""
55-
logger.info(f"Dividing {a} by {b}")
56-
if b == 0:
57-
logger.warning("Division by zero attempted")
58-
return "Cannot divide by zero"
59-
result = a / b
60-
return f"{a} divided by {b} is {result}"
55+
logger.info(f"Dividing {a} by {b}")
56+
if b == 0:
57+
logger.warning("Division by zero attempted")
58+
return "Cannot divide by zero"
59+
result = a / b
60+
return f"{a} divided by {b} is {result}"
6161

6262

6363
if __name__ == "__main__":
64-
try:
65-
# Log server details
66-
logger.info("Starting math server on http://0.0.0.0:8000")
67-
print("Math MCP Server is running on http://0.0.0.0:8000")
68-
print("Press Ctrl+C to stop.")
64+
try:
65+
# Log server details
66+
logger.info("Starting math server on http://0.0.0.0:8000")
67+
print("Math MCP Server is running on http://0.0.0.0:8000")
68+
print("Press Ctrl+C to stop.")
6969

70-
# List available tools
71-
print("\nAvailable tools:")
72-
print("- add: Add two numbers")
73-
print("- multiply: Multiply two numbers")
74-
print("- divide: Divide first number by second number")
70+
# List available tools
71+
print("\nAvailable tools:")
72+
print("- add: Add two numbers")
73+
print("- multiply: Multiply two numbers")
74+
print("- divide: Divide first number by second number")
7575

76-
# Add a small delay to ensure logging is complete
77-
time.sleep(0.5)
76+
# Add a small delay to ensure logging is complete
77+
time.sleep(0.5)
7878

79-
# Run the MCP server
80-
mcp.run()
81-
except KeyboardInterrupt:
82-
logger.info("Server shutdown requested")
83-
print("\nShutting down server...")
84-
except Exception as e:
85-
logger.error(f"Server error: {e}")
86-
raise
79+
# Run the MCP server
80+
mcp.run()
81+
except KeyboardInterrupt:
82+
logger.info("Server shutdown requested")
83+
print("\nShutting down server...")
84+
except Exception as e:
85+
logger.error(f"Server error: {e}")
86+
raise

0 commit comments

Comments
 (0)