Delete attached_assets directory

pull/819/head
Pavan Kumar 3 months ago committed by GitHub
parent 1a96821024
commit 3aad5acb6f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -1,110 +0,0 @@
# Browserbase MCP Server
![cover](../assets/browserbase-mcp.png)
## Get Started
1. Run `npm install` to install the necessary dependencies, then run `npm run build` to get `dist/index.js`.
2. Set up your Claude Desktop configuration to use the server.
```json
{
"mcpServers": {
"browserbase": {
"command": "node",
"args": ["path/to/mcp-server-browserbase/browserbase/dist/index.js"],
"env": {
"BROWSERBASE_API_KEY": "<YOUR_BROWSERBASE_API_KEY>",
"BROWSERBASE_PROJECT_ID": "<YOUR_BROWSERBASE_PROJECT_ID>"
}
}
}
}
```
3. Restart your Claude Desktop app and you should see the tools available clicking the 🔨 icon.
4. Start using the tools! Below is an image of Claude closing a browser session.
<p align="center">
<img src="../assets/browserbase-demo.png" alt="demo" width="600"/>
</p>
## Tools
### Browserbase API
- **browserbase_create_session**
- Create a new cloud browser session using Browserbase
- No required inputs
- **browserbase_navigate**
- Navigate to any URL in the browser
- Input: `url` (string)
- **browserbase_screenshot**
- Capture screenshots of the entire page or specific elements
- Inputs:
- `name` (string, required): Name for the screenshot
- `selector` (string, optional): CSS selector for element to screenshot
- `width` (number, optional, default: 800): Screenshot width
- `height` (number, optional, default: 600): Screenshot height
- **browserbase_click**
- Click elements on the page
- Input: `selector` (string): CSS selector for element to click
- **browserbase_fill**
- Fill out input fields
- Inputs:
- `selector` (string): CSS selector for input field
- `value` (string): Value to fill
- **browserbase_evaluate**
- Execute JavaScript in the browser console
- Input: `script` (string): JavaScript code to execute
- **browserbase_get_content**
- Extract all content from the current page
- Input: `selector` (string, optional): CSS selector to get content from specific elements
- **browserbase_parallel_sessions**
- Create multiple browser sessions and navigate to different URLs
- Input: `sessions` (array): Array of objects containing:
- `url` (string): URL to navigate to
- `id` (string): Session identifier
### Resources
The server provides access to two types of resources:
1. **Console Logs** (`console://logs`)
- Browser console output in text format
- Includes all console messages from the browser
2. **Screenshots** (`screenshot://<name>`)
- PNG images of captured screenshots
- Accessible via the screenshot name specified during capture
## Key Features
- Cloud browser automation
- Web data extraction
- Console log monitoring
- Screenshot capabilities
- JavaScript execution
- Basic web interaction (navigation, clicking, form filling)
## License
This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.

@ -1,59 +0,0 @@
=== 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:

@ -1,59 +0,0 @@
=== 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:

@ -1,59 +0,0 @@
=== 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,66 +0,0 @@
=== MINIMAL MCP AGENT INTEGRATION TEST ===
Testing only the core MCP integration with Agent
2025-04-20T18:19:47.080439+0000 | INFO | mcp_client:main:33 - Creating MCP server parameters...
2025-04-20T18:19:47.080601+0000 | INFO | mcp_client:main:45 - MCP Server URL: http://0.0.0.0:8000
2025-04-20T18:19:47.080686+0000 | INFO | mcp_client:main:46 - MCP Headers: {'Content-Type': 'application/json', 'Accept': 'text/event-stream'}
2025-04-20T18:19:47.080763+0000 | INFO | mcp_client:main:49 - Creating Agent with MCP integration...
2025-04-20T18:19:47.088927+0000 | WARNING | agent:llm_handling:613 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Agent created successfully!
Enter a math query or 'exit' to quit
Math query: what tools you have?
2025-04-20T18:20:39.747943+0000 | INFO | mcp_client:main:66 - Processing query: what tools you have?
╭────────────────── Agent Name MCP Test Agent [Max Loops: 1 ] ───────────────────╮
│ MCP Test Agent: {"tool_name": "none", "description": "I can perform addition, │
│ multiplication, and division using specific tools."} │
╰────────────────────────────────────────────────────────────────────────────────╯
2025-04-20T18:20:41.073474+0000 | ERROR | mcp_integration:connect:89 - Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
2025-04-20T18:20:41.073628+0000 | ERROR | mcp_integration:abatch_mcp_flow:268 - 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: It seems like you're encountering an error │
│ related to a batch operation in a programming or data processing context. │
│ However, I can assist you with mathematical calculations. If you have any │
│ specific calculations you'd like to perform, please provide the numbers and │
│ the operation (addition, multiplication, or division), and I'll format it as │
│ JSON for you. │
╰────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: MCP Test Agent
Your Description: None
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}
Human:: what tools you have?
MCP Test Agent: {"tool_name": "none", "description": "I can perform addition, multiplication, and division using specific tools."}
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: It seems like you're encountering an error related to a batch operation in a programming or data processing context. However, I can assist you with mathematical calculations. If you have any specific calculations you'd like to perform, please provide the numbers and the operation (addition, multiplication, or division), and I'll format it as JSON for you.
Math query:

@ -1,50 +0,0 @@
Math Agent System Initialized
Available operations:
2025-04-20 10:41:14 | WARNING | swarms.structs.agent:llm_handling:646 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Math Agent: add, multiply, divide
Enter your query (or 'exit' to quit): add 8 and 11
╭─────────────────────────────────────────────────────── Agent Name: Math Agent [Max Loops: 1] ───────────────────────────────────────────────────────╮
│ Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7ff74f418e20> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 10:44:25 | ERROR | swarms.structs.agent:_run:1147 - Attempt 1: Error generating response: 'Agent' object has no attribute 'mcp_execution_flow'
╭─────────────────────────────────────────────────────── Agent Name: Math Agent [Max Loops: 1] ───────────────────────────────────────────────────────╮
│ Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7ff74f3d2950> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 10:44:27 | ERROR | swarms.structs.agent:_run:1147 - Attempt 2: Error generating response: 'Agent' object has no attribute 'mcp_execution_flow'
╭─────────────────────────────────────────────────────── Agent Name: Math Agent [Max Loops: 1] ───────────────────────────────────────────────────────╮
│ Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7ff74f3d22c0> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 10:44:29 | ERROR | swarms.structs.agent:_run:1147 - Attempt 3: Error generating response: 'Agent' object has no attribute 'mcp_execution_flow'
2025-04-20 10:44:29 | ERROR | swarms.structs.agent:_run:1160 - Failed to generate a valid response after retry attempts.
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
Human:: add 8 and 11
Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7ff74f418e20>
Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7ff74f3d2950>
Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7ff74f3d22c0>
Enter your query (or 'exit' to quit):

@ -1,47 +0,0 @@
Math Agent System Initialized
Available operations:2025-04-20 11:05:16 | WARNING | swarms.structs.agent:llm_handling:646 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Math Agent: add, multiply, divide
Enter your query (or 'exit' to quit): add 2 and 4
╭─────────────────────────────────────────────────────── Agent Name: Math Agent [Max Loops: 1] ───────────────────────────────────────────────────────╮
│ Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7fb9d6ddcdf0> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:05:28 | ERROR | swarms.structs.agent:mcp_execution_flow:2807 - MCP flow failed: Expecting value: line 1 column 1 (char 0)
╭─────────────────────────────────────────────── Agent Name: Math Agent - Tool Executor [Max Loops: 1] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: [MCP-error] Expecting value: line 1 column 1 (char 0) │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭────────────────────────────────────────────── Agent Name: Math Agent - Agent Analysis [Max Loops: 1] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7fb9d6e14d30> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
Human:: add 2 and 4
Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7fb9d6ddcdf0>
Tool Executor: [MCP-error] Expecting value: line 1 column 1 (char 0)
Math Agent: <litellm.litellm_core_utils.streaming_handler.CustomStreamWrapper object at 0x7fb9d6e14d30>
Enter your query (or 'exit' to quit):

@ -1,118 +0,0 @@
Math Agent System Initialized
Available operations:
2025-04-20 11:08:41 | WARNING | swarms.structs.agent:llm_handling:646 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Math Agent: add, multiply, divide
Enter your query (or 'exit' to quit): add 2 and 3
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 2, "b": 3} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
/home/runner/workspace/swarms/structs/agent.py:1110: RuntimeWarning: coroutine 'batch_mcp_flow' was never awaited
out = self.mcp_execution_flow(response)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: <coroutine object batch_mcp_flow at 0x7fd18ec950e0> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems like you've provided a reference to a coroutine object, which is not a mathematical query. Please provide a │
│ specific mathematical question or operation you'd like me to assist you with, and I'll be happy to help! │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 2 and 3
Math Agent: {"tool_name": "add", "a": 2, "b": 3}
Tool Executor: <coroutine object batch_mcp_flow at 0x7fd18ec950e0>
Math Agent: It seems like you've provided a reference to a coroutine object, which is not a mathematical query. Please provide a specific mathematical question or operation you'd like me to assist you with, and I'll be happy to help!
Enter your query (or 'exit' to quit): waht tools you have
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: I have access to three mathematical tools that can perform basic operations: │
│ │
│ 1. **Add**: To calculate the sum of two numbers. │
│ 2. **Multiply**: To calculate the product of two numbers. │
│ 3. **Divide**: To calculate the quotient of two numbers. │
│ │
│ If you have a specific mathematical operation or question in mind, please let me know, and I'll assist you with it! │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: [MCP-error] Expecting value: line 1 column 1 (char 0) │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:09:41 | ERROR | swarms.structs.agent:mcp_execution_flow:2807 - MCP flow failed: Expecting value: line 1 column 1 (char 0)
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems there was an error with the math service. Please provide me with a mathematical query or operation you'd like │
│ to perform, and I'll assist you with it. │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 2 and 3
Math Agent: {"tool_name": "add", "a": 2, "b": 3}
Tool Executor: <coroutine object batch_mcp_flow at 0x7fd18ec950e0>
Math Agent: It seems like you've provided a reference to a coroutine object, which is not a mathematical query. Please provide a specific mathematical question or operation you'd like me to assist you with, and I'll be happy to help!
Human:: waht tools you have
Math Agent: I have access to three mathematical tools that can perform basic operations:
1. **Add**: To calculate the sum of two numbers.
2. **Multiply**: To calculate the product of two numbers.
3. **Divide**: To calculate the quotient of two numbers.
If you have a specific mathematical operation or question in mind, please let me know, and I'll assist you with it!
Tool Executor: [MCP-error] Expecting value: line 1 column 1 (char 0)
Math Agent: It seems there was an error with the math service. Please provide me with a mathematical query or operation you'd like to perform, and I'll assist you with it.
Enter your query (or 'exit' to quit):

@ -1,52 +0,0 @@
Math Agent System Initialized
Available operations:
Math Agent: add, multiply, divide
2025-04-20 11:29:58 | WARNING | swarms.structs.agent:llm_handling:647 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Enter your query (or 'exit' to quit): add 4 and 19834
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 4, "b": 19834} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
/home/runner/workspace/swarms/structs/agent.py:1111: RuntimeWarning: coroutine 'batch_mcp_flow' was never awaited
out = self.mcp_execution_flow(response)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: <coroutine object batch_mcp_flow at 0x7f79d6fc14d0> │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems like you've provided a reference to a coroutine object, which is not a mathematical query. Please provide a │
│ specific mathematical question or operation you'd like me to assist with, and I'll be happy to help! │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 4 and 19834
Math Agent: {"tool_name": "add", "a": 4, "b": 19834}
Tool Executor: <coroutine object batch_mcp_flow at 0x7f79d6fc14d0>
Math Agent: It seems like you've provided a reference to a coroutine object, which is not a mathematical query. Please provide a specific mathematical question or operation you'd like me to assist with, and I'll be happy to help!
Enter your query (or 'exit' to quit):

@ -1,50 +0,0 @@
Math Agent System Initialized
Available operations:
Math Agent: add, multiply, divide
2025-04-20 11:32:54 | WARNING | swarms.structs.agent:llm_handling:647 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Enter your query (or 'exit' to quit): add 343 and 33
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 343, "b": 33} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: [] │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:33:03 | ERROR | swarms.tools.mcp_integration:process_param:360 - Error processing parameter: {'url': 'http://0.0.0.0:8000', 'headers': {'Content-Type': 'application/json'}, 'timeout': 5.0, 'sse_read_timeout': 30.0}, error: __aenter__
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation │
│ you'd like assistance with? │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 343 and 33
Math Agent: {"tool_name": "add", "a": 343, "b": 33}
Tool Executor: []
Math Agent: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation you'd like assistance with?
Enter your query (or 'exit' to quit):

@ -1,50 +0,0 @@
Math Agent System Initialized
Available operations:
Math Agent: add, multiply, divide
2025-04-20 11:32:54 | WARNING | swarms.structs.agent:llm_handling:647 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Enter your query (or 'exit' to quit): add 343 and 33
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 343, "b": 33} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: [] │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:33:03 | ERROR | swarms.tools.mcp_integration:process_param:360 - Error processing parameter: {'url': 'http://0.0.0.0:8000', 'headers': {'Content-Type': 'application/json'}, 'timeout': 5.0, 'sse_read_timeout': 30.0}, error: __aenter__
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation │
│ you'd like assistance with? │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 343 and 33
Math Agent: {"tool_name": "add", "a": 343, "b": 33}
Tool Executor: []
Math Agent: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation you'd like assistance with?
Enter your query (or 'exit' to quit):

@ -1,50 +0,0 @@
Math Agent System Initialized
Available operations:
Math Agent: add, multiply, divide
2025-04-20 11:32:54 | WARNING | swarms.structs.agent:llm_handling:647 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Enter your query (or 'exit' to quit): add 343 and 33
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 343, "b": 33} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: [] │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:33:03 | ERROR | swarms.tools.mcp_integration:process_param:360 - Error processing parameter: {'url': 'http://0.0.0.0:8000', 'headers': {'Content-Type': 'application/json'}, 'timeout': 5.0, 'sse_read_timeout': 30.0}, error: __aenter__
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation │
│ you'd like assistance with? │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 343 and 33
Math Agent: {"tool_name": "add", "a": 343, "b": 33}
Tool Executor: []
Math Agent: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation you'd like assistance with?
Enter your query (or 'exit' to quit):

