Files
ops-mcp/internal/tool/system.go
T
yangzhaohan fb2c3a6cae Go MCP Server 项目初始化:工具注册架构 + 编译运行通过
- Tool 接口 + Registry 注册中心,工具模块化插拔
- system 工具:health / info
- database 工具:db_query / db_tables / db_table_info / db_explain(四层 SQL 安全)
- docker 工具:docker_ps / docker_logs / docker_inspect(白名单 + 大小限制)
- middleware:auth(JWT+APIKey)/ ratelimit(令牌桶)/ audit(slog 结构化)
- stdio / SSE 双传输模式,Viper 多环境配置
- Dockerfile 多阶段构建(golang:alpine → scratch),~15MB 镜像
- docker-compose.yml 一键部署 + 安全加固(read_only / no-new-privileges / cap_drop)
- go build ./... / go vet ./... / go test ./... 全部通过

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-07-06 10:26:52 +08:00

83 lines
2.4 KiB
Go

package tool
import (
"context"
"encoding/json"
"fmt"
"runtime"
"time"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
var StartTime = time.Now()
// SystemTool 提供 health 和 info 两个基础工具。
type SystemTool struct {
version string
registry HealthChecker
}
// HealthChecker 用于 system 工具检查其他工具的连通性。
type HealthChecker interface {
HealthCheckAll(ctx context.Context) map[string]error
}
func NewSystemTool(version string, reg HealthChecker) *SystemTool {
return &SystemTool{version: version, registry: reg}
}
func (s *SystemTool) Name() string { return "system" }
func (s *SystemTool) Description() string { return "系统健康检查和信息查询" }
func (s *SystemTool) Initialize(_ context.Context) error { return nil }
func (s *SystemTool) Shutdown(_ context.Context) error { return nil }
func (s *SystemTool) HealthCheck(_ context.Context) error { return nil }
func (s *SystemTool) Register(mcpServer *server.MCPServer) error {
mcpServer.AddTool(mcp.NewTool("health",
mcp.WithDescription("服务健康检查:运行时间、内存使用、连接状态"),
), s.handleHealth)
mcpServer.AddTool(mcp.NewTool("info",
mcp.WithDescription("服务信息:版本号、已配置的数据库、已加载的工具"),
), s.handleInfo)
return nil
}
func (s *SystemTool) handleHealth(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
result := map[string]any{
"status": "ok",
"uptime": time.Since(StartTime).String(),
"goroutines": runtime.NumGoroutine(),
"heap_mb": float64(m.HeapAlloc) / 1024 / 1024,
"gc_cycles": m.NumGC,
}
if s.registry != nil {
result["connections"] = s.registry.HealthCheckAll(ctx)
}
data, _ := json.MarshalIndent(result, "", " ")
return mcp.NewToolResultText(string(data)), nil
}
func (s *SystemTool) handleInfo(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
result := map[string]any{
"version": s.version,
"go_version": runtime.Version(),
"os": runtime.GOOS,
"arch": runtime.GOARCH,
"cpus": runtime.NumCPU(),
"start_time": StartTime.Format(time.RFC3339),
}
data, _ := json.MarshalIndent(result, "", " ")
return mcp.NewToolResultText(fmt.Sprintf("```json\n%s\n```", string(data))), nil
}