8000 feat: add to_mcp and example in workforce by MuggleJinx · Pull Request #2550 · camel-ai/camel · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: add to_mcp and example in workforce #2550

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 8, 2025
Merged

Conversation

MuggleJinx
Copy link
Collaborator

Description

Support workforce.to_mcp() function.

Checklist

Go over all the following points, and put an x in all the boxes that apply.

If you are unsure about any of these, don't hesitate to ask. We are here to help!

Copy link
Contributor
coderabbitai bot commented Jun 3, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A new to_mcp method was added to the Workforce class, enabling it to be served as a Modular Control Protocol (MCP) server for remote control and querying. Documentation for this method was added, and an example script demonstrates creating and running a workforce MCP server.

Changes

File(s) Change Summary
camel/societies/workforce/workforce.py Added to_mcp method to expose Workforce as an MCP server with multiple remote control endpoints.
docs/mintlify/reference/camel.societies.workforce.workforce.mdx Documented the new to_mcp method, detailing parameters and usage.
examples/workforce/simple_workforce_mcp.py New example script showing how to run a workforce as an MCP server and interact with it.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MCPServer
    participant Workforce

    Client->>MCPServer: process_task / get_workforce_info / add_worker
    MCPServer->>Workforce: Call corresponding method
    Workforce-->>MCPServer: Return result/status
    MCPServer-->>Client: Respond with result/status
Loading

Poem

In the warren of code, a new tunnel appears,
Workforce now listens with long, clever ears.
Through MCP magic, commands hop right in—
Add workers! Get info! Let teamwork begin!
So gather your agents, let tasks multiply—
This rabbit-built server is ready to try! 🐇


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@zjrwtx
Copy link
Collaborator
zjrwtx commented Jun 4, 2025

@coderabbitai review

Copy link
Contributor
coderabbitai bot commented Jun 4, 2025
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
camel/societies/workforce/workforce.py (2)

754-758: Split long error message for better readability.

The error message exceeds typical line length limits.

-                    return {
-                        "status": "error",
-                        "message": "Cannot add workers while workforce is running",  # noqa: E501
-                    }
+                    return {
+                        "status": "error",
+                        "message": (
+                            "Cannot add workers while workforce is running"
+                        ),
+                    }
🧰 Tools
🪛 Pylint (3.3.7)

[warning] 754-754: Access to a protected member _running of a client class

(W0212)


789-793: Apply consistent error message formatting.

For consistency with the previous suggestion, format this error message the same way.

-                    return {
-                        "status": "error",
-                        "message": "Cannot add workers while workforce is running",  # noqa: E501
-                    }
+                    return {
+                        "status": "error",
+                        "message": (
+                            "Cannot add workers while workforce is running"
+                        ),
+                    }
🧰 Tools
🪛 Pylint (3.3.7)

[warning] 789-789: Access to a protected member _running of a client class

(W0212)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1793418 and bfa26c9.