@ -1,50 +0,0 @@
Math Agent System Initialized
Available operations:
Math Agent: add, multiply, divide
2025-04-20 11:32:54 | WARNING | swarms.structs.agent:llm_handling:647 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Enter your query (or 'exit' to quit): add 343 and 33
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 343, "b": 33} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: [] │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:33:03 | ERROR | swarms.tools.mcp_integration:process_param:360 - Error processing parameter: {'url': 'http://0.0.0.0:8000', 'headers': {'Content-Type': 'application/json'}, 'timeout': 5.0, 'sse_read_timeout': 30.0}, error: __aenter__
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation │
│ you'd like assistance with? │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: add 343 and 33
Math Agent: {"tool_name": "add", "a": 343, "b": 33}
Tool Executor: []
Math Agent: It seems like your message is empty or unclear. Could you please provide a specific mathematical query or operation you'd like assistance with?
Enter your query (or 'exit' to quit):

@ -1,54 +0,0 @@
Math Agent System Initialized
Available operations:
Math Agent: add, multiply, divide
2025-04-20 11:34:49 | WARNING | swarms.structs.agent:llm_handling:647 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
Enter your query (or 'exit' to quit): AD D4 AND 5
╭─────────────────────────────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ───────────────────────────────────────────────────────╮
│ Math Agent: It seems like you want to add the numbers 4 and 5 together. I will use the addition tool to perform this calculation. │
│ │
│ {"tool_name": "add", "a": 4, "b": 5} │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 11:34:55 | ERROR | swarms.tools.mcp_integration:process_param:360 - Error processing parameter: {'url': 'http://0.0.0.0:8000', 'headers': {'Content-Type': 'application/json'}, 'timeout': 5.0, 'sse_read_timeout': 30.0}, error: __aenter__
╭─────────────────────────────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Tool Executor: No result returned from MCP server │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭────────────────────────────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────────────────────────────╮
│ Math Agent - Agent Analysis: It seems there was an issue with the MCP server not returning a result. Please provide me with a mathematical query or │
│ operation you'd like to perform, and I'll attempt to process it again. │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Math Agent Response: System: : Your Name: Math Agent
Your Description: Specialized agent for mathematical computations
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Remember to use the available MCP tools for calculations rather than doing them directly.
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
Human:: AD D4 AND 5
Math Agent: It seems like you want to add the numbers 4 and 5 together. I will use the addition tool to perform this calculation.
{"tool_name": "add", "a": 4, "b": 5}
Tool Executor: No result returned from MCP server
Math Agent: It seems there was an issue with the MCP server not returning a result. Please provide me with a mathematical query or operation you'd like to perform, and I'll attempt to process it again.
Enter your query (or 'exit' to quit):

@ -1,63 +0,0 @@
Math Calculator Ready!
Ask me any math question!
Examples: 'what is 5 plus 3?' or 'can you multiply 4 and 6?'
Type 'exit' to quit
What would you like to calculate? add 4 and 4
╭───────────────────────────── Agent Name Math Assistant [Max Loops: 1 ] ──────────────────────────────╮
│ Math Assistant: Using the add operation for 4 and 4 │
│ {"tool_name": "add", "a": 4, "b": 4} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 16:14:49 | ERROR | swarms.structs.agent:mcp_execution_flow:2697 - Error executing tool call: a coroutine was expected, got <_GatheringFuture pending>
╭───────────────────── Agent Name Math Assistant - Tool Executor [Max Loops: 1 ] ──────────────────────╮
│ Math Assistant - Tool Executor: Error executing tool call: a coroutine was expected, got │
│ <_GatheringFuture pending> │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭───────────────────── Agent Name Math Assistant - Agent Analysis [Max Loops: 1 ] ─────────────────────╮
│ Math Assistant - Agent Analysis: I'm here to help with math calculations. What would you like me to │
│ calculate for you? │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: Math Assistant
Your Description: Friendly math calculator
You are a helpful math calculator assistant.
Your role is to understand natural language math requests and perform calculations.
When asked to perform calculations:
1. Determine the operation (add, multiply, or divide)
2. Extract the numbers from the request
3. Use the appropriate math operation tool
Respond conversationally but be concise.
Example:
User: "what is 5 plus 3?"
You: Using the add operation for 5 and 3
{"tool_name": "add", "a": 5, "b": 3}
User: "multiply 4 times 6"
You: Using multiply for 4 and 6
{"tool_name": "multiply", "a": 4, "b": 6}
Human:: add 4 and 4
Math Assistant: Using the add operation for 4 and 4
{"tool_name": "add", "a": 4, "b": 4}
error: Error executing tool call: a coroutine was expected, got <_GatheringFuture pending>
Tool Executor: Error executing tool call: a coroutine was expected, got <_GatheringFuture pending>
Math Assistant: I'm here to help with math calculations. What would you like me to calculate for you?
What would you like to calculate?

@ -1,62 +0,0 @@
Math Calculator Ready!
Available operations: add, multiply, divide
Example: 'add 5 and 3' or 'multiply 4 by 6'
Type 'exit' to quit
Enter math operation: add 3 and334
╭─────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 3, "b": 334} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 15:54:35 | ERROR | swarms.tools.mcp_integration:_call_one_server:475 - Error calling server: ClientSession.__init__() missing 2 required positional arguments: 'read_stream' and 'write_stream'
╭─────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ────────────────────────╮
│ Math Agent - Tool Executor: No result from tool execution │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────╮
│ Math Agent - Agent Analysis: {"error": "No result from tool execution"} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: Math Agent
Your Description: Basic math calculator
You are a specialized math agent that can perform calculations by calling external math service APIs.
Key responsibilities:
1. Understand mathematical queries and break them down into basic operations
2. Use available math tools (add, multiply, divide) appropriately
3. Provide clear explanations of calculations
4. Handle errors gracefully if operations fail
Available tools and their JSON formats:
- Addition: {"tool_name": "add", "a": <number>, "b": <number>}
- Multiplication: {"tool_name": "multiply", "a": <number>, "b": <number>}
- Division: {"tool_name": "divide", "a": <number>, "b": <number>}
IMPORTANT:
1. Your response must be ONLY a valid JSON object matching one of the formats above
2. Do not include any additional text, explanations, or formatting
3. Convert all numbers to integers
4. Do not include any markdown, code blocks, or other formatting
Example interaction:
User: "add 5 and 3"
You: {"tool_name": "add", "a": 5, "b": 3}
Remember to use the available MCP tools for calculations rather than doing them directly.
Human:: add 3 and334
Math Agent: {"tool_name": "add", "a": 3, "b": 334}
error: No result from tool execution
Tool Executor: No result from tool execution
Math Agent: {"error": "No result from tool execution"}
Enter math operation:

@ -1,54 +0,0 @@
Math Calculator Ready!
Available operations: add, multiply, divide
Example: 'add 5 and 3' or 'multiply 4 by 6'
Type 'exit' to quit
Enter math operation: add 2 and 3
╭─────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 2, "b": 3} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 15:56:47 | ERROR | swarms.tools.mcp_integration:_call_one_server:475 - Error calling server: ClientSession.__init__() missing 2 required positional arguments: 'read_stream' and 'write_stream'
╭─────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ────────────────────────╮
│ Math Agent - Tool Executor: No result from tool execution │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────╮
│ Math Agent - Agent Analysis: {"tool_name": "add", "a": 0, "b": 0} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: Math Agent
Your Description: Basic math calculator
You are a math calculator agent that performs basic arithmetic operations.
Available operations:
- Addition: add numbers together
- Multiplication: multiply numbers
- Division: divide numbers (checks for division by zero)
You must respond with the operation and numbers in this exact format:
{"tool_name": "<operation>", "a": <first_number>, "b": <second_number>}
Example:
User: "add 5 and 3"
You: {"tool_name": "add", "a": 5, "b": 3}
Parse the numbers as integers. Only return the operation format, no other text.
Human:: add 2 and 3
Math Agent: {"tool_name": "add", "a": 2, "b": 3}
error: No result from tool execution
Tool Executor: No result from tool execution
Math Agent: {"tool_name": "add", "a": 0, "b": 0}
Enter math operation:

@ -1,56 +0,0 @@
Math Calculator Ready!
Available operations: add, multiply, divide
Example: 'add 5 and 3' or 'multiply 4 by 6'
Type 'exit' to quit
Enter math operation: 2025-04-20 16:12:06 | WARNING | swarms.structs.agent:llm_handling:635 - Model name is not provided, using gpt-4o-mini. You can configure any model from litellm if desired.
add 2 and 3
╭─────────────────────────────── Agent Name Math Agent [Max Loops: 1 ] ────────────────────────────────╮
│ Math Agent: {"tool_name": "add", "a": 2, "b": 3} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
2025-04-20 16:12:21 | ERROR | swarms.structs.agent:mcp_execution_flow:2697 - Error executing tool call: a coroutine was expected, got <_GatheringFuture pending>
╭─────────────────────── Agent Name Math Agent - Tool Executor [Max Loops: 1 ] ────────────────────────╮
│ Math Agent - Tool Executor: Error executing tool call: a coroutine was expected, got │
│ <_GatheringFuture pending> │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────────────────────── Agent Name Math Agent - Agent Analysis [Max Loops: 1 ] ───────────────────────╮
│ Math Agent - Agent Analysis: {"tool_name": "add", "a": 0, "b": 0} │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
Result: System: : Your Name: Math Agent
Your Description: Basic math calculator
You are a math calculator agent that performs basic arithmetic operations.
Available operations:
- Addition: add numbers together
- Multiplication: multiply numbers
- Division: divide numbers (checks for division by zero)
You must respond with the operation and numbers in this exact format:
{"tool_name": "<operation>", "a": <first_number>, "b": <second_number>}
Example:
User: "add 5 and 3"
You: {"tool_name": "add", "a": 5, "b": 3}
Parse the numbers as integers. Only return the operation format, no other text.
Human:: add 2 and 3
Math Agent: {"tool_name": "add", "a": 2, "b": 3}
error: Error executing tool call: a coroutine was expected, got <_GatheringFuture pending>
Tool Executor: Error executing tool call: a coroutine was expected, got <_GatheringFuture pending>
Math Agent: {"tool_name": "add", "a": 0, "b": 0}
Enter math operation:

@ -1,73 +0,0 @@
Multi-Agent Math System
Enter 'exit' to quit
Enter a math problem: show the agetns available
==================================================
Results:
==================================================
[Calculator]
--------------------------------------------------
I can perform basic mathematical operations: addition (use '+' or 'plus'), multiplication (use '*' or 'times'), and division (use '/' or 'divide by'). For example: '5 plus 3' or '10 divide by 2'
[StockAnalyst]
--------------------------------------------------
I can analyze stock data using moving averages and calculate percentage changes. For example: 'calculate moving average of [10,20,30,40,50] over 3 periods'
==================================================
Enter a math problem: add 3243 and 55
╭───────────────────────── Agent Name StockAnalyst [Max Loops: 1 ] ─────────────────────────╮
│ StockAnalyst: To add 3243 and 55, you can perform the calculation: │
│ │
│ 3243 + 55 = 3298. │
╰───────────────────────────────────────────────────────────────────────────────────────────╯
╭────────────────────────── Agent Name Calculator [Max Loops: 1 ] ──────────────────────────╮
│ Calculator: To add 3243 and 55, you can perform the calculation: │
│ │
│ 3243 + 55 = 3298. │
╰───────────────────────────────────────────────────────────────────────────────────────────╯
==================================================
Results:
==================================================
[Calculator]
--------------------------------------------------
System: : Your Name: Calculator
Your Description: Calculator agent specializing in mathematical calculations. For Calculator: use add, multiply, divide operations. For Stock Analyst: use moving averages and percentage change calculations.
You are Calculator, a math processing agent. You have access to these mathematical operations ONLY: addition, multiplication, and division. Only suggest calculations using these available tools. Do not attempt to solve problems requiring other operations like percentages, square roots, or advanced math. When users ask about capabilities, list only the basic operations you can perform.
Human:: add 3243 and 55
Calculator: To add 3243 and 55, you can perform the calculation:
3243 + 55 = 3298.
[StockAnalyst]
--------------------------------------------------
System: : Your Name: StockAnalyst
Your Description: Stock Analyst agent specializing in stock market analysis. For Calculator: use add, multiply, divide operations. For Stock Analyst: use moving averages and percentage change calculations.
You are StockAnalyst, a math processing agent. You have access to these mathematical operations ONLY: addition, multiplication, and division. Only suggest calculations using these available tools. Do not attempt to solve problems requiring other operations like percentages, square roots, or advanced math. When users ask about capabilities, list only the basic operations you can perform.
Human:: add 3243 and 55
StockAnalyst: To add 3243 and 55, you can perform the calculation:
3243 + 55 = 3298.
==================================================

@ -1,68 +0,0 @@
Multi-Agent Math System
Enter 'exit' to quit
Enter a math problem: what ptoblems you can solve
Results:
==================================================
I can perform basic mathematical operations: addition (use '+' or 'plus'), multiplication (use '*' or 'times'), and division (use '/' or 'divide by'). For example: '5 plus 3' or '10 divide by 2'
I can analyze stock data using moving averages and calculate percentage changes. For example: 'calculate moving average of [10,20,30,40,50] over 3 periods'
==================================================
Enter a math problem: get the altes stock data
╭───────────────────────── Agent Name StockAnalyst [Max Loops: 1 ] ─────────────────────────╮
│ StockAnalyst: I'm unable to retrieve stock data directly. However, if you have specific │
│ numbers or data points related to Altes stock, I can help you perform calculations using │
│ addition, multiplication, or division. Please provide the data you want to analyze! │
╰───────────────────────────────────────────────────────────────────────────────────────────╯
Results:
==================================================
System: : Your Name: StockAnalyst
Your Description: Stock Analyst agent specializing in stock market analysis. For Calculator: use add, multiply, divide operations. For Stock Analyst: use moving averages and percentage change calculations.
You are StockAnalyst, a math processing agent. You have access to these mathematical operations ONLY: addition, multiplication, and division. Only suggest calculations using these available tools. Do not attempt to solve problems requiring other operations like percentages, square roots, or advanced math. When users ask about capabilities, list only the basic operations you can perform.
Human:: get the altes stock data
StockAnalyst: I'm unable to retrieve stock data directly. However, if you have specific numbers or data points related to Altes stock, I can help you perform calculations using addition, multiplication, or division. Please provide the data you want to analyze!
==================================================
Enter a math problem: add 2 nmimebts 3 and 4
╭────────────────────────── Agent Name Calculator [Max Loops: 1 ] ──────────────────────────╮
│ Calculator: It seems there was a typo in your request. If you want to add the numbers 3 │
│ and 4, the calculation would be: │
│ │
│ 3 + 4 │
│ │
│ Would you like me to perform that calculation? │
╰───────────────────────────────────────────────────────────────────────────────────────────╯
Results:
==================================================
System: : Your Name: Calculator
Your Description: Calculator agent specializing in mathematical calculations. For Calculator: use add, multiply, divide operations. For Stock Analyst: use moving averages and percentage change calculations.
You are Calculator, a math processing agent. You have access to these mathematical operations ONLY: addition, multiplication, and division. Only suggest calculations using these available tools. Do not attempt to solve problems requiring other operations like percentages, square roots, or advanced math. When users ask about capabilities, list only the basic operations you can perform.
Human:: add 2 nmimebts 3 and 4
Calculator: It seems there was a typo in your request. If you want to add the numbers 3 and 4, the calculation would be:
3 + 4
Would you like me to perform that calculation?
==================================================
Enter a math problem:

