# MCP Tools

Model Context Protocol (MCP) tools enable standardized integration of external tools and services with AI assistants, providing a consistent interface for tool discovery, execution, and management.

## Overview

MCP (Model Context Protocol) is an open standard that allows AI assistants to discover and use tools from various providers through a standardized interface. This enables seamless integration of external capabilities without vendor lock-in.

## How MCP Works

### 1. Tool Discovery

Assistants automatically discover available MCP tools:


```python
# Tools are discovered automatically based on assistant configuration
assistant = freddy.assistants.create(
 name="MCP-Enabled Assistant",
 instructions="You have access to MCP tools for enhanced capabilities.",
 model="gpt-4o",
 tools=["mcp"] # Enable MCP tool discovery
)
```

### 2. Tool Registry

MCP tools are registered in a standardized format:


```json
{
 "name": "tool_name",
 "description": "What this tool does",
 "input_schema": {
 "type": "object",
 "properties": {
 "param1": {"type": "string", "description": "Parameter description"}
 }
 },
 "implementation": "tool_implementation_function"
}
```

### 3. Tool Execution

Tools are executed through the MCP interface:


```python
# Assistant automatically calls MCP tools when needed
result = await mcp_client.call_tool(
 tool_name="example_tool",
 parameters={"param1": "value"}
)
```

## Available MCP Tool Categories

### **Search & Discovery**

- **Web Search MCP** - Search the internet using various engines
- **Document Search MCP** - Search through document collections
- **Code Search MCP** - Search code repositories and documentation


### **Development Tools**

- **Code Execution MCP** - Run code in various languages
- **Git MCP** - Interact with Git repositories
- **Docker MCP** - Manage containerized environments


### **Data & Analytics**

- **Database MCP** - Query databases and data warehouses
- **API MCP** - Interact with REST and GraphQL APIs
- **Spreadsheet MCP** - Work with Excel and Google Sheets


### **AI & Machine Learning**

- **Model MCP** - Access various AI models and services
- **Vector DB MCP** - Search vector databases
- **ML Pipeline MCP** - Run machine learning workflows


## Implementing MCP Tools

### Creating a Custom MCP Tool


```python
from mcp import Tool, MCPServer

# Define a custom tool
class CustomTool(Tool):
 def __init__(self):
 super().__init__(
 name="custom_calculator",
 description="Perform advanced mathematical calculations",
 input_schema={
 "type": "object",
 "properties": {
 "operation": {
 "type": "string",
 "enum": ["add", "multiply", "power"],
 "description": "Mathematical operation to perform"
 },
 "numbers": {
 "type": "array",
 "items": {"type": "number"},
 "description": "Numbers for the calculation"
 }
 },
 "required": ["operation", "numbers"]
 }
 )

 async def execute(self, operation: str, numbers: list) -> dict:
 """Execute the mathematical operation."""
 if operation == "add":
 result = sum(numbers)
 elif operation == "multiply":
 result = 1
 for num in numbers:
 result *= num
 elif operation == "power":
 result = numbers[0] ** numbers[1]
 else:
 raise ValueError(f"Unknown operation: {operation}")

 return {
 "operation": operation,
 "inputs": numbers,
 "result": result
 }

# Register the tool
server = MCPServer(tools=[CustomTool()])
```

### Publishing MCP Tools


```python
# Publish tool to MCP registry
freddy.mcp_tools.publish(
 tool=CustomTool(),
 metadata={
 "author": "Your Name",
 "version": "1.0.0",
 "tags": ["mathematics", "calculator"],
 "documentation": "https://example.com/docs/custom-calculator"
 }
)
```

## Using MCP Tools in Assistants

### Enable MCP in Assistant


```python
# Create assistant with MCP support
assistant = freddy.assistants.create(
 name="MCP Assistant",
 instructions="""You have access to MCP tools that extend your capabilities:

Available tools:
- Use web_search for current information
- Use code_executor for running code
- Use database_query for data analysis
- Use custom_calculator for complex math

Always choose the most appropriate tool for each task.""",
 model="gpt-4o",
 tools=[{"type": "mcp"}]
)
```

### Tool Selection and Usage


```python
# Assistant automatically selects and uses MCP tools
message = freddy.threads.messages.create(
 thread_id=thread.id,
 role="user",
 content="Calculate 2^10 + 15 * 3 using the custom calculator"
)

# Assistant will:
# 1. Recognize the need for mathematical calculation
# 2. Select the custom_calculator MCP tool
# 3. Call the tool with appropriate parameters
# 4. Present the result in natural language
```

