parent
1a96821024
commit
3aad5acb6f
@ -1,110 +0,0 @@
|
||||
# Browserbase MCP Server
|
||||
|
||||

|
||||
|
||||
## 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,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
|
||||
|
||||

|
||||
|
||||
## 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…
Reference in new issue