"""
MCP 工具实现模块
提供各种工具的具体实现
"""
import json
import os
import math
from typing import Dict, Any, List
from datetime import datetime
class MCPTools:
"""MCP 工具集合类"""
@staticmethod
def calculator(expression: str) -> Dict[str, Any]:
"""
计算器工具 - 安全地计算数学表达式
Args:
expression: 数学表达式字符串
Returns:
包含计算结果的字典
"""
try:
# 只允许安全的数学操作
allowed_names = {
k: v for k, v in math.__dict__.items()
if not k.startswith("__")
}
allowed_names.update({
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"pow": pow
})
# 安全计算表达式
result = eval(expression, {"__builtins__": {}}, allowed_names)
return {
"success": True,
"result": result,
"expression": expression,
"type": type(result).__name__
}
except Exception as e:
return {
"success": False,
"error": str(e),
"expression": expression
}
@staticmethod
def text_analyzer(text: str) -> Dict[str, Any]:
"""
文本分析工具 - 分析文本的基本统计信息
Args:
text: 要分析的文本
Returns:
包含文本分析结果的字典
"""
try:
words = text.split()
sentences = text.split('.')
# 计算基本统计信息
char_count = len(text)
word_count = len(words)
sentence_count = len([s for s in sentences if s.strip()])
# 计算平均词长
avg_word_length = sum(len(word) for word in words) / len(words) if words else 0
# 查找最常见的词
word_freq = {}
for word in words:
word_lower = word.lower().strip('.,!?;:"')
word_freq[word_lower] = word_freq.get(word_lower, 0) + 1
most_common = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:5]
return {
"success": True,
"statistics": {
"character_count": char_count,
"word_count": word_count,
"sentence_count": sentence_count,
"average_word_length": round(avg_word_length, 2),
"most_common_words": most_common
},
"text_preview": text[:100] + "..." if len(text) > 100 else text
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
@staticmethod
def file_reader(file_path: str, max_size: int = 1024) -> Dict[str, Any]:
"""
文件读取工具 - 安全地读取文件内容
Args:
file_path: 文件路径
max_size: 最大读取字节数
Returns:
包含文件内容的字典
"""
try:
# 安全检查:只允许读取当前目录及子目录的文件
abs_path = os.path.abspath(file_path)
current_dir = os.path.abspath(".")
if not abs_path.startswith(current_dir):
return {
"success": False,
"error": "Access denied: file outside allowed directory"
}
if not os.path.exists(abs_path):
return {
"success": False,
"error": f"File not found: {file_path}"
}
if os.path.getsize(abs_path) > max_size:
return {
"success": False,
"error": f"File too large (max {max_size} bytes)"
}
with open(abs_path, 'r', encoding='utf-8') as f:
content = f.read()
return {
"success": True,
"content": content,
"file_path": file_path,
"file_size": len(content),
"lines": len(content.split('\n'))
}
except UnicodeDecodeError:
try:
# 尝试以二进制模式读取
abs_path = os.path.abspath(file_path)
with open(abs_path, 'rb') as f:
content = f.read()
return {
"success": True,
"content": f"Binary file ({len(content)} bytes)",
"file_path": file_path,
"file_size": len(content),
"is_binary": True
}
except Exception as e:
return {
"success": False,
"error": f"Cannot read file: {str(e)}"
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def get_tool_schema() -> List[Dict[str, Any]]:
"""
获取所有工具的模式定义
Returns:
工具模式列表
"""
return [
{
"name": "calculator",
"description": "计算数学表达式的值",
"inputSchema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "要计算的数学表达式,支持基本运算和数学函数"
}
},
"required": ["expression"]
}
},
{
"name": "text_analyzer",
"description": "分析文本内容,提供统计信息",
"inputSchema": {
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "要分析的文本内容"
}
},
"required": ["text"]
}
},
{
"name": "file_reader",
"description": "读取文件内容(限制在当前目录内)",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "要读取的文件路径"
},
"max_size": {
"type": "integer",
"description": "最大读取字节数",
"default": 1024
}
},
"required": ["file_path"]
}
}
]