@ -1,105 +0,0 @@
### What “FastMCP” is today  and why your code keeps breaking
| What you tried to import | Why it fails | What to do instead |
|---|---|---|
| `from fastmcp.servers …` / `fastmcp.client.sse` | **The layout you remember was removed.**<br/>As of *FastMCP  1.0* the project focuses **only on helping you *write servers***. All *clientside* helpers (SSE transport, `FastClientSession`, etc.) were merged into the **official `mcp` Python SDK** and deleted from FastMCP. citeturn14view0 | • Keep using the **`mcp` SDK** for talking to servers (list tools, call tools).<br/>• Use **FastMCP only to *build* servers you want to expose to Claude/Swarms**. |
| `NotRequired` from `typing` on Python  3.10 | `typing.NotRequired` is available only in 3.11+. | Import it from `typing_extensions`: <br/>```python<br/>from typing_extensions import NotRequired, TypedDict<br/>``` |
---
## 1 · Update your Swarms integration (client side)
```diff
- from fastmcp.client.sse import sse_client
- from fastmcp import FastClientSession as ClientSession
+ from mcp import ClientSession # unchanged from old codebase
+ from mcp.client.sse import sse_client # still lives in `mcp`
```
Nothing else in your `MCPServer*` helper classes has to change the wire protocol is the same.
### Add the missing `mcp_servers` field to `Agent`
```diff
class Agent:
def __init__(self,
...
- tools_list_dictionary: Optional[List[Dict[str, Any]]] = None,
+ tools_list_dictionary: Optional[List[Dict[str, Any]]] = None,
+ mcp_servers: Optional[list[MCPServerSseParams]] = None,
*args, **kwargs):
...
self.mcp_servers = mcp_servers or []
```
and inside `handle_tool_init` gate tool execution with `if self.mcp_servers:` instead of accessing an attribute that did not exist.
---
## 2 · Build (or reuse) servers with FastMCP
FastMCP is perfect for *authoring* a server e.g. a tiny calculator you can smoketest against Swarms:
```python
# calc_server.py
from fastmcp import FastMCP
mcp = FastMCP("Calc") # the object name *must* be `mcp`, `app`, or `server`
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
```
Run it locally:
```bash
pip install fastmcp mcp # FastMCP 2.2.0 pulls the right deps
fastmcp dev calc_server.py # opens the GUI inspector
```
or keep it running for Swarms with
```bash
fastmcp run calc_server.py
```
---
## 3 · Connect from Swarms (smoketest)
```python
from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams
server_local = MCPServerSseParams(
url="http://127.0.0.1:6274", # the URL printed by `fastmcp run`
headers={"Content-Type": "application/json"},
)
agent = Agent(
agent_name = "MathSmokeTester",
system_prompt = "You call external MCP tools to do the math.",
mcp_servers = [server_local], # <-- now it exists
max_loops = 1,
)
print(agent.run("Use the add tool to add 2 and 2"))
```
If the calculator server is reachable, Swarms will:
1. Receive the LLMs functioncall JSON,
2. Pass it to `batch_mcp_flow`,
3. The MCP client will POST to `http://127.0.0.1:6274`,
4. Tool returns `4`, which your `Agent` prints.
---
## 4 · Where to read the current docs
* **FastMCP PyPI** installation & quickstart citeturn14view0
* **Official MCP SDK** (client utilities) <https://github.com/modelcontextprotocol/python-sdk>
Stick to this split and you can forget about missing modules or mismatched versions.

@ -1,123 +0,0 @@
### What happened?
1. **The LLM is returning a streaming wrapper instead of text**
Because `streaming_on=True`, LiteLLM gives you a `CustomStreamWrapper` object.
Your helper `parse_llm_output()` doesnt know how to turn that object into a string, so the
agent stores the wrapper itself.
2. **`mcp_execution_flow()` received an empty string**
When the agent tried to forward the toolcall to your FastMCP server it called
`json.loads(<emptystring>)`, which raised
*“Expecting value: line 1 column 1 (char 0)”*.
That means the HTTP call to `http://0.0.0.0:8000/mcp` returned **no body**
usually because the path is wrong or the server crashed.
---
### Fast MCP mockserver: correct URL
`FastMCP.run(transport="sse", port=8000)` serves SSE on
`http://<host>:8000/stream` **and** accepts JSONRPC over POST on the root
`http://<host>:8000/`.
So point the client at the root (no `/mcp` suffix):
```python
math_server = MCPServerSseParams(
url="http://0.0.0.0:8000", # <── just the origin
headers={"Content-Type": "application/json"},
timeout=5.0,
sse_read_timeout=30.0,
)
```
---
### Stop streaming while you debug
```python
math_agent = Agent(
agent_name="Math Agent",
agent_description="Specialized agent for mathematical computations",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[math_server],
streaming_on=False, # <── turn off for now
)
```
(You can turn it back on when everything works and you extend
`parse_llm_output()` to unwrap streams.)
---
### Make sure the LLM actually *produces* a tool call
LLMs wont invent a JSONRPC envelope unless you ask them.
Add a very small system hint that mirrors the MCP schema, e.g.
```python
TOOL_CALL_INSTRUCTION = """
When you want to use a math tool, reply with a JSON object only:
{"tool_name": "<add|multiply|divide>", "a": <int>, "b": <int>}
"""
math_agent.short_memory.add(role="system", content=TOOL_CALL_INSTRUCTION)
```
Now “**add 2 and 4**” should yield
```json
{"tool_name":"add","a":2,"b":4}
```
which your `mcp_execution_flow()` can forward.
---
### Fix the emptybody crash guard (optional)
Inside `mcp_execution_flow()` (or `mcp_flow`) you can protect yourself:
```python
resp = client.post(...)
if not resp.text:
raise RuntimeError("MCP server returned empty body")
```
That turns an unhelpful JSON decode error into a clear MCPconnection error.
---
### Quick test commands
```bash
# 1. Start mock server in one shell
python mock_math_server.py # “Starting Mock Math Server on port 8000…”
# 2. In another shell, make sure it answers
curl -X POST http://0.0.0.0:8000 \
-H "Content-Type: application/json" \
-d '{"tool_name":"add","a":2,"b":4}'
# → {"result":6}
# 3. Run your client
python mcp_client.py
```
If you now type `add 2 and 4`, the agent should respond **6** (with your
explanation string) instead of the streamobject dump.
---
#### Next steps
* Reenable `streaming_on=True` and add handling of LiteLLMs stream wrapper in
`parse_llm_output()`.
* Return the math result to the user in natural language (e.g. “2 + 4 = 6”).
* Add error handling in the mock server (e.g. dividebyzero already covered).
That should give you a clean smoketest of **Fast MCP + Swarms Agent** without
the functioncalling “craziness”.

@ -1,116 +0,0 @@
### What happened?
The Replit automerge put **two very different things in one file**:
1. **FastMCP server code** (`add / multiply / divide` tools)
2. **Client/Agent code** that is supposed to *call* those tools
That hybrid script cant work correctly:
* The moment `mcp.run()` starts the SSE server loop, the code **after it never executes**, so the `Agent` you created would never run.
* Even if it did, youd be pointing the client back to *itself* on the same port—nothing useful.
---
### Correct separation
| File | Role | Runs in its own process |
|------|------|-------------------------|
| **`math_server.py`** | Hosts the tools (`@mcp.tool()`), listens on :8000 | ✅ |
| **`math_agent.py`** | Swarms `Agent` that talks to that server | ✅ |
---
#### 1 . `math_server.py`  *serveronly*
```python
# math_server.py
from fastmcp import FastMCP
import time
mcp = FastMCP("MathMockServer")
@mcp.tool()
def add(a: int, b: int) -> int:
time.sleep(0.1)
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
time.sleep(0.1)
return a * b
@mcp.tool()
def divide(a: int, b: int) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
time.sleep(0.1)
return a / b
if __name__ == "__main__":
print("🚀 Math MCP server on :8000")
mcp.run(transport="sse", host="0.0.0.0", port=8000)
```
(`server.py` never imports `Agent` or `MCPServerSseParams`.)
---
#### 2 . `math_agent.py`  *client/agentonly*
```python
# math_agent.py
from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams
MATH_SERVER = MCPServerSseParams(
url="http://127.0.0.1:8000", # no “/mcp” path required
headers={"Content-Type": "application/json"},
)
agent = Agent(
agent_name="Math-Processing-Agent",
agent_description="Specialised agent for basic math ops",
system_prompt=(
"You can use the add, multiply and divide MCP tools "
"to answer any arithmetic question."
),
max_loops=1,
mcp_servers=[MATH_SERVER],
model_name="gpt-4o-mini",
output_type="final",
)
if __name__ == "__main__":
answer = agent.run("Use the add tool to add 2 and 2")
print("Agent replied ➜", answer)
```
---
### How to run (locally or on Replit)
```bash
# Terminal 1 (or first Replit tab)
python math_server.py
# Terminal 2 (second tab)
python math_agent.py
```
Expected console:
```
🚀 Math MCP server on :8000
Agent replied ➜ 4
```
---
### Key points to remember
1. **Never start an Agent in the same process that is serving MCP**—keep client and server separate.
2. `MCPServerSseParams.url` points to the **root** of the FastMCP server, not `/mcp`.
3. The Swarms base `Agent` already knows how to wrap the JSONRPC call; you only supply `mcp_servers=[…]`.
Follow that structure, and your managers “initialize the agent like this” requirement is fully satisfied.

@ -1,105 +0,0 @@
### Why youre getting the `ImportError`
`fastmcp`  2.0 renamed **`FastClientSession`** → **`Client`** and moved it into the toplevel package.
So
```python
from fastmcp import FastClientSession # 🚫 no longer exists
```
now raises the exact error you see.
---
### Quick fix  patch the import
Open **`swarms/tools/mcp_integration.py`** and replace the first import block:
```python
# OLD
from fastmcp import FastClientSession as ClientSession
```
with
```python
# NEW works with fastmcp ≥ 2.0
from fastmcp import Client as ClientSession
```
*(If you need to stay on fastmcp 1.x, install the old version instead:
`pip install "fastmcp<2"` and keep your original import.)*
---
### Minimal working smoketest
```python
# examples/mcp_example/mcp_client.py
import asyncio
from swarms import Agent
from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
from swarms.tools.mcp_integration import MCPServerSseParams
# 1. describe the remote MCP server you want to hit
server = MCPServerSseParams(
url="http://localhost:6274", # or any public MCP SSE endpoint
headers={"Content-Type": "application/json"}
)
# 2. create a Swarms agent and hand it the server list
math_agent = Agent(
agent_name="MathMCPTester",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[server], # < now recognised
output_type="final",
)
# 3. run a call that should trigger the servers “add” tool
result = math_agent.run("Use the add tool to add 2 and 2")
print("🟢 RESULT:", result)
```
---
### Extra housekeeping
1. **Expose `mcp_servers`**
In your current `Agent.__init__` the assignment line is commented out:
```python
# self.mcp_servers = mcp_servers # <- uncomment
```
Make sure the attribute exists before it is accessed in `handle_tool_init()`.
2. **Python < 3.11 + `NotRequired`**
Keep
```python
from typing_extensions import NotRequired
```
(You already changed this good.)
3. **Install / upgrade fastmcp**
```bash
pip install -U fastmcp # latest 2.x
# or, for the old API:
# pip install "fastmcp<2"
```
---
### What if you dont have your own server yet?
Until you spin up the Browserbase example (or any other MCP server), you can test against the **FastMCP public demo**:
```python
demo = MCPServerSseParams(url="https://demo.fastmcp.io/sse")
```
It exposes trivial arithmetic tools (`add`, `multiply`, …) that match the smoketest above.
Thats all you need to get your Swarms agent talking to an existing MCP server without touching serverside code. 🚀

@ -1,110 +0,0 @@
### Why youre seeing **`name 'batch_mcp_flow' is not defined`**
1. In **`swarms/structs/agent.py`** the method `mcp_execution_flow()` (or the block that calls MCP) still tries to invoke `batch_mcp_flow`.
2. At the very top of the file the import that *defines* that symbol was commented out when you switched to fastMCP:
```python
# from swarms.tools.mcp_integration import (
# MCPServerSseParams,
# batch_mcp_flow, # ← you lost this
# mcp_flow_get_tool_schema,
# )
```
3. When Python hits `batch_mcp_flow(…)` it isnt in the modules namespace, so the call blows up and your agent prints the MCPerror.
---
## Twostep fix
> Below assumes your `swarms/tools/mcp_integration.py` already contains a working (sync) wrapper named `batch_mcp_flow` that *returns a string*, **not** a coroutine object.
> If you kept it **async**, see the “If your wrapper is still async” note at the end.
---
### 1  · Restore the import in **`agent.py`**
Uncomment (or add) the line:
```python
from swarms.tools.mcp_integration import batch_mcp_flow
```
Keep the `MCPServerSseParams` import too if you reference it elsewhere.
---
### 2  · Make sure `batch_mcp_flow()` is **synchronous**
Inside **`swarms/tools/mcp_integration.py`** do something like:
```python
# ── swarms/tools/mcp_integration.py ─────────────────────
import asyncio
# … other imports …
async def _batch_mcp_flow_async(
params: list[MCPServerSseParams],
function_call: dict[str, Any],
) -> str:
# your existing async logic that talks to MCP
# and returns a JSONserialisable string/str
...
def batch_mcp_flow(
params: list[MCPServerSseParams],
function_call: dict[str, Any],
) -> str:
"""Blocking wrapper so callers don't have to await."""
return asyncio.run(
_batch_mcp_flow_async(params, function_call)
)
```
Now `agent.py` can call `batch_mcp_flow(...)` directly and
get **the tools real answer**, not a coroutine object.
---
### Quick checklist
- [ ] Reimport `batch_mcp_flow` in `swarms/structs/agent.py`.
- [ ] Ensure `batch_mcp_flow()` (the public one) **returns a value**, not a coroutine.
- [ ] Remove or comment out the temporary warning prints you added earlier.
---
### If your wrapper is still async
You can alternatively **await** it inside `mcp_execution_flow`:
```python
import asyncio
def mcp_execution_flow(self, response: str) -> str:
try:
resp_dict = json.loads(response)
return asyncio.run(
batch_mcp_flow(self.mcp_servers, resp_dict)
)
except Exception as e:
logger.error(f"MCP flow failed: {e}")
return f"[MCP-error] {e}"
```
Either approach works; the key is that the call you make inside the agent must not leave a bare coroutine object floating around.
Once those two lines are fixed, run the client again:
```bash
python examples/mcp_example/mcp_client.py
```
You should now see a clean answer:
```
Enter your query (or 'exit' to quit): add 3 and 33
Math Agent Response: 36
```
Happy calculating!

