Files

483 lines
16 KiB
Python
Raw Permalink Normal View History

"""
MCP 协议接入(框架预留)
========================
【功能说明】
MCP(Model Context Protocol)标准工具协议接入框架。
对应功能 41:Agent 生态标准化对接。
【技术选型理由】
1. MCP 是 Agent 工具接入的标准协议(Anthropic 主导);
2. 框架化设计:支持注册/发现/调用 MCP Server 工具;
3. 预留 httpx 传输层,可对接任意 MCP Server。
【实现思路】
- McpToolRegistry:注册/查询/调用 MCP 工具;
- 后续可接入 MCP Server(GitHub、数据库、浏览器等)。
"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
logger = logging.getLogger("agent.mcp")
class McpTool:
"""MCP 工具定义"""
def __init__(self, name: str, description: str, input_schema: dict, server_url: str = ""):
self.name = name
self.description = description
self.input_schema = input_schema
self.server_url = server_url
class McpToolRegistry:
"""MCP 工具注册表"""
def __init__(self) -> None:
self._tools: dict[str, McpTool] = {}
def register(self, tool: McpTool) -> None:
self._tools[tool.name] = tool
logger.info("MCP 工具已注册:%s", tool.name)
def list_tools(self) -> list[dict]:
return [
{
"name": t.name,
"description": t.description,
"input_schema": t.input_schema,
"server_url": t.server_url,
}
for t in self._tools.values()
]
def get_tool(self, name: str) -> McpTool | None:
return self._tools.get(name)
def call_tool(self, name: str, arguments: dict[str, Any]) -> dict:
"""调用 MCP 工具(优先本地实现,其次 httpx 传输)。"""
tool = self._tools.get(name)
if tool is None:
return {"success": False, "message": f"工具不存在:{name}"}
# 优先使用本地实现
local_impl = _TOOL_IMPLEMENTATIONS.get(name)
if local_impl:
try:
return local_impl(arguments)
except Exception as exc: # noqa: BLE001
return {"success": False, "message": f"本地工具执行失败:{exc}"}
# 无本地实现:走远程 MCP Server
if not tool.server_url:
return {
"success": False,
"message": f"工具 {name} 需要外部凭证配置(GITHUB_TOKEN/SLACK_TOKEN 等),当前未配置",
}
try:
import httpx
resp = httpx.post(
tool.server_url,
json={"tool": name, "arguments": arguments},
timeout=30.0,
)
return {"success": resp.status_code == 200, "data": resp.json() if resp.status_code == 200 else resp.text}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": f"调用失败:{exc}"}
# 全局注册表
registry = McpToolRegistry()
# ========== 本地工具实现(无需外部凭证)==========
def _tool_filesystem(arguments: dict) -> dict:
"""MCP Filesystem 工具:文件读写、搜索、浏览。"""
action = arguments.get("action", "read")
path = arguments.get("path", "")
try:
p = Path(path)
if action == "read":
content = p.read_text(encoding="utf-8", errors="replace")[:50000]
return {"success": True, "content": content}
elif action == "write":
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(arguments.get("content", ""), encoding="utf-8")
return {"success": True, "message": f"已写入 {path}"}
elif action == "list":
items = [
{"name": x.name, "is_dir": x.is_dir(), "size": x.stat().st_size if x.is_file() else 0}
for x in p.iterdir()
]
return {"success": True, "items": items}
elif action == "search":
pattern = arguments.get("pattern", "*")
results = [
str(x) for x in p.rglob(pattern) if x.is_file()
][:50]
return {"success": True, "results": results}
else:
return {"success": False, "message": f"不支持的操作:{action}"}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_web_search(arguments: dict) -> dict:
"""MCP WebSearch 工具:网页搜索(DuckDuckGo)。"""
query = arguments.get("query", "")
if not query:
return {"success": False, "message": "query 必填"}
try:
import httpx
resp = httpx.get(
f"https://html.duckduckgo.com/html/?q={query}",
headers={"User-Agent": "Mozilla/5.0"},
timeout=10.0,
)
return {"success": True, "results": resp.text[:5000], "source": "duckduckgo"}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_web_fetch(arguments: dict) -> dict:
"""MCP WebFetch 工具:抓取网页内容。"""
url = arguments.get("url", "")
if not url:
return {"success": False, "message": "url 必填"}
try:
import httpx
resp = httpx.get(url, timeout=15.0, follow_redirects=True)
return {
"success": True,
"status_code": resp.status_code,
"content": resp.text[:20000],
"content_type": resp.headers.get("content-type", ""),
}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_memory(arguments: dict) -> dict:
"""MCP Memory 工具:长期记忆存取。"""
action = arguments.get("action", "recall")
try:
from app.services.memory_service import get_memory_store
store = get_memory_store()
if action == "remember":
mem_id = store.remember(
content=arguments.get("content", ""),
project_id=arguments.get("project_id", ""),
category=arguments.get("category", "mcp"),
)
return {"success": True, "id": mem_id}
elif action == "recall":
items = store.recall(
query=arguments.get("query", ""),
project_id=arguments.get("project_id", ""),
top_k=int(arguments.get("top_k", 5)),
)
return {"success": True, "memories": items}
else:
return {"success": False, "message": f"不支持:{action}"}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_docker(arguments: dict) -> dict:
"""MCP Docker 工具:容器管理。"""
action = arguments.get("action", "ps")
try:
import subprocess
cmd_map = {
"ps": ["docker", "ps", "-a", "--format", "table {{.Names}}\t{{.Status}}\t{{.Image}}"],
"images": ["docker", "images", "--format", "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"],
"logs": ["docker", "logs", "--tail", "50", arguments.get("container", "")],
"stats": ["docker", "stats", "--no-stream"],
}
cmd = cmd_map.get(action)
if not cmd:
return {"success": False, "message": f"不支持:{action}"}
result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15)
return {"success": result.returncode == 0, "output": result.stdout[:5000], "error": result.stderr[:500]}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_health(arguments: dict) -> dict:
"""MCP 健康检查工具:系统全链路探活。"""
try:
from app.services.health_service import check_all
return {"success": True, "health": check_all()}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_zentao(arguments: dict) -> dict:
"""禅道项目管理工具。"""
try:
from app.services.zentao_service import get_zentao_service
service = get_zentao_service()
action = arguments.get("action", "search")
if action == "create_bug":
result = service.create_bug(
title=arguments.get("title", ""),
description=arguments.get("description", ""),
project_id=arguments.get("project_id", ""),
)
return result
elif action == "create_task":
result = service.create_task(
title=arguments.get("title", ""),
description=arguments.get("description", ""),
project_id=arguments.get("project_id", ""),
)
return result
elif action == "search":
result = service.search(keyword=arguments.get("title", ""))
return result
elif action == "update_status":
result = service.update_status(
issue_id=arguments.get("issue_id", ""),
status=arguments.get("status", "done"),
)
return result
else:
return {"success": False, "message": f"不支持:{action}"}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
def _tool_git(arguments: dict) -> dict:
"""Git 深度集成工具。"""
try:
from app.tools.git_tools import get_diff, ensure_task_branch, commit_changes
action = arguments.get("action", "status")
repo_path = arguments.get("repo_path", "")
if action == "diff":
result = get_diff(repo_path)
return {"success": True, **result}
elif action == "status":
import subprocess
result = subprocess.run(
["git", "status", "--short"],
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
return {"success": True, "output": result.stdout}
elif action == "commit":
result = commit_changes(
repo_path,
message=arguments.get("message", "自动提交"),
task_id=arguments.get("task_id", ""),
)
return {"success": True, **result}
elif action == "log":
import subprocess
result = subprocess.run(
["git", "log", "--oneline", "-20"],
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
return {"success": True, "output": result.stdout}
elif action == "branch":
import subprocess
result = subprocess.run(
["git", "branch", "-a"],
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
return {"success": True, "output": result.stdout}
else:
return {"success": False, "message": f"不支持:{action}"}
except Exception as exc: # noqa: BLE001
return {"success": False, "message": str(exc)}
# ========== 工具实现映射 ==========
_TOOL_IMPLEMENTATIONS = {
"filesystem": _tool_filesystem,
"web_search": _tool_web_search,
"web_fetch": _tool_web_fetch,
"memory": _tool_memory,
"docker": _tool_docker,
"health_check": _tool_health,
"zentao": _tool_zentao,
"git": _tool_git,
}
# ========== 注册全部工具 ==========
registry.register(McpTool(
name="filesystem",
description="文件系统操作(读/写/列目录/搜索)",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["read", "write", "list", "search"]},
"path": {"type": "string"},
"content": {"type": "string"},
"pattern": {"type": "string"},
},
},
))
registry.register(McpTool(
name="web_search",
description="网页搜索(DuckDuckGo)",
input_schema={"type": "object", "properties": {"query": {"type": "string"}}},
))
registry.register(McpTool(
name="web_fetch",
description="抓取网页内容",
input_schema={"type": "object", "properties": {"url": {"type": "string"}}},
))
registry.register(McpTool(
name="memory",
description="长期记忆(存取项目约定、决策、规范)",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["remember", "recall"]},
"content": {"type": "string"},
"query": {"type": "string"},
"project_id": {"type": "string"},
},
},
))
registry.register(McpTool(
name="docker",
description="Docker 容器管理(ps/images/logs/stats)",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["ps", "images", "logs", "stats"]},
"container": {"type": "string"},
},
},
))
registry.register(McpTool(
name="health_check",
description="系统健康检查(全链路探活)",
input_schema={"type": "object", "properties": {}},
))
# ========== 需要凭证的工具(框架就绪)==========
registry.register(McpTool(
name="github",
description="GitHub 操作(PR/Issue/仓库)— 需要 GITHUB_TOKEN",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["create_pr", "list_issues", "create_issue", "get_repo"]},
"repo": {"type": "string"},
"title": {"type": "string"},
"body": {"type": "string"},
},
},
server_url="", # 需配置
))
registry.register(McpTool(
name="zentao",
description="禅道项目管理(创建/查询/更新 Bug 和任务)",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["create_bug", "create_task", "search", "update_status"]},
"title": {"type": "string"},
"description": {"type": "string"},
"project_id": {"type": "string"},
"issue_id": {"type": "string"},
},
},
))
registry.register(McpTool(
name="git",
description="Git 深度集成(commit/diff/branch/log/blame)",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["status", "diff", "commit", "log", "branch", "blame"]},
"repo_path": {"type": "string"},
"message": {"type": "string"},
"file_path": {"type": "string"},
},
},
))
registry.register(McpTool(
name="jira",
description="Jira 任务管理(创建/查询/更新)— 需要 JIRA_TOKEN",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["create_issue", "search", "update"]},
"project": {"type": "string"},
"summary": {"type": "string"},
},
},
))
registry.register(McpTool(
name="redis",
description="Redis 缓存操作(GET/SET/DEL)— 需要 Redis 连接",
input_schema={
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["get", "set", "del", "keys"]},
"key": {"type": "string"},
"value": {"type": "string"},
},
},
))
registry.register(McpTool(
name="database",
description="通用数据库查询(SQL)— 需要数据库连接",
input_schema={
"type": "object",
"properties": {
"connection_id": {"type": "string"},
"sql": {"type": "string"},
},
},
))
registry.register(McpTool(
name="email",
description="邮件发送(SMTP)— 需要邮箱凭证",
input_schema={
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"},
},
},
))