Application classes (tied to specific external services), Universal MCP also allows you to define and register standalone Python functions as custom tools. This is useful for:
- Utility functions that your AI agent might need.
- Functions that perform computations or data transformations not tied to an external API.
- Integrating local scripts or functionalities.
Defining a Custom Tool Function
A custom tool is simply a Python function. To ensure it integrates well with Universal MCP and is understandable by AI agents, you should:- Use Type Hints: Provide type hints for all arguments and the return value. This helps in generating the correct parameter schema.
- Write a Clear Docstring: The docstring is crucial. Universal MCP parses it to generate the tool’s
description,args_description,returns_description, andtags. Follow a style thatdocstring_parsercan understand (Google style is recommended).
Registering Custom Tools with ToolManager
Once your function is defined, you use the ToolManager to register it. You have two primary methods:
-
ToolManager.add_tool(fn: Callable[..., Any] | Tool, name: str | None = None) -> Tool: This is the most direct way. You pass the function object itself.- If
nameis not provided, the function’s__name__is used. - It’s good practice to provide an explicit, descriptive name, especially if the function name is generic.
- This method internally calls
Tool.from_function(fn, name=name)to create theToolobject.
- If
-
Creating a
Toolinstance explicitly and then registering: This gives you more control if you need to customizeToolcreation, thoughadd_toolis usually sufficient.Theexamples/langraph.pyfile demonstrates adding a simplecalculatefunction as a tool.
Best Practices for Custom Tools
- Clear Naming: Choose a tool name that clearly indicates its purpose.
- Comprehensive Docstrings: The quality of your docstring directly impacts how well an LLM can understand and use your tool. Include:
- A concise summary.
- Detailed descriptions for each argument (
Args:). - A clear description of what the tool returns (
Returns:). - Potential exceptions it might raise (
Raises:). - Relevant
Tags:for categorization and discovery.
- Type Hinting: Accurate type hints enable robust input validation and schema generation.
- Error Handling: Implement proper error handling within your tool function and document potential exceptions in the docstring.
- Idempotency (if applicable): If a tool performs an action that has side effects, consider if it can be made idempotent.