@ -1,110 +0,0 @@
### Why youre seeing **`name 'batch_mcp_flow' is not defined`**
1. In **`swarms/structs/agent.py`** the method `mcp_execution_flow()` (or the block that calls MCP) still tries to invoke `batch_mcp_flow`.
2. At the very top of the file the import that *defines* that symbol was commented out when you switched to fastMCP:
```python
# from swarms.tools.mcp_integration import (
# MCPServerSseParams,
# batch_mcp_flow, # ← you lost this
# mcp_flow_get_tool_schema,
# )
```
3. When Python hits `batch_mcp_flow(…)` it isnt in the modules namespace, so the call blows up and your agent prints the MCPerror.
---
## Twostep fix
> Below assumes your `swarms/tools/mcp_integration.py` already contains a working (sync) wrapper named `batch_mcp_flow` that *returns a string*, **not** a coroutine object.
> If you kept it **async**, see the “If your wrapper is still async” note at the end.
---
### 1  · Restore the import in **`agent.py`**
Uncomment (or add) the line:
```python
from swarms.tools.mcp_integration import batch_mcp_flow
```
Keep the `MCPServerSseParams` import too if you reference it elsewhere.
---
### 2  · Make sure `batch_mcp_flow()` is **synchronous**
Inside **`swarms/tools/mcp_integration.py`** do something like:
```python
# ── swarms/tools/mcp_integration.py ─────────────────────
import asyncio
# … other imports …
async def _batch_mcp_flow_async(
params: list[MCPServerSseParams],
function_call: dict[str, Any],
) -> str:
# your existing async logic that talks to MCP
# and returns a JSONserialisable string/str
...
def batch_mcp_flow(
params: list[MCPServerSseParams],
function_call: dict[str, Any],
) -> str:
"""Blocking wrapper so callers don't have to await."""
return asyncio.run(
_batch_mcp_flow_async(params, function_call)
)
```
Now `agent.py` can call `batch_mcp_flow(...)` directly and
get **the tools real answer**, not a coroutine object.
---
### Quick checklist
- [ ] Reimport `batch_mcp_flow` in `swarms/structs/agent.py`.
- [ ] Ensure `batch_mcp_flow()` (the public one) **returns a value**, not a coroutine.
- [ ] Remove or comment out the temporary warning prints you added earlier.
---
### If your wrapper is still async
You can alternatively **await** it inside `mcp_execution_flow`:
```python
import asyncio
def mcp_execution_flow(self, response: str) -> str:
try:
resp_dict = json.loads(response)
return asyncio.run(
batch_mcp_flow(self.mcp_servers, resp_dict)
)
except Exception as e:
logger.error(f"MCP flow failed: {e}")
return f"[MCP-error] {e}"
```
Either approach works; the key is that the call you make inside the agent must not leave a bare coroutine object floating around.
Once those two lines are fixed, run the client again:
```bash
python examples/mcp_example/mcp_client.py
```
You should now see a clean answer:
```
Enter your query (or 'exit' to quit): add 3 and 33
Math Agent Response: 36
```
Happy calculating!

@ -1,189 +0,0 @@
Below is a **surgical “diffstyle” checklist** that shows exactly what you have to change (and what you can delete outright) to migrate your current `Agent`/`mcp_integration` pair from **JSONfunctioncalling → FastMCP**.
I kept it to the two files you pasted, so you can copypaste or cherrypick with your IDEs patch tool.
---
## 0. New dependency
```bash
pip install fastmcp # tiny async wrapper around mcp.ClientSession in “fast” mode
```
---
## 1. `swarms/tools/mcp_integration.py`
### 1.1 Imports
```diff
-from mcp import (
- ClientSession,
- StdioServerParameters,
- Tool as MCPTool,
- stdio_client,
-)
+# fastmcp gives us a dropin “FastClientSession” that sets the right SSE headers
+from fastmcp import FastClientSession as ClientSession
+from fastmcp.servers import fast_sse_client as sse_client # replaces std one
```
*(Keep the rest of the imports asis; they still compile.)*
### 1.2 Replace the SSE transport factory
FastMCP reuses the same SSE wire format but forces `FAST_MCP_MODE=1` headers and keeps the connection hot.
```diff
- def create_streams(self, ...) -> AbstractAsyncContextManager[...]:
- return sse_client(
- url=self.params["url"],
- headers=self.params.get("headers", None),
- timeout=self.params.get("timeout", 5),
- sse_read_timeout=self.params.get("sse_read_timeout", 60*5),
- )
+ def create_streams(self, ...) -> AbstractAsyncContextManager[...]:
+ return sse_client( # NOTE: imported from fastmcp.servers above
+ url=self.params["url"],
+ headers=self.params.get("headers", None),
+ timeout=self.params.get("timeout", 5),
+ sse_read_timeout=self.params.get("sse_read_timeout", 60 * 5),
+ )
```
### 1.3 Add **fast** helper for a single call (optional)
```python
async def call_tool_fast(server: MCPServerSse, payload: dict[str, Any]):
"""
Convenience wrapper that opens → calls → closes in one shot.
"""
await server.connect()
result = await server.call_tool(payload)
await server.cleanup()
return result.model_dump() if hasattr(result, "model_dump") else result
```
---
## 2. `swarms/structs/agent.py`
### 2.1 accept `mcp_servers` parameter (you commented it out)
```diff
- tools_list_dictionary: Optional[List[Dict[str, Any]]] = None,
- # mcp_servers: List[MCPServerSseParams] = [],
+ tools_list_dictionary: Optional[List[Dict[str, Any]]] = None,
+ mcp_servers: Optional[List[Dict[str, Any]]] = None, # NEW
```
and save it:
```diff
self.tools_list_dictionary = tools_list_dictionary
+# FastMCP
+self.mcp_servers = mcp_servers or []
```
### 2.2 Drop `parse_and_execute_json` branch and replace with FastMCP
Inside `_run()` where you currently have:
```python
if self.tools is not None or hasattr(self, 'mcp_servers'):
...
```
replace everything in that `if` block with:
```diff
-if self.tools is not None or hasattr(self, 'mcp_servers'):
- if self.tools:
- out = self.parse_and_execute_tools(response)
- if hasattr(self, 'mcp_servers') and self.mcp_servers:
- out = self.mcp_execution_flow(response)
-
- self.short_memory.add(role="Tool Executor", content=out)
- ...
+if self.mcp_servers: # ـ فقط FastMCP path
+ # Response from the model **will be** JSONRPC already. Convert str → dict
+ try:
+ fn_call = json.loads(response) if isinstance(response, str) else response
+ except Exception:
+ # Not a toolcall, skip.
+ fn_call = None
+
+ if fn_call and isinstance(fn_call, dict):
+ # roundrobin you can pick a smarter loadbalancer later
+ target = random.choice(self.mcp_servers)
+ out = mcp_flow(target, fn_call) # <- from mcp_integration.py
+
+ self.short_memory.add(role="Tool", content=out)
+ agent_print(f"{self.agent_name} tool result", out, loop_count, self.streaming_on)
+
+ # Let the model reflect on the tools answer
+ follow_up = self.llm.run(out)
+ self.short_memory.add(role=self.agent_name, content=follow_up)
```
### 2.3 Delete **parse_and_execute_tools** helper altogether
If nothing else in your codebase uses it, just remove the whole method to avoid dead weight.
### 2.4 Optional: preload tool schemas into the model (good prompt hygiene)
At the end of `init_handling()` add:
```python
# Advertise remote tools to the model (tool descriptions feed)
if self.mcp_servers:
try:
first = self.mcp_servers[0]
schema_txt = any_to_str(mcp_flow_get_tool_schema(first))
self.short_memory.add(role="system", content=f"REMOTE_TOOLS:\n{schema_txt}")
except Exception as e:
logger.warning(f"Could not fetch tool schema: {e}")
```
---
## 3. Quick smoke test
```python
from swarms.structs.agent import Agent
FLOWISE = {"url": "https://mcp.flowise.ai"} # no auth for public demo
bot = Agent(
agent_name="fastmcp-demo",
model_name="gpt-4o-mini",
streaming_on=True,
mcp_servers=[FLOWISE], # <- the only change you really need
)
print(
bot("Use `serp.search` to fetch todays ETH price and summarise in one sentence")
)
```
You should see:
1. LLM emits a `call_tool` JSON.
2. Agent relays it to Flowise server via FastMCP.
3. Response streams back; LLM reasons on it; final answer printed.
---
### What we just *removed*
* `parse_and_execute_json`
* `tool_choice`, `function_calling_format_type`, etc. (theyre harmless but unused)
* Manual “functioncalling” retries.
### What we just *added*
* `fastmcp` dependency + a **single** SSE connection that stays alive for the whole agent run.
---
Thats it!
Apply the diff, run the smoke test, and youre on FastMCP.
If you bump into a specific traceback, paste it and well debug the next inch. Happy hacking 🚀

@ -1,100 +0,0 @@
Both stacktraces come from very small compatibility issues in **your local copy** of the library.
Fixing them just needs two tiny edits.
---
## 1  `'Agent' object has no attribute 'mcp_servers'`
`Agent.__init__()` used to take `mcp_servers`, but in your checkout that
parameter line is commented out:
```python
# mcp_servers: List[MCPServerSseParams] = [],
```
Yet `handle_tool_init()` still refers to `self.mcp_servers`, so the
attribute is missing when the object is created.
### Patch
```diff
@@ class Agent:
- # mcp_servers: List[MCPServerSseParams] = [],
+ mcp_servers: Optional[list] = None, # list[MCPServerSseParams]
@@ def __init__(...):
- self.tools_list_dictionary = tools_list_dictionary
- # self.mcp_servers = mcp_servers
+ self.tools_list_dictionary = tools_list_dictionary
+ self.mcp_servers = mcp_servers
```
> *Nothing else has to change; the `exists(self.mcp_servers)` check will now
> work, and you can pass `mcp_servers=[server_one]` from your smoketest.*
---
## 2  `ImportError: cannot import name 'NotRequired' from typing`
`typing.NotRequired` only exists in **Python  3.11**.
On 3.10 you have to import it from **`typing_extensions`**.
The top of `swarms/tools/mcp_integration.py` currently has:
```python
from typing import Any, Dict, List, Optional, TypedDict, NotRequired
```
### Patch
```diff
-from typing import Any, Dict, List, Optional, TypedDict, NotRequired
+from typing import Any, Dict, List, Optional
+from typing_extensions import NotRequired, TypedDict
```
(There is already a `typing_extensions` import later, so you can simply reuse
it and remove `NotRequired` from the `typing` line.)
> Make sure the wheel `typingextensions` is installed:
> ```bash
> pip install -U typing_extensions
> ```
---
### After the fixes
Your smoketest script should run:
```python
from swarms.tools.mcp_integration import MCPServerSseParams
from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
from swarms import Agent
server_one = MCPServerSseParams(
url="http://127.0.0.1:6274",
headers={"Content-Type": "application/json"},
)
agent = Agent(
agent_name="MathTester",
agent_description="Does arithmetic via MCP add tool",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[server_one],
output_type="final",
)
print(agent.run("Use the add tool to add 2 and 2"))
```
---
**Summary**
* add the `mcp_servers` parameter back into `Agent.__init__`
* import `NotRequired` from `typing_extensions`, not `typing`
After these two edits the “attribute missing” and “ImportError” messages
disappear and the agent can reach the MCP server for your smoketest.

@ -1,107 +0,0 @@
Heres why the latest run blew up and what to change so the **Swarms Agent + MCP** combo finally works:
---
### 1  Fix the import thats blowing up
`mcp` exposes **ClientSession**, not **Client**.
Change the topoffile imports in **swarms/tools/mcp_integration.py**
```diff
- from mcp import Client as ClientSession
- from fastmcp.client.sse import sse_client # (this package doesnt exist)
+ from mcp import ClientSession # core SDK class
+ from mcp.client.sse import sse_client # SSE transport helper
```
(See MCP quickstart that shows `from mcp import ClientSession`citeturn3search8)
---
### 2  Use `typing_extensions.NotRequired` on Python  3.10
Python 3.11 added `typing.NotRequired`; on 3.10 you must pull it from
`typing_extensions`:
```python
from typing_extensions import NotRequired, TypedDict
```
You already have that line keep it.
---
### 3  Let your `Agent` actually hold the server list
The attributeerror you saw (`'Agent' object has no attribute 'mcp_servers'`)
happens because the constructor parameter was commented out.
Add the param and stash it:
```diff
-class Agent:
- def __init__(self,
+class Agent:
+ def __init__(self,
...
- # mcp_servers: List[MCPServerSseParams] = [],
+ mcp_servers: Optional[list[MCPServerSseParams]] = None,
*args, **kwargs):
...
- # self.mcp_servers = mcp_servers
+ self.mcp_servers = mcp_servers or []
```
Now `handle_tool_init()` can safely look at `self.mcp_servers`.
---
### 4  Example “smoke test” with the Browserbase MCP server
```python
# examples/mcp_example/mcp_client.py
from swarms.structs.agent import Agent
from swarms.prompts.agent_prompts import MATH_AGENT_PROMPT
from swarms.tools.mcp_integration import MCPServerSseParams
browserbase = MCPServerSseParams(
url="http://127.0.0.1:6274", # running Browserbase MCP server
headers={"Content-Type": "application/json"},
)
math_bot = Agent(
agent_name="MathMCPBot",
agent_description="Performs arithmetic via MCP tools",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[browserbase], # <-- now recognised
output_type="final",
)
print(math_bot.run("Use the add tool to add 2 and 2"))
```
Make sure youve installed the SDK:
```bash
pip install "mcp>=0.3.0" typing_extensions
```
and that the Browserbase server from the README snippet is running (or any
other MCP SSE server).
---
### 5  What to do *if* you really want “fastmcp”
There isnt a published `fastmcp` Python package today (hence the
`ModuleNotFoundError`). Stick with the official `mcp` SDK until/if the
fastvariant is released. When it lands the only changes youd make are the
two import lines in **mcp_integration.py**; the rest of the Swarms integration
stays identical.
---
Apply those three code edits, reinstall dependencies, and your smoke test
should run without import errors. If you hit the next snag, drop the new
traceback and well keep tightening the bolts.

