MCP ToolsΒΆ
Model Context Protocol (MCP) tool registration, execution, and lifecycle management.
Define tools with MCPTool, manage them with MCPToolManager, and execute them by name or ID β all thread-safe.
v2.0 Improvements
MCPTool uses __slots__ for memory efficiency. MCPToolManager uses threading.Lock for thread safety and provides remove_tool() cleanup.
OverviewΒΆ
| Class | Purpose |
|---|---|
MCPTool | Data class representing a single tool (id, name, capability, execute function) |
MCPToolManager | Registry that stores, lists, and executes tools |
Quick StartΒΆ
Defining ToolsΒΆ
Each MCPTool has four attributes (stored via __slots__):
| Attribute | Type | Description |
|---|---|---|
id | str | Unique identifier |
name | str | Human-readable name |
capability | str | Description of what the tool does |
execute_fn | Callable | The function to invoke |
Managing ToolsΒΆ
RegisterΒΆ
ListΒΆ
| Python | |
|---|---|
Execute by IDΒΆ
| Python | |
|---|---|
Execute by NameΒΆ
| Python | |
|---|---|
RemoveΒΆ
| Python | |
|---|---|
Thread SafetyΒΆ
All MCPToolManager operations are protected by threading.Lock:
API ReferenceΒΆ
MCPToolΒΆ
| Attribute | Type | Description |
|---|---|---|
id | str | Unique tool identifier |
name | str | Human-readable name |
capability | str | Tool description |
execute_fn | Callable | Function to invoke |
Uses __slots__ β no __dict__ overhead.
MCPToolManagerΒΆ
| Method | Returns | Description |
|---|---|---|
register_tool(tool) | None | Register an MCPTool instance |
execute_tool(tool_id, **kwargs) | Any | Execute a tool by its ID |
execute_tool_by_name(name, **kwargs) | Any | Execute a tool by its name |
list_tools() | list[MCPTool] | List all registered tools |
remove_tool(tool_id) | None | Remove a tool by ID |
Best PracticesΒΆ
Do
- Use descriptive
capabilitystrings β LLMs use them for tool selection. - Use unique, stable
idvalues (e.g. snake_case identifiers). - Handle exceptions inside
execute_fnor wrap calls in try/except. - Clean up with
remove_tool()when tools are no longer needed.
Don't
- Register multiple tools with the same
id(last one wins). - Use long-blocking operations in
execute_fnwithout timeouts. - Forget that
execute_fnruns synchronously on the calling thread.
Related DocumentationΒΆ
- Tools β general tool framework
- Hub β component registry
- Agents β agent lifecycle
- Integration β third-party integrations