📒 Files selected for processing (3)
  • camel/societies/workforce/workforce.py (2 hunks)
  • docs/mintlify/reference/camel.societies.workforce.workforce.mdx (1 hunks)
  • examples/workforce/simple_workforce_mcp.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.py`: Review the python code against the google python style guide and point out any mismatches.

**/*.py: Review the python code against the google python style guide and point out any mismatches.

  • examples/workforce/simple_workforce_mcp.py
  • camel/societies/workforce/workforce.py
🧬 Code Graph Analysis (1)
examples/workforce/simple_workforce_mcp.py (3)
camel/agents/chat_agent.py (2)
  • ChatAgent (112-1859)
  • system_message (408-410)
camel/messages/base.py (2)
  • BaseMessage (55-553)
  • make_assistant_message (134-176)
camel/societies/workforce/workforce.py (4)
  • Workforce (51-825)
  • add_single_agent_worker (223-237)
  • add_single_agent_worker (746-775)
  • to_mcp (603-825)
🪛 Pylint (3.3.7)
examples/workforce/simple_workforce_mcp.py

[error] 30-30: Unable to import 'camel.agents'

(E0401)


[error] 31-31: Unable to import 'camel.messages'

(E0401)


[error] 32-32: Unable to import 'camel.societies.workforce'

(E0401)

camel/societies/workforce/workforce.py

[refactor] 603-603: Too many arguments (6/5)

(R0913)


[refactor] 603-603: Too many positional arguments (6/5)

(R0917)


[refactor] 603-603: Too many local variables (16/15)

(R0914)


[convention] 634-634: Import outside toplevel (mcp.server.fastmcp.FastMCP)

(C0415)


[warning] 636-639: Consider explicitly re-raising using 'except ImportError as exc' and 'raise ImportError("The 'mcp' package is required to use the to_mcp method. Install it with 'pip install mcp'.") from exc'

(W0707)


[warning] 682-682: Catching too general exception Exception

(W0718)


[warning] 698-698: Catching too general exception Exception

(W0718)


[warning] 708-708: Access to a protected member _children of a client class

(W0212)


[warning] 709-709: Access to a protected member _running of a client class

(W0212)


[warning] 710-710: Access to a protected member _pending_tasks of a client class

(W0212)


[warning] 713-713: Access to a protected member _task of a client class

(W0212)


[warning] 712-712: Access to a protected member _task of a client class

(W0212)


[warning] 723-723: Access to a protected member _children of a client class

(W0212)


[warning] 738-738: Access to a protected member _children of a client class

(W0212)


[warning] 739-739: Access to a protected member _running of a client class

(W0212)


[warning] 774-774: Catching too general exception Exception

(W0718)


[warning] 754-754: Access to a protected member _running of a client class

(W0212)


[warning] 772-772: Access to a protected member _children of a client class

(W0212)


[refactor] 778-778: Too many arguments (7/5)

(R0913)


[refactor] 778-778: Too many positional arguments (7/5)

(R0917)


[warning] 810-810: Catching too general exception Exception

(W0718)


[warning] 789-789: Access to a protected member _running of a client class

(W0212)


[warning] 808-808: Access to a protected member _children of a client class

(W0212)

🪛 Ruff (0.11.9)
camel/societies/workforce/workforce.py

636-639: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (2)
docs/mintlify/reference/camel.societies.workforce.workforce.mdx (1)

261-289: Documentation looks good!

The documentation for the to_mcp method is well-structured and follows the existing documentation format. All parameters are properly documented with their types, defaults, and descriptions.

examples/workforce/simple_workforce_mcp.py (1)

1-71: Well-structured example demonstrating the new MCP functionality!

The example provides clear instructions for testing and demonstrates proper usage of the to_mcp method. Good use of exception handling for graceful shutdown.

🧰 Tools
🪛 Pylint (3.3.7)

[error] 30-30: Unable to import 'camel.agents'

(E0401)


[error] 31-31: Unable to import 'camel.messages'

(E0401)


[error] 32-32: Unable to import 'camel.societies.workforce'

(E0401)

Comment on lines +698 to +699
except Exception as e:
return {"status": "error", "message": str(e)}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add logging to exception handlers for better debugging.

Similar to the earlier suggestion, add logging to these exception handlers to aid in debugging.

For the reset function (line 698):

-            except Exception as e:
-                return {"status": "error", "message": str(e)}
+            except Exception as e:
+                logger.error(f"Error resetting workforce: {e}", exc_info=True)
+                return {"status": "error", "message": str(e)}

For add_single_agent_worker (line 774):

-            except Exception as e:
-                return {"status": "error", "message": str(e)}
+            except Exception as e:
+                logger.error(f"Error adding single agent worker: {e}", exc_info=True)
+                return {"status": "error", "message": str(e)}

For add_role_playing_worker (line 810):

-            except Exception as e:
-                return {"status": "error", "message": str(e)}
+            except Exception as e:
+                logger.error(f"Error adding role playing worker: {e}", exc_info=True)
+                return {"status": "error", "message": str(e)}

Also applies to: 774-775, 810-811

🧰 Tools
🪛 Pylint (3.3.7)

[warning] 698-698: Catching too general exception Exception

(W0718)

🤖 Prompt for AI Agents
In camel/societies/workforce/workforce.py at lines 698-699, 774-775, and
810-811, the exception handlers return error messages without logging the
exceptions. Modify these handlers to log the caught exceptions using the
appropriate logger before returning the error response. This will improve
debugging by recording the error details in the logs.

Comment on lines 633 to 639
try:
from mcp.server.fastmcp import FastMCP
except ImportError:
raise ImportError(
"The 'mcp' package is required to use the to_mcp method. "
"Install it with 'pip install mcp'."
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use explicit exception chaining in the import error.

When re-raising exceptions, use from err to preserve the exception chain for better debugging.

-        try:
-            from mcp.server.fastmcp import FastMCP
-        except ImportError:
-            raise ImportError(
-                "The 'mcp' package is required to use the to_mcp method. "
-                "Install it with 'pip install mcp'."
-            )
+        try:
+            from mcp.server.fastmcp import FastMCP
+        except ImportError as err:
+            raise ImportError(
+                "The 'mcp' package is required to use the to_mcp method. "
+                "Install it with 'pip install mcp'."
+            ) from err
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
from mcp.server.fastmcp import FastMCP
except ImportError:
raise ImportError(
"The 'mcp' package is required to use the to_mcp method. "
"Install it with 'pip install mcp'."
)
try:
from mcp.server.fastmcp import FastMCP
except ImportError as err:
raise ImportError(
"The 'mcp' package is required to use the to_mcp method. "
"Install it with 'pip install mcp'."
) from err
🧰 Tools
🪛 Ruff (0.11.9)

636-639: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🪛 Pylint (3.3.7)

[convention] 634-634: Import outside toplevel (mcp.server.fastmcp.FastMCP)

(C0415)


[warning] 636-639: Consider explicitly re-raising using 'except ImportError as exc' and 'raise ImportError("The 'mcp' package is required to use the to_mcp method. Install it with 'pip install mcp'.") from exc'

(W0707)

🤖 Prompt for AI Agents
In camel/societies/workforce/workforce.py around lines 633 to 639, the
ImportError is re-raised without explicit exception chaining. Modify the except
block to capture the original ImportError as a variable (e.g., err) and re-raise
the new ImportError using 'from err' to preserve the exception chain for better
debugging.

Comment on lines +682 to +687
except Exception as e:
return {
"status": "error",
"message": str(e),
"task_id": task.id,
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider more specific exception handling or logging.

Catching generic Exception can hide unexpected errors. Consider catching specific exceptions or at least logging the full exception details for debugging.

-            except Exception as e:
-                return {
-                    "status": "error",
-                    "message": str(e),
-                    "task_id": task.id,
-                }
+            except Exception as e:
+                logger.error(f"Error processing task {task.id}: {e}", exc_info=True)
+                return {
+                    "status": "error",
+                    "message": str(e),
+                    "task_id": task.id,
+                }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
except Exception as e:
return {
"status": "error",
"message": str(e),
"task_id": task.id,
}
except Exception as e:
logger.error(f"Error processing task {task.id}: {e}", exc_info=True)
return {
"status": "error",
"message": str(e),
"task_id": task.id,
}
🧰 Tools
🪛 Pylint (3.3.7)

[warning] 682-682: Catching too general exception Exception

(W0718)

🤖 Prompt for AI Agents
In camel/societies/workforce/workforce.py around lines 682 to 687, the code
catches a generic Exception which can obscure unexpected errors. Refactor the
exception handling to catch more specific exceptions relevant to the code block
or add logging of the full exception details including stack trace before
returning the error response. This will improve error visibility and aid
debugging.

Copy link
Member
@Wendong-Fan Wendong-Fan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @MuggleJinx ! Overall LGTM, left some minor comments

role_name="Assistant",
agent_kwargs=None,
):
r"""Add a single agent worker to the workforce."""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docstring missing for arguments, same for other functions

description,
assistant_role_name,
user_role_name,
chat_turn_limit=3,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe better by default no limit

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the role_playing_worker's default init is 3..

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @MuggleJinx , 3 is too limited, I adjusted this value to 20

@Wendong-Fan Wendong-Fan added the Waiting for Update PR has been reviewed, need to be updated based on review comment label Jun 4, 2025
@MuggleJinx MuggleJinx requested a review from Wendong-Fan June 8, 2025 02:36
@MuggleJinx MuggleJinx added Review Required PR need to be reviewed and removed Waiting for Update PR has been reviewed, need to be updated based on review comment labels Jun 8, 2025
@Wendong-Fan Wendong-Fan merged commit df8e870 into master Jun 8, 2025
9 of 10 checks passed
@Wendong-Fan Wendong-Fan deleted the workforce-to-mcp branch June 8, 2025 15:35
@Wendong-Fan Wendong-Fan removed the Review Required PR need to be reviewed label Jun 8, 2025
@majauhar
Copy link
Contributor

Hi @MuggleJinx , great work! Thank you. Just a quick question, do you have any local scripts for the client and server that you used to test this feature locally? I am tring to make it work on my machine but kinda stuck. TIA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants
0