@ -1,92 +0,0 @@
The log tells us two separate things are still wrong:
| Symptom | Root cause | 1line fix |
|---------|------------|------------|
| `RuntimeWarning: coroutine 'batch_mcp_flow' was never awaited` | `batch_mcp_flow()` is **async**, but you call it like a plain function. | `out = await batch_mcp_flow(...)` *or* wrap the call in `asyncio.run(…)` if you want to stay sync. |
| `[MCPerror] Expecting value: line 1 column 1 (char 0)` | The FastMCP mock server replied, but your client tried to `json.loads()` an **empty body** (usually means the HTTP endpoint or headers are wrong). | Point the URL at the server **root** (`http://0.0.0.0:8000`) and send plain JSONRPC. |
Below is a minimal patch that removes both errors without touching the rest of your codebase.
---
## 1   make `mcp_execution_flow()` await the coroutine
```python
# ── swarms/structs/agent.py ─────────────────────────────────────────
import asyncio # add this at the top if its not there
# …
def mcp_execution_flow(self, payload: dict):
"""
Forward the toolcall dict to every MCP server in self.mcp_servers.
Returns the first nonerror response as a string.
"""
try:
# batch_mcp_flow is async ➜ run it synchronously
result = asyncio.run(
batch_mcp_flow(self.mcp_servers, payload)
)
return any_to_str(result)
except Exception as err:
logger.error(f"MCP flow failed: {err}")
return f"[MCP-error] {err}"
```
*(If you prefer your whole agent to stay async, just make
`mcp_execution_flow` itself `async def` and `await batch_mcp_flow` —
then call it with `await` from the `_run` loop.)*
---
## 2   use the correct FastMCP endpoint
In the client that spins up the **math agent**:
```python
math_server = MCPServerSseParams(
url="http://0.0.0.0:8000", # ← root! no “/mcp”
headers={"Content-Type": "application/json"},
timeout=5.0,
sse_read_timeout=30.0,
)
```
 FastMCPs `run(transport="sse", port=8000)` already exposes both
the SSE stream and the JSONRPC POST endpoint on that root URL.
Adding `/mcp` makes the request hit a 404, so the body is empty — thats
exactly what the JSON decoder complained about.
---
## 3   (optional) turn streaming off until everything works
```python
math_agent = Agent(
# …
streaming_on=False # ← easier to debug; turn back on later
)
```
With streaming disabled, `LiteLLM` returns plain strings, so your
`parse_llm_output()` method wont be handed a
`CustomStreamWrapper` object any more.
---
### Quick test matrix
| Action | Expected result |
|--------|-----------------|
| `curl -X POST http://0.0.0.0:8000 -d '{"tool_name":"add","a":2,"b":3}' -H 'Content-Type: application/json'` | `{"result":5}` |
| Run `mock_math_server.py` | “Starting Mock Math Server on port 8000…” |
| Run `mcp_client.py`, type `add 2 and 3` | Agent replies something like “2 + 3 = 5”. No coroutine warning. |
As soon as the roundtrip works once, you can:
* reenable `streaming_on=True` and teach `parse_llm_output()` to turn a
`CustomStreamWrapper` into text (`"".join(token.choices[0].delta.content for token in wrapper)`);
* point the agent at your real MCP servers instead of the mock one.
Happy hacking!

@ -1,100 +0,0 @@
The root of that “unhandled errors in a TaskGroup (1 subexception)” is simply that your clients `MCPServerSse.connect()` is failing under the hood (most likely a connection/refused or pathnotfound error) and AnyIO is wrapping it in a TaskGroup exception. You dont see the real cause because it gets hidden by AnyIOs TaskGroup. Heres how to unmask it and fix it:
---
## 1. Diagnose the real error
Wrap the connect call and print the underlying exception:
```python
async def _test_connect():
server = MCPServerSse(get_server_params())
try:
await server.connect()
await server.cleanup()
return True
except Exception as e:
# Print the actual cause
import traceback; traceback.print_exc()
return False
print(asyncio.run(_test_connect()))
```
Youll probably see a **connection refused** or **404 on /sse** in the stack trace.
---
## 2. Ensure client and server agree on your SSE endpoint
By default FastMCP serves its SSE stream at `/sse` and messages on `/messages`. If you only pass `url="http://127.0.0.1:8000"` the client will try whatever its default path is (often `/events` or `/stream`). You need to be explicit:
```python
from swarms.tools.mcp_integration import MCPServerSseParams
def get_server_params():
return MCPServerSseParams(
url="http://127.0.0.1:8000",
sse_path="/sse", # <— tell it exactly where the SSE lives
messages_path="/messages", # <— if your server uses /messages for POSTs
headers={
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
timeout=15.0,
sse_read_timeout=60.0,
require_session_id=False, # match your servers require_session_id
)
```
---
## 3. Dont manually call `MCPServerSse` unless you need to
Your `test_server_connection()` can more reliably just do a raw HTTP(S) healthcheck:
```python
def test_server_connection():
health_url = get_server_params().url + get_server_params().sse_path
try:
r = httpx.get(health_url,
headers={"Accept":"text/event-stream"},
timeout=5.0)
if r.status_code == 200:
logger.info("✅ SSE endpoint is up")
return True
else:
logger.error(f"❌ Unexpected status {r.status_code}")
return False
except Exception as e:
logger.error(f"❌ Connection to SSE endpoint failed: {e}")
return False
```
That way you see immediately if the server is refusing connections or returning 404.
---
## 4. Align your Agent configuration
Once youve verified the raw GET to `http://127.0.0.1:8000/sse` is 200, your Agent should work with exactly the same params:
```python
math_agent = Agent(
agent_name="Math Assistant",
agent_description="Friendly math calculator",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
model_name="gpt-3.5-turbo",
verbose=True,
mcp_servers=[ get_server_params() ]
)
```
Now when you do `math_agent.run("add 3 and 4")`, the SSE handshake will succeed and youll no longer see that TaskGroup error.
---
### TL;DR
1. **Print the real exception** behind the TaskGroup to see “connection refused” or “404.”
2. **Explicitly set** `sse_path="/sse"` (and `messages_path`) in `MCPServerSseParams`.
3. **Healthcheck** with a simple `httpx.get("…/sse")` instead of `server.connect()`.
4. Pass those same params straight into your `Agent`.
Once your client is pointing at the exact SSE URL your FastMCP server is serving, the Agent will connect cleanly and youll be back to doing math instead of wrestling TaskGroup errors.

@ -1,47 +0,0 @@
Traceback (most recent call last):
File "/home/runner/workspace/examples/mcp_example/mcp_client.py", line 1, in <module>
from swarms import Agent
File "/home/runner/workspace/swarms/__init__.py", line 9, in <module>
from swarms.agents import * # noqa: E402, F403
File "/home/runner/workspace/swarms/agents/__init__.py", line 1, in <module>
from swarms.agents.agent_judge import AgentJudge
File "/home/runner/workspace/swarms/agents/agent_judge.py", line 4, in <module>
from swarms.structs.agent import Agent
File "/home/runner/workspace/swarms/structs/__init__.py", line 1, in <module>
from swarms.structs.agent import Agent
File "/home/runner/workspace/swarms/structs/agent.py", line 1870
logger.info(f"Adding response filter: {filter_word}")
IndentationError: unexpected indent
`IndentationError: unexpected indent` means Python found a line that is indented farther than the block it lives in.
In `agent.py` the culprit is inside **`add_response_filter`** (around line 1870).
Just move the `logger.info(…)` line two spaces to the **left** (so it lines up with the first statement in the function) and, while youre there, fix the small typo in the attribute name.
```python
# ── swarms/structs/agent.py ─────────────────────────────
# Response Filtering
def add_response_filter(self, filter_word: str) -> None:
"""
Add a response filter to filter out certain words from the response.
"""
logger.info(f"Adding response filter: {filter_word}")
# attribute is self.response_filters (an "s"), not self.reponse_filters
self.response_filters.append(filter_word)
```
Full diffstyle patch  (*only the three changed lines shown*):
```diff
@@
- logger.info(f"Adding response filter: {filter_word}")
- self.reponse_filters.append(filter_word)
+ logger.info(f"Adding response filter: {filter_word}")
+ self.response_filters.append(filter_word)
```
After you save the file:
```bash
black swarms/structs/agent.py # optional but keeps everything wellindented
python -m py_compile swarms/structs/agent.py
```
Compilation should pass and the `mcp_client.py` script will start without the indentation error.

@ -1,114 +0,0 @@
Youve fixed the *RuntimeWarning* by wrapping the coroutine, but now the call never actually reaches the mock server.
Two things are still wrong:
| symptom | real cause |
|---------|------------|
| **`__aenter__`** error from `process_param` | `MCPServerSse` *is* an asynccontextmanager; you must use **`async with`** (or call its `connect/cleanup` explicitly). |
| **“No result returned from MCP server”** | we never awaited `call_tool`, so the request was never sent; the wrapper returned `None`. |
Below is a minimal, fullyworking patch set.
Apply it and the *MathMockServer* will answer correctly (e.g. `add 4 and 19834 → 19838`).
---
## 1  `tools/mcp_integration.py`
```python
# keep the import you already added
import asyncio
# ────────────────────────────────────────────────────────────
# 1. async helper that really talks to one MCP server
async def _call_one_server(param: MCPServerSseParams,
payload: dict[str, any]) -> str:
async with MCPServerSse(param, cache_tools_list=True) as srv:
# ↓ fastmcp returns a pydantic model; make it jsonserialisable
res = await srv.call_tool(payload)
try:
return res.model_dump() # fastmcp ≥0.2
except AttributeError:
return res # plain dict / str
# 2. public sync wrapper what the Agent imports & uses
def batch_mcp_flow(params: list[MCPServerSseParams],
payload: dict[str, any]) -> list[str]:
"""Blocking helper fanout to every MCP server given in *params*."""
return asyncio.run(_batch(params, payload))
# 3. little async fanout
async def _batch(params: list[MCPServerSseParams],
payload: dict[str, any]) -> list[str]:
coros = [_call_one_server(p, payload) for p in params]
return await asyncio.gather(*coros)
```
---
## 2  `structs/agent.py`
Replace **only** the `mcp_execution_flow` method with the synchronous
wrapper that now returns the real value (note: `payload` is a *string* here):
```python
# inside class Agent
def mcp_execution_flow(self, response: str) -> str:
"""
Forward the JSON toolcall coming from the LLM to all MCP servers
listed in self.mcp_servers.
"""
try:
payload = json.loads(response) # {"tool_name": …}
results = batch_mcp_flow(self.mcp_servers, payload)
# `batch_mcp_flow` already blocks, so results is a list[str]
return any_to_str(results[0] if len(results) == 1 else results)
except Exception as err:
logger.error(f"MCP flow failed: {err}")
return f"[MCP-error] {err}"
```
*(you may keep the rest of your big `Agent` class unchanged)*
---
## 3  clientside tiny polish
When you start the mock server you exposed SSE at `http://0.0.0.0:8000`.
Thats fine the fastmcp helper discovers the SSE endpoint automatically,
so the URL in `MCPServerSseParams` is correct.
---
## 4  Quick smoketest
1. **Start the mock server** (in one shell):
```bash
python math_mock_server.py # prints “Starting Mock Math Server…”
```
2. **Run the client** (your `mcp_client.py`) in another shell:
```
Enter your query (or 'exit' to quit): add 4 and 19834
Math Agent Response: 19838
```
No warning, no `[MCPerror]`, and you get the right answer.
---
### Why this works
* `async with MCPServerSse(...) as srv:` guarantees `connect()` and `cleanup()` are
called and awaited.
* `await srv.call_tool(payload)` actually sends the JSONRPC request.
* `asyncio.run()` in the wrapper lets the rest of your Agent stay 100 % synchronous.
* Any exception bubbles up, gets logged, and your Agent sees
`[MCPerror] …` instead of mysterious `None`.
You can now add more servers to `self.mcp_servers` theyll all be invoked in
parallel, and the first element of the returned list will always hold the
result from the first server (adapt as needed).
Happy calculating!

@ -1,114 +0,0 @@
Youve fixed the *RuntimeWarning* by wrapping the coroutine, but now the call never actually reaches the mock server.
Two things are still wrong:
| symptom | real cause |
|---------|------------|
| **`__aenter__`** error from `process_param` | `MCPServerSse` *is* an asynccontextmanager; you must use **`async with`** (or call its `connect/cleanup` explicitly). |
| **“No result returned from MCP server”** | we never awaited `call_tool`, so the request was never sent; the wrapper returned `None`. |
Below is a minimal, fullyworking patch set.
Apply it and the *MathMockServer* will answer correctly (e.g. `add 4 and 19834 → 19838`).
---
## 1  `tools/mcp_integration.py`
```python
# keep the import you already added
import asyncio
# ────────────────────────────────────────────────────────────
# 1. async helper that really talks to one MCP server
async def _call_one_server(param: MCPServerSseParams,
payload: dict[str, any]) -> str:
async with MCPServerSse(param, cache_tools_list=True) as srv:
# ↓ fastmcp returns a pydantic model; make it jsonserialisable
res = await srv.call_tool(payload)
try:
return res.model_dump() # fastmcp ≥0.2
except AttributeError:
return res # plain dict / str
# 2. public sync wrapper what the Agent imports & uses
def batch_mcp_flow(params: list[MCPServerSseParams],
payload: dict[str, any]) -> list[str]:
"""Blocking helper fanout to every MCP server given in *params*."""
return asyncio.run(_batch(params, payload))
# 3. little async fanout
async def _batch(params: list[MCPServerSseParams],
payload: dict[str, any]) -> list[str]:
coros = [_call_one_server(p, payload) for p in params]
return await asyncio.gather(*coros)
```
---
## 2  `structs/agent.py`
Replace **only** the `mcp_execution_flow` method with the synchronous
wrapper that now returns the real value (note: `payload` is a *string* here):
```python
# inside class Agent
def mcp_execution_flow(self, response: str) -> str:
"""
Forward the JSON toolcall coming from the LLM to all MCP servers
listed in self.mcp_servers.
"""
try:
payload = json.loads(response) # {"tool_name": …}
results = batch_mcp_flow(self.mcp_servers, payload)
# `batch_mcp_flow` already blocks, so results is a list[str]
return any_to_str(results[0] if len(results) == 1 else results)
except Exception as err:
logger.error(f"MCP flow failed: {err}")
return f"[MCP-error] {err}"
```
*(you may keep the rest of your big `Agent` class unchanged)*
---
## 3  clientside tiny polish
When you start the mock server you exposed SSE at `http://0.0.0.0:8000`.
Thats fine the fastmcp helper discovers the SSE endpoint automatically,
so the URL in `MCPServerSseParams` is correct.
---
## 4  Quick smoketest
1. **Start the mock server** (in one shell):
```bash
python math_mock_server.py # prints “Starting Mock Math Server…”
```
2. **Run the client** (your `mcp_client.py`) in another shell:
```
Enter your query (or 'exit' to quit): add 4 and 19834
Math Agent Response: 19838
```
No warning, no `[MCPerror]`, and you get the right answer.
---
### Why this works
* `async with MCPServerSse(...) as srv:` guarantees `connect()` and `cleanup()` are
called and awaited.
* `await srv.call_tool(payload)` actually sends the JSONRPC request.
* `asyncio.run()` in the wrapper lets the rest of your Agent stay 100 % synchronous.
* Any exception bubbles up, gets logged, and your Agent sees
`[MCPerror] …` instead of mysterious `None`.
You can now add more servers to `self.mcp_servers` theyll all be invoked in
parallel, and the first element of the returned list will always hold the
result from the first server (adapt as needed).
Happy calculating!