## MCP Tool Management

### Discovering Available Tools


```python
# List available MCP tools
tools = freddy.mcp_tools.list()

for tool in tools:
 print(f"Name: {tool.name}")
 print(f"Description: {tool.description}")
 print(f"Category: {tool.category}")
 print(f"Version: {tool.version}")
```

### Tool Configuration


```python
# Configure tool settings
freddy.mcp_tools.configure(
 tool_name="web_search",
 settings={
 "default_engine": "google",
 "safe_search": True,
 "max_results": 10,
 "timeout": 30
 }
)
```

### Tool Monitoring


```python
# Monitor tool usage and performance
usage = freddy.mcp_tools.get_usage(
 tool_name="custom_calculator",
 start_date="2024-01-01",
 end_date="2024-01-31"
)

print(f"Total executions: {usage.total_executions}")
print(f"Average execution time: {usage.avg_execution_time}ms")
print(f"Success rate: {usage.success_rate}%")
```

## Best Practices

### Tool Design

- **Clear Descriptions**: Write clear, concise tool descriptions
- **Proper Schemas**: Define input/output schemas accurately
- **Error Handling**: Implement robust error handling
- **Documentation**: Provide comprehensive usage examples


### Security Considerations

- **Input Validation**: Validate all inputs thoroughly
- **Access Control**: Implement appropriate permission checks
- **Data Protection**: Handle sensitive data securely
- **Audit Logging**: Log tool usage for security monitoring


### Performance Optimization

- **Efficient Execution**: Optimize tool execution speed
- **Resource Management**: Manage memory and CPU usage
- **Caching**: Cache results when appropriate
- **Async Operations**: Use async operations for better performance


## Advanced MCP Features

### Tool Chaining

Create workflows that use multiple MCP tools in sequence:


```python
# Example: Research workflow using multiple tools
async def research_workflow(topic: str):
 """Perform comprehensive research using multiple MCP tools."""

 # Step 1: Search the web for current information
 web_results = await mcp_client.call_tool("web_search", {"query": topic})

 # Step 2: Search documents for related information
 doc_results = await mcp_client.call_tool("document_search", {"query": topic})

 # Step 3: Analyze data with code execution
 analysis = await mcp_client.call_tool("code_executor", {
 "code": "analyze_research_data(web_results, doc_results)"
 })

 return {
 "topic": topic,
 "findings": analysis["result"],
 "sources": {"web": web_results, "documents": doc_results}
 }
```

### Dynamic Tool Loading

Load tools dynamically based on context:


```python
# Load specialized tools for specific tasks
def load_specialized_tools(task_type: str):
 """Load appropriate tools based on task requirements."""

 if task_type == "data_analysis":
 return ["pandas_analyzer", "statistics_tool", "visualization_tool"]
 elif task_type == "web_research":
 return ["web_search", "content_summarizer", "fact_checker"]
 elif task_type == "code_development":
 return ["code_executor", "linter", "test_runner"]

 return ["general_search"] # Default tools
```

## Troubleshooting

### Common Issues

**Tool Not Found**

- Verify tool is properly registered in MCP registry
- Check tool name spelling and casing
- Ensure tool is enabled for the assistant


**Tool Execution Failures**

- Check tool input parameters match schema
- Verify tool dependencies are available
- Review tool logs for specific error details


**Performance Issues**

- Monitor tool execution times
- Check for resource contention
- Optimize tool implementations


### Debugging Tools


```python
# Enable debug mode for detailed logging
freddy.mcp_tools.set_debug_mode(True)

# Test individual tools
test_result = freddy.mcp_tools.test("custom_calculator", {
 "operation": "add",
 "numbers": [1, 2, 3]
})

print(f"Test result: {test_result}")
```

## Next Steps

- [Create Assistant API](/docs/api-reference/assistants/create) - Create assistants with MCP support
- [Assistant Object](/docs/api-reference/objects/assistant-object) - Assistant configuration details
- [Function Calling Guide](/docs/documentation/function-calling) - Using functions with assistants


## Resources

- [MCP Specification](https://modelcontextprotocol.io/) - Official MCP documentation
- [MCP Tools Registry](https://registry.modelcontextprotocol.io/) - Discover available tools
- [MCP SDK Documentation](https://sdk.modelcontextprotocol.io/) - Development tools and libraries


For technical support, contact [support@aitronos.com](mailto:support@aitronos.com).