You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

85 lines
2.2 KiB

package mcp
import (
"context"
"yunyan/lego/sys/log"
"net/http"
"runtime/debug"
"time"
"github.com/mark3labs/mcp-go/mcp"
)
const (
ToolGroup_GLOBAL = "GLOBAL" // 全局工具组
ToolGroup_OVERSEAS = "OVERSEAS" // 海外工具组
ToolGroup_CHINA = "CHINA" // 国内工具组
)
type (
ITool interface {
Tool() (tool mcp.Tool)
Handl(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)
}
)
func stringInArray(target string, array []string) bool {
for _, item := range array {
if item == target {
return true
}
}
return false
}
func isValidDate(dateStr string) bool {
_, err := time.Parse("2006-01-02", dateStr)
return err == nil
}
// withRecover 添加panic恢复中间件,防止单个请求的panic导致整个服务崩溃
func withRecover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
// 记录panic信息
log.Errorf("Panic recovered in %s %s: %v", r.Method, r.URL.Path, err)
// 打印堆栈信息用于调试
if stack := debug.Stack(); len(stack) > 0 {
log.Errorf("Stack trace: %s", string(stack))
}
// 返回500错误给客户端
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error":"Internal server error","message":"服务器内部错误,请稍后重试"}`))
}
}()
next.ServeHTTP(w, r)
})
}
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Session-Id, Mcp-Session-Id")
w.Header().Set("Access-Control-Expose-Headers", "Mcp-Session-Id")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// 处理预检请求
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}