@ -1,114 +0,0 @@
Youve fixed the *RuntimeWarning* by wrapping the coroutine, but now the call never actually reaches the mock server.
Two things are still wrong:
| symptom | real cause |
|---------|------------|
| **`__aenter__`** error from `process_param` | `MCPServerSse` *is* an asynccontextmanager; you must use **`async with`** (or call its `connect/cleanup` explicitly). |
| **“No result returned from MCP server”** | we never awaited `call_tool`, so the request was never sent; the wrapper returned `None`. |
Below is a minimal, fullyworking patch set.
Apply it and the *MathMockServer* will answer correctly (e.g. `add 4 and 19834 → 19838`).
---
## 1  `tools/mcp_integration.py`
```python
# keep the import you already added
import asyncio
# ────────────────────────────────────────────────────────────
# 1. async helper that really talks to one MCP server
async def _call_one_server(param: MCPServerSseParams,
payload: dict[str, any]) -> str:
async with MCPServerSse(param, cache_tools_list=True) as srv:
# ↓ fastmcp returns a pydantic model; make it jsonserialisable
res = await srv.call_tool(payload)
try:
return res.model_dump() # fastmcp ≥0.2
except AttributeError:
return res # plain dict / str
# 2. public sync wrapper what the Agent imports & uses
def batch_mcp_flow(params: list[MCPServerSseParams],
payload: dict[str, any]) -> list[str]:
"""Blocking helper fanout to every MCP server given in *params*."""
return asyncio.run(_batch(params, payload))
# 3. little async fanout
async def _batch(params: list[MCPServerSseParams],
payload: dict[str, any]) -> list[str]:
coros = [_call_one_server(p, payload) for p in params]
return await asyncio.gather(*coros)
```
---
## 2  `structs/agent.py`
Replace **only** the `mcp_execution_flow` method with the synchronous
wrapper that now returns the real value (note: `payload` is a *string* here):
```python
# inside class Agent
def mcp_execution_flow(self, response: str) -> str:
"""
Forward the JSON toolcall coming from the LLM to all MCP servers
listed in self.mcp_servers.
"""
try:
payload = json.loads(response) # {"tool_name": …}
results = batch_mcp_flow(self.mcp_servers, payload)
# `batch_mcp_flow` already blocks, so results is a list[str]
return any_to_str(results[0] if len(results) == 1 else results)
except Exception as err:
logger.error(f"MCP flow failed: {err}")
return f"[MCP-error] {err}"
```
*(you may keep the rest of your big `Agent` class unchanged)*
---
## 3  clientside tiny polish
When you start the mock server you exposed SSE at `http://0.0.0.0:8000`.
Thats fine the fastmcp helper discovers the SSE endpoint automatically,
so the URL in `MCPServerSseParams` is correct.
---
## 4  Quick smoketest
1. **Start the mock server** (in one shell):
```bash
python math_mock_server.py # prints “Starting Mock Math Server…”
```
2. **Run the client** (your `mcp_client.py`) in another shell:
```
Enter your query (or 'exit' to quit): add 4 and 19834
Math Agent Response: 19838
```
No warning, no `[MCPerror]`, and you get the right answer.
---
### Why this works
* `async with MCPServerSse(...) as srv:` guarantees `connect()` and `cleanup()` are
called and awaited.
* `await srv.call_tool(payload)` actually sends the JSONRPC request.
* `asyncio.run()` in the wrapper lets the rest of your Agent stay 100 % synchronous.
* Any exception bubbles up, gets logged, and your Agent sees
`[MCPerror] …` instead of mysterious `None`.
You can now add more servers to `self.mcp_servers` theyll all be invoked in
parallel, and the first element of the returned list will always hold the
result from the first server (adapt as needed).
Happy calculating!

@ -1,123 +0,0 @@
Your mock Math MCP server is running fine  the errors are coming from the
**Swarms Agent** side:
1. **`mcp_execution_flow` is missing**
2. The agent reports **`CustomStreamWrapper …`** instead of the models text
because `streaming_on=True` but the helper that “unwraps” the stream is not
in place yet.
Below is the minimal patch set that makes the smoke test work today.
Apply the three diffs, reinstall, and rerun `examples/mcp_example/mcp_client.py`.
---
### ① Add `mcp_execution_flow` to the Agent
Put this anywhere inside **swarms/structs/agent.py** (e.g. just under
`parse_and_execute_tools`).
It converts the LLMfunctioncall JSON into a normal dict, then dispatches it
to every server you supplied in `mcp_servers`.
```python
# --- MCP TOOL EXECUTION -------------------------------------------------
def mcp_execution_flow(self, response: str | dict) -> str | None:
"""
Detect an LLM functioncall style response and proxy the call to the
configured MCP servers. Returns the tool output as a string so it can
be fed back into the conversation.
"""
if not self.mcp_servers:
return None
try:
# LLM may give us a JSON string or alreadyparsed dict
if isinstance(response, str):
call_dict = json.loads(response)
else:
call_dict = response
if not isinstance(call_dict, dict):
return None # nothing to do
if "tool_name" not in call_dict and "name" not in call_dict:
return None # not a tool call
from swarms.tools.mcp_integration import batch_mcp_flow
out = batch_mcp_flow(self.mcp_servers, call_dict)
return any_to_str(out)
except Exception as e:
logger.error(f"MCP flow failed: {e}")
return f"[MCPerror] {e}"
```
---
### ② Expose `mcp_servers` on the Agent constructor
Earlier you commented it out; put it back so the attribute exists.
```diff
- # mcp_servers: List[MCPServerSseParams] = [],
+ mcp_servers: Optional[List[MCPServerSseParams]] = None,
*args, **kwargs,
):
...
- # self.mcp_servers = mcp_servers
+ self.mcp_servers = mcp_servers or []
```
---
### ③ Call the new flow inside `_run`
Replace the tiny block where you already try to use it:
```diff
- if self.tools is not None or hasattr(self, 'mcp_servers'):
+ if self.tools is not None or self.mcp_servers:
if self.tools:
out = self.parse_and_execute_tools(response)
- if hasattr(self, 'mcp_servers') and self.mcp_servers:
- out = self.mcp_execution_flow(response)
+ if self.mcp_servers:
+ mcp_out = self.mcp_execution_flow(response)
+ if mcp_out:
+ out = mcp_out
```
---
### ④ (Optionally) turn off streaming for now
Until you implement a streamunwrapper, just start the math agent with
`streaming_on=False`:
```python
math_agent = Agent(
...
streaming_on=False
)
```
---
### ⑤ Rerun the smoke test
```bash
pip install -U mcp typing_extensions
python examples/mcp_example/math_server.py # leave running
python examples/mcp_example/mcp_client.py
```
```
Enter your query: add 8 and 11
Math Agent Response: 19
```
No more attribute errors or `CustomStreamWrapper` objects.
You can now iterate on nicer output formatting or reenable streaming once you
unwrap the tokens.
Thats it  your Swarms agent is now able to call MCP tools via the mock
FastMCP math server.

@ -1,397 +0,0 @@
from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams, MCPServerSse, mcp_flow_get_tool_schema
from loguru import logger
import sys
import asyncio
import json
import httpx
import time
# Configure logging for more detailed output
logger.remove()
logger.add(sys.stdout,
level="DEBUG",
format="{time} | {level} | {module}:{function}:{line} - {message}")
# Relaxed prompt that doesn't enforce strict JSON formatting
# Create server parameters
def get_server_params():
"""Get the MCP server connection parameters."""
return MCPServerSseParams(
url=
"http://127.0.0.1:8000", # Use 127.0.0.1 instead of localhost/0.0.0.0
headers={
"Content-Type": "application/json",
"Accept": "text/event-stream"
},
timeout=15.0, # Longer timeout
sse_read_timeout=60.0 # Longer read timeout
)
def initialize_math_system():
"""Initialize the math agent with MCP server configuration."""
# Create the agent with the MCP server configuration
math_agent = Agent(agent_name="Math Assistant",
agent_description="Friendly math calculator",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[get_server_params()],
model_name="gpt-3.5-turbo",
verbose=True)
return math_agent
# Function to get list of available tools from the server
async def get_tools_list():
"""Fetch and format the list of available tools from the server."""
try:
server_params = get_server_params()
tools = await mcp_flow_get_tool_schema(server_params)
if not tools:
return "No tools are currently available on the server."
# Format the tools information
tools_info = "Available tools:\n"
for tool in tools:
tools_info += f"\n- {tool.name}: {tool.description or 'No description'}\n"
if tool.parameters and hasattr(tool.parameters, 'properties'):
tools_info += " Parameters:\n"
for param_name, param_info in tool.parameters.properties.items(
):
param_type = param_info.get('type', 'unknown')
param_desc = param_info.get('description',
'No description')
tools_info += f" - {param_name} ({param_type}): {param_desc}\n"
return tools_info
except Exception as e:
logger.error(f"Failed to get tools list: {e}")
return f"Error retrieving tools list: {str(e)}"
# Function to test server connection
def test_server_connection():
"""Test if the server is reachable and responsive."""
try:
# Create a short-lived connection to check server
server = MCPServerSse(get_server_params())
# Try connecting (this is synchronous)
asyncio.run(server.connect())
asyncio.run(server.cleanup())
logger.info("✅ Server connection test successful")
return True
except Exception as e:
logger.error(f"❌ Server connection test failed: {e}")
return False
# Manual math operation handler as ultimate fallback
def manual_math(query):
"""Parse and solve a math problem without using the server."""
query = query.lower()
# Check if user is asking for available tools/functions
if "list" in query and ("tools" in query or "functions" in query
or "operations" in query):
return """
Available tools:
1. add - Add two numbers together (e.g., "add 3 and 4")
2. multiply - Multiply two numbers together (e.g., "multiply 5 and 6")
3. divide - Divide the first number by the second (e.g., "divide 10 by 2")
"""
try:
if "add" in query or "plus" in query or "sum" in query:
# Extract numbers using a simple approach
numbers = [int(s) for s in query.split() if s.isdigit()]
if len(numbers) >= 2:
result = numbers[0] + numbers[1]
return f"The sum of {numbers[0]} and {numbers[1]} is {result}"
elif "multiply" in query or "times" in query or "product" in query:
numbers = [int(s) for s in query.split() if s.isdigit()]
if len(numbers) >= 2:
result = numbers[0] * numbers[1]
return f"The product of {numbers[0]} and {numbers[1]} is {result}"
elif "divide" in query or "quotient" in query:
numbers = [int(s) for s in query.split() if s.isdigit()]
if len(numbers) >= 2:
if numbers[1] == 0:
return "Cannot divide by zero"
result = numbers[0] / numbers[1]
return f"{numbers[0]} divided by {numbers[1]} is {result}"
return "I couldn't parse your math request. Try something like 'add 3 and 4'."
except Exception as e:
logger.error(f"Manual math error: {e}")
return f"Error performing calculation: {str(e)}"
def main():
try:
logger.info("Initializing math system...")
# Test server connection first
server_available = test_server_connection()
if server_available:
math_agent = initialize_math_system()
print("\nMath Calculator Ready! (Server connection successful)")
else:
print(
"\nServer connection failed - using fallback calculator mode")
math_agent = None
print("Ask me any math question!")
print("Examples: 'what is 5 plus 3?' or 'can you multiply 4 and 6?'")
print("Type 'list tools' to see available operations")
print("Type 'exit' to quit\n")
while True:
try:
query = input("What would you like to calculate? ").strip()
if not query:
continue
if query.lower() == 'exit':
break
# Handle special commands
if query.lower() in ('list tools', 'show tools',
'available tools', 'what tools'):
if server_available:
# Get tools list from server
tools_info = asyncio.run(get_tools_list())
print(f"\n{tools_info}\n")
else:
# Use manual fallback
print(manual_math("list tools"))
continue
logger.info(f"Processing query: {query}")
# First try the agent if available
if math_agent and server_available:
try:
result = math_agent.run(query)
print(f"\nResult: {result}\n")
continue
except Exception as e:
logger.error(f"Agent error: {e}")
print("Agent encountered an error, trying fallback...")
# If agent fails or isn't available, use manual calculator
result = manual_math(query)
print(f"\nCalculation result: {result}\n")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
logger.error(f"Error processing query: {e}")
print(f"Sorry, there was an error: {str(e)}")
except Exception as e:
logger.error(f"System initialization error: {e}")
print(f"Failed to start the math system: {str(e)}")
if __name__ == "__main__":
main() "from fastmcp import FastMCP
from loguru import logger
import time
import json
# Create the MCP server with detailed debugging
mcp = FastMCP(
host="0.0.0.0", # Bind to all interfaces
port=8000,
transport="sse",
require_session_id=False,
cors_allowed_origins=["*"], # Allow connections from any origin
debug=True # Enable debug mode for more verbose output
)
# Add a more flexible parsing approach
def parse_input(input_str):
"""Parse input that could be JSON or natural language."""
try:
# First try to parse as JSON
return json.loads(input_str)
except json.JSONDecodeError:
# If not JSON, try to parse natural language
input_lower = input_str.lower()
# Parse for addition
if "add" in input_lower or "plus" in input_lower or "sum" in input_lower:
# Extract numbers - very simple approach
numbers = [int(s) for s in input_lower.split() if s.isdigit()]
if len(numbers) >= 2:
return {"a": numbers[0], "b": numbers[1]}
# Parse for multiplication
if "multiply" in input_lower or "times" in input_lower or "product" in input_lower:
numbers = [int(s) for s in input_lower.split() if s.isdigit()]
if len(numbers) >= 2:
return {"a": numbers[0], "b": numbers[1]}
# Parse for division
if "divide" in input_lower or "quotient" in input_lower:
numbers = [int(s) for s in input_lower.split() if s.isdigit()]
if len(numbers) >= 2:
return {"a": numbers[0], "b": numbers[1]}
# Could not parse successfully
return None
# Define tools with more flexible input handling
@mcp.tool()
def add(input_str=None, a=None, b=None):
"""Add two numbers. Can accept JSON parameters or natural language.
Args:
input_str (str, optional): Natural language input to parse
a (int, optional): First number if provided directly
b (int, optional): Second number if provided directly
Returns:
str: A message containing the sum
"""
logger.info(f"Add tool called with input_str={input_str}, a={a}, b={b}")
# If we got a natural language string instead of parameters
if input_str and not (a is not None and b is not None):
parsed = parse_input(input_str)
if parsed:
a = parsed.get("a")
b = parsed.get("b")
# Validate we have what we need
if a is None or b is None:
return "Sorry, I couldn't understand the numbers to add"
try:
a = int(a)
b = int(b)
result = a + b
return f"The sum of {a} and {b} is {result}"
except ValueError:
return "Please provide valid numbers for addition"
@mcp.tool()
def multiply(input_str=None, a=None, b=None):
"""Multiply two numbers. Can accept JSON parameters or natural language.
Args:
input_str (str, optional): Natural language input to parse
a (int, optional): First number if provided directly
b (int, optional): Second number if provided directly
Returns:
str: A message containing the product
"""
logger.info(
f"Multiply tool called with input_str={input_str}, a={a}, b={b}")
# If we got a natural language string instead of parameters
if input_str and not (a is not None and b is not None):
parsed = parse_input(input_str)
if parsed:
a = parsed.get("a")
b = parsed.get("b")
# Validate we have what we need
if a is None or b is None:
return "Sorry, I couldn't understand the numbers to multiply"
try:
a = int(a)
b = int(b)
result = a * b
return f"The product of {a} and {b} is {result}"
except ValueError:
return "Please provide valid numbers for multiplication"
@mcp.tool()
def divide(input_str=None, a=None, b=None):
"""Divide two numbers. Can accept JSON parameters or natural language.
Args:
input_str (str, optional): Natural language input to parse
a (int, optional): Numerator if provided directly
b (int, optional): Denominator if provided directly
Returns:
str: A message containing the division result or an error message
"""
logger.info(f"Divide tool called with input_str={input_str}, a={a}, b={b}")
# If we got a natural language string instead of parameters
if input_str and not (a is not None and b is not None):
parsed = parse_input(input_str)
if parsed:
a = parsed.get("a")
b = parsed.get("b")
# Validate we have what we need
if a is None or b is None:
return "Sorry, I couldn't understand the numbers to divide"
try:
a = int(a)
b = int(b)
if b == 0:
logger.warning("Division by zero attempted")
return "Cannot divide by zero"
result = a / b
return f"{a} divided by {b} is {result}"
except ValueError:
return "Please provide valid numbers for division"
if __name__ == "__main__":
try:
logger.info("Starting math server on http://0.0.0.0:8000")
print("Math MCP Server is running. Press Ctrl+C to stop.")
print(
"Server is configured to accept both JSON and natural language input"
)
# Add a small delay to ensure logging is complete before the server starts
time.sleep(0.5)
# Run the MCP server
mcp.run()
except KeyboardInterrupt:
logger.info("Server shutdown requested")
print("\nShutting down server...")
except Exception as e:
logger.error(f"Server error: {e}")
raise
" server is runnig poeroperly "2025-04-20 17:35:01.251 | INFO | __main__:<module>:161 - Starting math server on http://0.0.0.0:8000
Math MCP Server is running. Press Ctrl+C to stop.
Server is configured to accept both JSON and natural language input
[04/20/25 17:35:01] INFO Starting server "FastMCP"... " butwhy im getting these errore "2025-04-20T17:35:04.174629+0000 | INFO | mcp_client:main:159 - Initializing math system...
2025-04-20T17:35:04.203591+0000 | ERROR | mcp_integration:connect:89 - Error initializing MCP server: unhandled errors in a TaskGroup (1 sub-exception)
2025-04-20T17:35:04.204437+0000 | ERROR | mcp_client:test_server_connection:110 - ❌ Server connection test failed: unhandled errors in a TaskGroup (1 sub-exception)
Server connection failed - using fallback calculator mode
Ask me any math question!
Examples: 'what is 5 plus 3?' or 'can you multiply 4 and 6?'
Type 'list tools' to see available operations
Type 'exit' to quit
What would you like to calculate? "

