base.pyโข3.31 kB
"""
Base Tool Class
Author: Yobie Benjamin
Version: 0.9
Date: August 1, 2025
This module defines the base class for all tools in the MCP server.
Tools are functions that can be called by Claude to perform specific tasks.
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
@dataclass
class ToolResult:
"""
Standard result format for tool execution.
Attributes:
success: Whether the tool executed successfully
data: The result data
error: Error message if failed
metadata: Additional metadata about the execution
"""
success: bool
data: Any = None
error: Optional[str] = None
metadata: Dict[str, Any] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
result = {
"success": self.success,
"data": self.data
}
if self.error:
result["error"] = self.error
if self.metadata:
result["metadata"] = self.metadata
return result
class BaseTool(ABC):
"""
Abstract base class for all tools.
Each tool must implement:
- name: Unique identifier
- description: Human-readable description
- parameters: Pydantic model for input validation
- execute: Async method to perform the tool's function
"""
@property
@abstractmethod
def name(self) -> str:
"""Return the tool's unique name."""
pass
@property
@abstractmethod
def description(self) -> str:
"""Return a description of what the tool does."""
pass
@property
@abstractmethod
def parameters(self) -> type[BaseModel]:
"""Return the Pydantic model for parameter validation."""
pass
@abstractmethod
async def execute(self, **kwargs) -> ToolResult:
"""
Execute the tool with given parameters.
Args:
**kwargs: Tool-specific parameters
Returns:
ToolResult with execution outcome
"""
pass
def get_schema(self) -> Dict[str, Any]:
"""
Get the tool's schema in MCP format.
Returns:
Dictionary with tool schema
"""
# Get JSON schema from Pydantic model
param_schema = self.parameters.schema() if self.parameters else {}
return {
"name": self.name,
"description": self.description,
"inputSchema": {
"type": "object",
"properties": param_schema.get("properties", {}),
"required": param_schema.get("required", [])
}
}
def validate_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate parameters using the Pydantic model.
Args:
params: Raw parameters to validate
Returns:
Validated parameters
Raises:
ValidationError: If parameters are invalid
"""
if self.parameters:
model = self.parameters(**params)
return model.dict()
return params