@ -1,83 +0,0 @@
from swarms import Agent
from swarms.tools.mcp_integration import MCPServerSseParams
from loguru import logger
# Comprehensive math prompt that encourages proper JSON formatting
MATH_AGENT_PROMPT = """
You are a helpful math calculator assistant.
Your role is to understand natural language math requests and perform calculations.
When asked to perform calculations:
1. Determine the operation (add, multiply, or divide)
2. Extract the numbers from the request
3. Use the appropriate math operation tool
FORMAT YOUR TOOL CALLS AS JSON with this format:
{"tool_name": "add", "a": <first_number>, "b": <second_number>}
or
{"tool_name": "multiply", "a": <first_number>, "b": <second_number>}
or
{"tool_name": "divide", "a": <first_number>, "b": <second_number>}
Always respond with a tool call in JSON format first, followed by a brief explanation.
"""
def initialize_math_system():
"""Initialize the math agent with MCP server configuration."""
# Configure the MCP server connection
math_server = MCPServerSseParams(
url="http://0.0.0.0:8000",
headers={"Content-Type": "application/json"},
timeout=5.0,
sse_read_timeout=30.0
)
# Create the agent with the MCP server configuration
math_agent = Agent(
agent_name="Math Assistant",
agent_description="Friendly math calculator",
system_prompt=MATH_AGENT_PROMPT,
max_loops=1,
mcp_servers=[math_server], # Pass MCP server config as a list
model_name="gpt-3.5-turbo",
verbose=True # Enable verbose mode to see more details
)
return math_agent
def main():
try:
logger.info("Initializing math system...")
math_agent = initialize_math_system()
print("\nMath Calculator Ready!")
print("Ask me any math question!")
print("Examples: 'what is 5 plus 3?' or 'can you multiply 4 and 6?'")
print("Type 'exit' to quit\n")
while True:
try:
query = input("What would you like to calculate? ").strip()
if not query:
continue
if query.lower() == 'exit':
break
logger.info(f"Processing query: {query}")
result = math_agent.run(query)
print(f"\nResult: {result}\n")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
logger.error(f"Error processing query: {e}")
print(f"Sorry, there was an error: {str(e)}")
except Exception as e:
logger.error(f"System initialization error: {e}")
print(f"Failed to start the math system: {str(e)}")
if __name__ == "__main__":
main()

@ -1,113 +0,0 @@
if not available "Traceback (most recent call last):
File "/home/runner/workspace/examples/mcp_example/mcp_client.py", line 4, in <module>
from swarms.prompts.agent_prompts import FINANCE_AGENT_PROMPT, MATH_AGENT_PROMPT
ImportError: cannot import name 'FINANCE_AGENT_PROMPT' from 'swarms.prompts.agent_prompts' (/home/runner/workspace/.pythonlibs/lib/python3.10/site-packages/swarms/prompts/agent_prompts.py)" add the peorppoert "" I WNAT THIS AS TO ME EXMPALE SERVER THAT I WANT TO CONNTECT TO DO THE SMOCKE TEST "# Browserbase MCP Server
![cover](../assets/browserbase-mcp.png)
## Get Started
1. Run `npm install` to install the necessary dependencies, then run `npm run build` to get `dist/index.js`.
2. Set up your Claude Desktop configuration to use the server.
```json
{
"mcpServers": {
"browserbase": {
"command": "node",
"args": ["path/to/mcp-server-browserbase/browserbase/dist/index.js"],
"env": {
"BROWSERBASE_API_KEY": "<YOUR_BROWSERBASE_API_KEY>",
"BROWSERBASE_PROJECT_ID": "<YOUR_BROWSERBASE_PROJECT_ID>"
}
}
}
}
```
3. Restart your Claude Desktop app and you should see the tools available clicking the 🔨 icon.
4. Start using the tools! Below is an image of Claude closing a browser session.
<p align="center">
<img src="../assets/browserbase-demo.png" alt="demo" width="600"/>
</p>
## Tools
### Browserbase API
- **browserbase_create_session**
- Create a new cloud browser session using Browserbase
- No required inputs
- **browserbase_navigate**
- Navigate to any URL in the browser
- Input: `url` (string)
- **browserbase_screenshot**
- Capture screenshots of the entire page or specific elements
- Inputs:
- `name` (string, required): Name for the screenshot
- `selector` (string, optional): CSS selector for element to screenshot
- `width` (number, optional, default: 800): Screenshot width
- `height` (number, optional, default: 600): Screenshot height
- **browserbase_click**
- Click elements on the page
- Input: `selector` (string): CSS selector for element to click
- **browserbase_fill**
- Fill out input fields
- Inputs:
- `selector` (string): CSS selector for input field
- `value` (string): Value to fill
- **browserbase_evaluate**
- Execute JavaScript in the browser console
- Input: `script` (string): JavaScript code to execute
- **browserbase_get_content**
- Extract all content from the current page
- Input: `selector` (string, optional): CSS selector to get content from specific elements
- **browserbase_parallel_sessions**
- Create multiple browser sessions and navigate to different URLs
- Input: `sessions` (array): Array of objects containing:
- `url` (string): URL to navigate to
- `id` (string): Session identifier
### Resources
The server provides access to two types of resources:
1. **Console Logs** (`console://logs`)
- Browser console output in text format
- Includes all console messages from the browser
2. **Screenshots** (`screenshot://<name>`)
- PNG images of captured screenshots
- Accessible via the screenshot name specified during capture
## Key Features
- Cloud browser automation
- Web data extraction
- Console log monitoring
- Screenshot capabilities
- JavaScript execution
- Basic web interaction (navigation, clicking, form filling)
## License
This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository."

@ -1,392 +0,0 @@
this si the oreginal firle siese for integration base dont his update it not for sepcief case the mcop_inteation is used it inteage in aget firle"from __future__ import annotations
from typing import Any, List
from loguru import logger
import abc
import asyncio
from contextlib import AbstractAsyncContextManager, AsyncExitStack
from pathlib import Path
from typing import Literal
from anyio.streams.memory import (
MemoryObjectReceiveStream,
MemoryObjectSendStream,
)
from mcp import (
ClientSession,
StdioServerParameters,
Tool as MCPTool,
stdio_client,
)
from mcp.client.sse import sse_client
from mcp.types import CallToolResult, JSONRPCMessage
from typing_extensions import NotRequired, TypedDict
from swarms.utils.any_to_str import any_to_str
class MCPServer(abc.ABC):
"""Base class for Model Context Protocol servers."""
@abc.abstractmethod
async def connect(self):
"""Connect to the server. For example, this might mean spawning a subprocess or
opening a network connection. The server is expected to remain connected until
`cleanup()` is called.
"""
pass
@property
@abc.abstractmethod
def name(self) -> str:
"""A readable name for the server."""
pass
@abc.abstractmethod
async def cleanup(self):
"""Cleanup the server. For example, this might mean closing a subprocess or
closing a network connection.
"""
pass
@abc.abstractmethod
async def list_tools(self) -> list[MCPTool]:
"""List the tools available on the server."""
pass
@abc.abstractmethod
async def call_tool(
self, tool_name: str, arguments: dict[str, Any] | None
) -> CallToolResult:
"""Invoke a tool on the server."""
pass
class _MCPServerWithClientSession(MCPServer, abc.ABC):
"""Base class for MCP servers that use a `ClientSession` to communicate with the server."""
def __init__(self, cache_tools_list: bool):
"""
Args:
cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
cached and only fetched from the server once. If `False`, the tools list will be
fetched from the server on each call to `list_tools()`. The cache can be invalidated
by calling `invalidate_tools_cache()`. You should set this to `True` if you know the
server will not change its tools list, because it can drastically improve latency
(by avoiding a round-trip to the server every time).
"""
self.session: ClientSession | None = None
self.exit_stack: AsyncExitStack = AsyncExitStack()
self._cleanup_lock: asyncio.Lock = asyncio.Lock()
self.cache_tools_list = cache_tools_list
# The cache is always dirty at startup, so that we fetch tools at least once
self._cache_dirty = True
self._tools_list: list[MCPTool] | None = None
@abc.abstractmethod
def create_streams(
self,
) -> AbstractAsyncContextManager[
tuple[
MemoryObjectReceiveStream[JSONRPCMessage | Exception],
MemoryObjectSendStream[JSONRPCMessage],
]
]:
"""Create the streams for the server."""
pass
async def __aenter__(self):
await self.connect()
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.cleanup()
def invalidate_tools_cache(self):
"""Invalidate the tools cache."""
self._cache_dirty = True
async def connect(self):
"""Connect to the server."""
try:
transport = await self.exit_stack.enter_async_context(
self.create_streams()
)
read, write = transport
session = await self.exit_stack.enter_async_context(
ClientSession(read, write)
)
await session.initialize()
self.session = session
except Exception as e:
logger.error(f"Error initializing MCP server: {e}")
await self.cleanup()
raise
async def list_tools(self) -> list[MCPTool]:
"""List the tools available on the server."""
if not self.session:
raise Exception(
"Server not initialized. Make sure you call `connect()` first."
)
# Return from cache if caching is enabled, we have tools, and the cache is not dirty
if (
self.cache_tools_list
and not self._cache_dirty
and self._tools_list
):
return self._tools_list
# Reset the cache dirty to False
self._cache_dirty = False
# Fetch the tools from the server
self._tools_list = (await self.session.list_tools()).tools
return self._tools_list
async def call_tool(
self, arguments: dict[str, Any] | None
) -> CallToolResult:
"""Invoke a tool on the server."""
tool_name = arguments.get("tool_name") or arguments.get(
"name"
)
if not tool_name:
raise Exception("No tool name found in arguments")
if not self.session:
raise Exception(
"Server not initialized. Make sure you call `connect()` first."
)
return await self.session.call_tool(tool_name, arguments)
async def cleanup(self):
"""Cleanup the server."""
async with self._cleanup_lock:
try:
await self.exit_stack.aclose()
self.session = None
except Exception as e:
logger.error(f"Error cleaning up server: {e}")
class MCPServerStdioParams(TypedDict):
"""Mirrors `mcp.client.stdio.StdioServerParameters`, but lets you pass params without another
import.
"""
command: str
"""The executable to run to start the server. For example, `python` or `node`."""
args: NotRequired[list[str]]
"""Command line args to pass to the `command` executable. For example, `['foo.py']` or
`['server.js', '--port', '8080']`."""
env: NotRequired[dict[str, str]]
"""The environment variables to set for the server. ."""
cwd: NotRequired[str | Path]
"""The working directory to use when spawning the process."""
encoding: NotRequired[str]
"""The text encoding used when sending/receiving messages to the server. Defaults to `utf-8`."""
encoding_error_handler: NotRequired[
Literal["strict", "ignore", "replace"]
]
"""The text encoding error handler. Defaults to `strict`.
See https://docs.python.org/3/library/codecs.html#codec-base-classes for
explanations of possible values.
"""
class MCPServerStdio(_MCPServerWithClientSession):
"""MCP server implementation that uses the stdio transport. See the [spec]
(https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio) for
details.
"""
def __init__(
self,
params: MCPServerStdioParams,
cache_tools_list: bool = False,
name: str | None = None,
):
"""Create a new MCP server based on the stdio transport.
Args:
params: The params that configure the server. This includes the command to run to
start the server, the args to pass to the command, the environment variables to
set for the server, the working directory to use when spawning the process, and
the text encoding used when sending/receiving messages to the server.
cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
cached and only fetched from the server once. If `False`, the tools list will be
fetched from the server on each call to `list_tools()`. The cache can be
invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
if you know the server will not change its tools list, because it can drastically
improve latency (by avoiding a round-trip to the server every time).
name: A readable name for the server. If not provided, we'll create one from the
command.
"""
super().__init__(cache_tools_list)
self.params = StdioServerParameters(
command=params["command"],
args=params.get("args", []),
env=params.get("env"),
cwd=params.get("cwd"),
encoding=params.get("encoding", "utf-8"),
encoding_error_handler=params.get(
"encoding_error_handler", "strict"
),
)
self._name = name or f"stdio: {self.params.command}"
def create_streams(
self,
) -> AbstractAsyncContextManager[
tuple[
MemoryObjectReceiveStream[JSONRPCMessage | Exception],
MemoryObjectSendStream[JSONRPCMessage],
]
]:
"""Create the streams for the server."""
return stdio_client(self.params)
@property
def name(self) -> str:
"""A readable name for the server."""
return self._name
class MCPServerSseParams(TypedDict):
"""Mirrors the params in`mcp.client.sse.sse_client`."""
url: str
"""The URL of the server."""
headers: NotRequired[dict[str, str]]
"""The headers to send to the server."""
timeout: NotRequired[float]
"""The timeout for the HTTP request. Defaults to 5 seconds."""
sse_read_timeout: NotRequired[float]
"""The timeout for the SSE connection, in seconds. Defaults to 5 minutes."""
class MCPServerSse(_MCPServerWithClientSession):
"""MCP server implementation that uses the HTTP with SSE transport. See the [spec]
(https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse)
for details.
"""
def __init__(
self,
params: MCPServerSseParams,
cache_tools_list: bool = False,
name: str | None = None,
):
"""Create a new MCP server based on the HTTP with SSE transport.
Args:
params: The params that configure the server. This includes the URL of the server,
the headers to send to the server, the timeout for the HTTP request, and the
timeout for the SSE connection.
cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
cached and only fetched from the server once. If `False`, the tools list will be
fetched from the server on each call to `list_tools()`. The cache can be
invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
if you know the server will not change its tools list, because it can drastically
improve latency (by avoiding a round-trip to the server every time).
name: A readable name for the server. If not provided, we'll create one from the
URL.
"""
super().__init__(cache_tools_list)
self.params = params
self._name = name or f"sse: {self.params['url']}"
def create_streams(
self,
) -> AbstractAsyncContextManager[
tuple[
MemoryObjectReceiveStream[JSONRPCMessage | Exception],
MemoryObjectSendStream[JSONRPCMessage],
]
]:
"""Create the streams for the server."""
return sse_client(
url=self.params["url"],
headers=self.params.get("headers", None),
timeout=self.params.get("timeout", 5),
sse_read_timeout=self.params.get(
"sse_read_timeout", 60 * 5
),
)
@property
def name(self) -> str:
"""A readable name for the server."""
return self._name
def mcp_flow_get_tool_schema(
params: MCPServerSseParams,
) -> MCPServer:
server = MCPServerSse(params, cache_tools_list=True)
# Connect the server
asyncio.run(server.connect())
# Return the server
output = asyncio.run(server.list_tools())
# Cleanup the server
asyncio.run(server.cleanup())
return output.model_dump()
def mcp_flow(
params: MCPServerSseParams,
function_call: dict[str, Any],
) -> MCPServer:
server = MCPServerSse(params, cache_tools_list=True)
# Connect the server
asyncio.run(server.connect())
# Return the server
output = asyncio.run(server.call_tool(function_call))
output = output.model_dump()
# Cleanup the server
asyncio.run(server.cleanup())
return any_to_str(output)
def batch_mcp_flow(
params: List[MCPServerSseParams],
function_call: List[dict[str, Any]] = [],
) -> MCPServer:
output_list = []
for param in params:
output = mcp_flow(param, function_call)
output_list.append(output)
return output_list"

@ -1,392 +0,0 @@
this si the oreginal firle siese for integration base dont his update it not for sepcief case the mcop_inteation is used it inteage in aget firle"from __future__ import annotations
from typing import Any, List
from loguru import logger
import abc
import asyncio
from contextlib import AbstractAsyncContextManager, AsyncExitStack
from pathlib import Path
from typing import Literal
from anyio.streams.memory import (
MemoryObjectReceiveStream,
MemoryObjectSendStream,
)
from mcp import (
ClientSession,
StdioServerParameters,
Tool as MCPTool,
stdio_client,
)
from mcp.client.sse import sse_client
from mcp.types import CallToolResult, JSONRPCMessage
from typing_extensions import NotRequired, TypedDict
from swarms.utils.any_to_str import any_to_str
class MCPServer(abc.ABC):
"""Base class for Model Context Protocol servers."""
@abc.abstractmethod
async def connect(self):
"""Connect to the server. For example, this might mean spawning a subprocess or
opening a network connection. The server is expected to remain connected until
`cleanup()` is called.
"""
pass
@property
@abc.abstractmethod
def name(self) -> str:
"""A readable name for the server."""
pass
@abc.abstractmethod
async def cleanup(self):
"""Cleanup the server. For example, this might mean closing a subprocess or
closing a network connection.
"""
pass
@abc.abstractmethod
async def list_tools(self) -> list[MCPTool]:
"""List the tools available on the server."""
pass
@abc.abstractmethod
async def call_tool(
self, tool_name: str, arguments: dict[str, Any] | None
) -> CallToolResult:
"""Invoke a tool on the server."""
pass
class _MCPServerWithClientSession(MCPServer, abc.ABC):
"""Base class for MCP servers that use a `ClientSession` to communicate with the server."""
def __init__(self, cache_tools_list: bool):
"""
Args:
cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
cached and only fetched from the server once. If `False`, the tools list will be
fetched from the server on each call to `list_tools()`. The cache can be invalidated
by calling `invalidate_tools_cache()`. You should set this to `True` if you know the
server will not change its tools list, because it can drastically improve latency
(by avoiding a round-trip to the server every time).
"""
self.session: ClientSession | None = None
self.exit_stack: AsyncExitStack = AsyncExitStack()
self._cleanup_lock: asyncio.Lock = asyncio.Lock()
self.cache_tools_list = cache_tools_list
# The cache is always dirty at startup, so that we fetch tools at least once
self._cache_dirty = True
self._tools_list: list[MCPTool] | None = None
@abc.abstractmethod
def create_streams(
self,
) -> AbstractAsyncContextManager[
tuple[
MemoryObjectReceiveStream[JSONRPCMessage | Exception],
MemoryObjectSendStream[JSONRPCMessage],
]
]:
"""Create the streams for the server."""
pass
async def __aenter__(self):
await self.connect()
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.cleanup()
def invalidate_tools_cache(self):
"""Invalidate the tools cache."""
self._cache_dirty = True
async def connect(self):
"""Connect to the server."""
try:
transport = await self.exit_stack.enter_async_context(
self.create_streams()
)
read, write = transport
session = await self.exit_stack.enter_async_context(
ClientSession(read, write)
)
await session.initialize()
self.session = session
except Exception as e:
logger.error(f"Error initializing MCP server: {e}")
await self.cleanup()
raise
async def list_tools(self) -> list[MCPTool]:
"""List the tools available on the server."""
if not self.session:
raise Exception(
"Server not initialized. Make sure you call `connect()` first."
)
# Return from cache if caching is enabled, we have tools, and the cache is not dirty
if (
self.cache_tools_list
and not self._cache_dirty
and self._tools_list
):
return self._tools_list
# Reset the cache dirty to False
self._cache_dirty = False
# Fetch the tools from the server
self._tools_list = (await self.session.list_tools()).tools
return self._tools_list
async def call_tool(
self, arguments: dict[str, Any] | None
) -> CallToolResult:
"""Invoke a tool on the server."""
tool_name = arguments.get("tool_name") or arguments.get(
"name"
)
if not tool_name:
raise Exception("No tool name found in arguments")
if not self.session:
raise Exception(
"Server not initialized. Make sure you call `connect()` first."
)
return await self.session.call_tool(tool_name, arguments)
async def cleanup(self):
"""Cleanup the server."""
async with self._cleanup_lock:
try:
await self.exit_stack.aclose()
self.session = None
except Exception as e:
logger.error(f"Error cleaning up server: {e}")
class MCPServerStdioParams(TypedDict):
"""Mirrors `mcp.client.stdio.StdioServerParameters`, but lets you pass params without another
import.
"""
command: str
"""The executable to run to start the server. For example, `python` or `node`."""
args: NotRequired[list[str]]
"""Command line args to pass to the `command` executable. For example, `['foo.py']` or
`['server.js', '--port', '8080']`."""
env: NotRequired[dict[str, str]]
"""The environment variables to set for the server. ."""
cwd: NotRequired[str | Path]
"""The working directory to use when spawning the process."""
encoding: NotRequired[str]
"""The text encoding used when sending/receiving messages to the server. Defaults to `utf-8`."""
encoding_error_handler: NotRequired[
Literal["strict", "ignore", "replace"]
]
"""The text encoding error handler. Defaults to `strict`.
See https://docs.python.org/3/library/codecs.html#codec-base-classes for
explanations of possible values.
"""
class MCPServerStdio(_MCPServerWithClientSession):
"""MCP server implementation that uses the stdio transport. See the [spec]
(https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio) for
details.
"""
def __init__(
self,
params: MCPServerStdioParams,
cache_tools_list: bool = False,
name: str | None = None,
):
"""Create a new MCP server based on the stdio transport.
Args:
params: The params that configure the server. This includes the command to run to
start the server, the args to pass to the command, the environment variables to
set for the server, the working directory to use when spawning the process, and
the text encoding used when sending/receiving messages to the server.
cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
cached and only fetched from the server once. If `False`, the tools list will be
fetched from the server on each call to `list_tools()`. The cache can be
invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
if you know the server will not change its tools list, because it can drastically
improve latency (by avoiding a round-trip to the server every time).
name: A readable name for the server. If not provided, we'll create one from the
command.
"""
super().__init__(cache_tools_list)
self.params = StdioServerParameters(
command=params["command"],
args=params.get("args", []),
env=params.get("env"),
cwd=params.get("cwd"),
encoding=params.get("encoding", "utf-8"),
encoding_error_handler=params.get(
"encoding_error_handler", "strict"
),
)
self._name = name or f"stdio: {self.params.command}"
def create_streams(
self,
) -> AbstractAsyncContextManager[
tuple[
MemoryObjectReceiveStream[JSONRPCMessage | Exception],
MemoryObjectSendStream[JSONRPCMessage],
]
]:
"""Create the streams for the server."""
return stdio_client(self.params)
@property
def name(self) -> str:
"""A readable name for the server."""
return self._name
class MCPServerSseParams(TypedDict):
"""Mirrors the params in`mcp.client.sse.sse_client`."""
url: str
"""The URL of the server."""
headers: NotRequired[dict[str, str]]
"""The headers to send to the server."""
timeout: NotRequired[float]
"""The timeout for the HTTP request. Defaults to 5 seconds."""
sse_read_timeout: NotRequired[float]
"""The timeout for the SSE connection, in seconds. Defaults to 5 minutes."""
class MCPServerSse(_MCPServerWithClientSession):
"""MCP server implementation that uses the HTTP with SSE transport. See the [spec]
(https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse)
for details.
"""
def __init__(
self,
params: MCPServerSseParams,
cache_tools_list: bool = False,
name: str | None = None,
):
"""Create a new MCP server based on the HTTP with SSE transport.
Args:
params: The params that configure the server. This includes the URL of the server,
the headers to send to the server, the timeout for the HTTP request, and the
timeout for the SSE connection.
cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
cached and only fetched from the server once. If `False`, the tools list will be
fetched from the server on each call to `list_tools()`. The cache can be
invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
if you know the server will not change its tools list, because it can drastically
improve latency (by avoiding a round-trip to the server every time).
name: A readable name for the server. If not provided, we'll create one from the
URL.
"""
super().__init__(cache_tools_list)
self.params = params
self._name = name or f"sse: {self.params['url']}"
def create_streams(
self,
) -> AbstractAsyncContextManager[
tuple[
MemoryObjectReceiveStream[JSONRPCMessage | Exception],
MemoryObjectSendStream[JSONRPCMessage],
]
]:
"""Create the streams for the server."""
return sse_client(
url=self.params["url"],
headers=self.params.get("headers", None),
timeout=self.params.get("timeout", 5),
sse_read_timeout=self.params.get(
"sse_read_timeout", 60 * 5
),
)
@property
def name(self) -> str:
"""A readable name for the server."""
return self._name
def mcp_flow_get_tool_schema(
params: MCPServerSseParams,
) -> MCPServer:
server = MCPServerSse(params, cache_tools_list=True)
# Connect the server
asyncio.run(server.connect())
# Return the server
output = asyncio.run(server.list_tools())
# Cleanup the server
asyncio.run(server.cleanup())
return output.model_dump()
def mcp_flow(
params: MCPServerSseParams,
function_call: dict[str, Any],
) -> MCPServer:
server = MCPServerSse(params, cache_tools_list=True)
# Connect the server
asyncio.run(server.connect())
# Return the server
output = asyncio.run(server.call_tool(function_call))
output = output.model_dump()
# Cleanup the server
asyncio.run(server.cleanup())
return any_to_str(output)
def batch_mcp_flow(
params: List[MCPServerSseParams],
function_call: List[dict[str, Any]] = [],
) -> MCPServer:
output_list = []
for param in params:
output = mcp_flow(param, function_call)
output_list.append(output)
return output_list"
Loading…
Cancel
Save