diff --git a/internal/infrastructure/ai/mcp_sse_client.go b/internal/infrastructure/ai/mcp_sse_client.go index cdb5274..799ff37 100644 --- a/internal/infrastructure/ai/mcp_sse_client.go +++ b/internal/infrastructure/ai/mcp_sse_client.go @@ -33,12 +33,15 @@ type MCPSSEClient struct { started bool postURL string cancelFn context.CancelFunc - pending map[uint64]chan json.RawMessage + pending map[uint64]chan json.RawMessage // 请求 ID: 响应 channel 的映射, 这是并发请求-响应匹配的核心 nextID atomic.Uint64 streamErr chan error endpointSig chan struct{} } +// NewMCPSSEClient +// 创建一个 MCP SSE 客户端实例. baseURI 为服务端基础地址, endpoint 为 SSE 端点路径, requestTimeoutMillis 为单次 RPC 调用的超时毫秒数. +// 该函数只初始化配置, 不会建立连接, 连接会在首次调用工具或列出工具时按需建立. func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSEClient { timeout := time.Duration(requestTimeoutMillis) * time.Millisecond if timeout <= 0 { @@ -47,11 +50,14 @@ func NewMCPSSEClient(baseURI, endpoint string, requestTimeoutMillis int) *MCPSSE return &MCPSSEClient{ baseURI: strings.TrimRight(baseURI, "/"), endpoint: endpoint, - httpClient: &http.Client{Timeout: 0}, + httpClient: &http.Client{Timeout: 0}, // SSE 不设置超时 timeout: timeout, } } +// ensureStarted +// 确保 SSE 连接已经建立. +// 若尚未启动, 则依次完成: 发起 SSE 长连接、等待服务端下发 endpoint 事件、完成 JSON-RPC 初始化握手; 失败时调用 shutdown 重置状态. func (c *MCPSSEClient) ensureStarted(ctx context.Context) error { c.mu.Lock() if c.started { @@ -61,16 +67,18 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error { c.pending = make(map[uint64]chan json.RawMessage) c.endpointSig = make(chan struct{}) c.streamErr = make(chan error, 1) - streamCtx, cancel := context.WithCancel(context.Background()) + streamCtx, cancel := context.WithCancel(context.Background()) // streamCtx 用来控制后台 SSE 读取 goroutine 的生命周期 c.cancelFn = cancel c.started = true c.mu.Unlock() + // 发起 GET /sse, 建立 SSE 长连接 if err := c.openSSE(streamCtx); err != nil { c.shutdown() return err } + // 等待服务器通过 SSE 推送 endpoint 事件 waitCtx, waitCancel := context.WithTimeout(ctx, c.timeout) defer waitCancel() select { @@ -83,6 +91,7 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error { return fmt.Errorf("mcp sse endpoint event timeout: %w", waitCtx.Err()) } + // 执行 JSON-RPC 初始化握手 if err := c.initialize(ctx); err != nil { c.shutdown() return err @@ -90,6 +99,8 @@ func (c *MCPSSEClient) ensureStarted(ctx context.Context) error { return nil } +// openSSE +// 向服务端发起 GET 请求建立 SSE 长连接, 并在成功后启动后台 readLoop goroutine 持续读取事件流. func (c *MCPSSEClient) openSSE(ctx context.Context) error { target := c.baseURI + c.endpoint req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) @@ -106,13 +117,16 @@ func (c *MCPSSEClient) openSSE(ctx context.Context) error { _ = resp.Body.Close() return fmt.Errorf("mcp sse status %d: %s", resp.StatusCode, truncate(string(raw), 200)) } - go c.readLoop(resp) + go c.readLoop(resp) // 启动 readLoop goroutine 持续读取 SSE 事件 return nil } +// readLoop +// 在后台 goroutine 中持续读取 SSE 事件流, 按 event/data 行解析事件, 并在事件结束时根据事件类型分发处理; +// 读取失败时会通知所有等待中的 RPC 调用. func (c *MCPSSEClient) readLoop(resp *http.Response) { defer resp.Body.Close() - reader := bufio.NewReader(resp.Body) + reader := bufio.NewReader(resp.Body) // 获取带缓冲逐行读的字节流 var event string var dataBuf strings.Builder dispatch := func() { @@ -133,7 +147,7 @@ func (c *MCPSSEClient) readLoop(resp *http.Response) { } for { line, err := reader.ReadString('\n') - if err != nil { + if err != nil { // 读取失败, 通知所有等待中的 RPC 调用, 并退出循环 if err != io.EOF { c.signalStreamErr(fmt.Errorf("mcp sse read: %w", err)) } else { @@ -158,6 +172,8 @@ func (c *MCPSSEClient) readLoop(resp *http.Response) { } } +// handleEndpoint +// 处理 SSE 的 endpoint 事件, 解析并记录服务端下发的 POST 消息地址; 若已记录过地址, 则尝试将数据按普通 message 事件处理. func (c *MCPSSEClient) handleEndpoint(data, eventName string) { if c.postURLAlreadySet() { if eventName == "" { @@ -174,12 +190,17 @@ func (c *MCPSSEClient) handleEndpoint(data, eventName string) { c.mu.Unlock() } +// postURLAlreadySet +// 返回当前是否已经记录 POST 消息地址. func (c *MCPSSEClient) postURLAlreadySet() bool { c.mu.Lock() defer c.mu.Unlock() return c.postURL != "" } +// resolvePostURL +// 将服务端返回的 endpoint 数据解析为完整可用的 POST 地址; +// 若数据为相对路径, 则基于 baseURI 进行解析. func (c *MCPSSEClient) resolvePostURL(raw string) string { parsed, err := url.Parse(raw) if err != nil || !parsed.IsAbs() { @@ -194,6 +215,8 @@ func (c *MCPSSEClient) resolvePostURL(raw string) string { return raw } +// handleMessage +// 处理 SSE 的 message 事件: 解析 JSON-RPC 2.0 响应, 根据响应 ID 找到对应的等待 channel 并投递结果或错误. func (c *MCPSSEClient) handleMessage(data string) { var resp struct { ID json.Number `json:"id"` @@ -231,11 +254,15 @@ func (c *MCPSSEClient) handleMessage(data string) { close(ch) } +// mustJSON 将任意值序列化为 JSON 字节; +// 这里仅用于构造错误包装对象, 因此忽略序列化错误. func mustJSON(v any) json.RawMessage { raw, _ := json.Marshal(v) return raw } +// signalStreamErr +// 在 SSE 流读取失败时向所有等待中的 RPC 调用广播错误, 并清理 pending 映射, 避免 goroutine 泄漏. func (c *MCPSSEClient) signalStreamErr(err error) { c.mu.Lock() defer c.mu.Unlock() @@ -250,6 +277,8 @@ func (c *MCPSSEClient) signalStreamErr(err error) { } } +// shutdown +// 取消后台读取 goroutine 并重置客户端状态, 使客户端可以再次尝试启动. func (c *MCPSSEClient) shutdown() { c.mu.Lock() defer c.mu.Unlock() @@ -261,6 +290,8 @@ func (c *MCPSSEClient) shutdown() { c.pending = nil } +// initialize +// 执行 MCP 协议初始化握手: 发送 initialize 请求, 随后发送 notifications/initialized 通知. func (c *MCPSSEClient) initialize(ctx context.Context) error { _, err := c.callRPC(ctx, "initialize", map[string]any{ "protocolVersion": mcpProtocolVersion, @@ -279,6 +310,8 @@ func (c *MCPSSEClient) initialize(ctx context.Context) error { return nil } +// CallTool +// 调用指定的 MCP 工具: 确保连接已建立后, 将工具名与 JSON 参数通过 tools/call 发送给服务端, 并返回提取后的文本结果. func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (string, error) { if err := c.ensureStarted(ctx); err != nil { return "", err @@ -300,6 +333,8 @@ func (c *MCPSSEClient) CallTool(ctx context.Context, name, arguments string) (st return extractToolText(result), nil } +// ListTools +// 调用 tools/list 获取服务端暴露的工具列表, 并返回所有工具名. func (c *MCPSSEClient) ListTools(ctx context.Context) ([]string, error) { if err := c.ensureStarted(ctx); err != nil { return nil, err @@ -331,6 +366,9 @@ type toolCallResult struct { IsError bool `json:"isError"` } +// extractToolText +// 从 MCP 工具调用的原始响应中提取文本内容; +// 若响应不符合标准结构, 则返回原始 JSON 字符串. func extractToolText(raw json.RawMessage) string { var parsed toolCallResult if err := json.Unmarshal(raw, &parsed); err != nil { @@ -348,6 +386,8 @@ func extractToolText(raw json.RawMessage) string { return strings.Join(parts, "\n") } +// callRPC +// 发送一个 JSON-RPC 2.0 请求, 并通过 SSE 通道异步等待对应 ID 的响应, 支持 context 超时控制. func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) (json.RawMessage, error) { id := c.nextID.Add(1) ch := make(chan json.RawMessage, 1) @@ -401,6 +441,9 @@ func (c *MCPSSEClient) callRPC(ctx context.Context, method string, params any) ( } } +// notify +// 发送一个不带 ID 的 JSON-RPC 通知; +// 通知无需等待服务端响应. func (c *MCPSSEClient) notify(ctx context.Context, method string, params any) error { c.mu.Lock() postURL := c.postURL @@ -438,6 +481,8 @@ type MCPToolRouter struct { listFailures map[string]error } +// NewMCPToolRouter +// 创建一个 MCP 工具路由器, 用于注册、自动发现并分发 MCP 工具调用. func NewMCPToolRouter() *MCPToolRouter { return &MCPToolRouter{ clients: make(map[string]*MCPSSEClient), @@ -447,16 +492,24 @@ func NewMCPToolRouter() *MCPToolRouter { } } +// Register +// 注册一个工具; +// 内部直接委托给 RegisterAndExpand 处理. func (r *MCPToolRouter) Register(tool ports.Tool) { r.RegisterAndExpand(tool) } +// RegisterAndExpand +// 注册工具并对 SSE 类型的 MCP 工具进行自动展开: 创建共享客户端、调用 tools/list 发现所有工具并逐一注册; +// 发现失败时降级保留原始工具. func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool { mcp, ok := tool.(MCPTool) + // 非 MCP 工具不展开,直接注册,返回原始工具 if !ok { r.tools = append(r.tools, tool) return []ports.Tool{tool} } + // 不是 SSE 传输类型的 MCP 工具也是原样注册 if mcp.TransportType != "sse" { r.tools = append(r.tools, mcp) return []ports.Tool{mcp} @@ -475,6 +528,7 @@ func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool { r.tools = append(r.tools, mcp) return []ports.Tool{mcp} } + // 将发现的工具名注册为 EinoTool, 并共享同一个 SSE 客户端 expanded := make([]ports.Tool, 0, len(names)) for _, n := range names { r.clients[n] = client @@ -486,10 +540,15 @@ func (r *MCPToolRouter) RegisterAndExpand(tool ports.Tool) []ports.Tool { return expanded } +// Tools +// 返回当前已注册的所有工具. func (r *MCPToolRouter) Tools() []ports.Tool { return r.tools } +// CallTool +// 根据工具名将调用分发给已注册的 MCP SSE 客户端; +// 找不到可调用客户端时返回明确错误. func (r *MCPToolRouter) CallTool(ctx context.Context, name, arguments string) (string, error) { if client, ok := r.clients[name]; ok { return client.CallTool(ctx, name, arguments) diff --git a/internal/infrastructure/ai/tools.go b/internal/infrastructure/ai/tools.go index 2abd599..1bf08fb 100644 --- a/internal/infrastructure/ai/tools.go +++ b/internal/infrastructure/ai/tools.go @@ -13,6 +13,7 @@ import ( "ai-agent-scaffold-go/internal/domain/agent/model" "ai-agent-scaffold-go/internal/domain/agent/ports" + "gopkg.in/yaml.v3" ) @@ -41,14 +42,22 @@ type SkillTool struct { ManifestPath string } +// NewToolFactory 创建 ToolFactory. +// router 用于将构建出的 MCP 工具注册并展开为 LLM 可调用的工具列表,可为 nil. func NewToolFactory(router *MCPToolRouter) *ToolFactory { return &ToolFactory{router: router} } +// NewSkillFactory 创建 SkillFactory. +// SkillFactory 是无状态的,所有技能信息均从磁盘上的 SKILL.md 扫描获得. func NewSkillFactory() *SkillFactory { return &SkillFactory{} } +// ports.MCPToolFactory 接口方法实现. +// BuildTools 根据 model.ToolMCPConfig 构建工具列表. +// 支持 local、sse、stdio 三种传输方式; +// SSE 工具会交由 router 动态展开为服务端真实工具列表. func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig) ([]ports.Tool, error) { kind, err := validateMCPConfig(config) if err != nil { @@ -91,10 +100,14 @@ func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig) return tools, nil } +// ports.Tool 接口方法实现 +// Name 返回工具名. func (t MCPTool) Name() string { return t.ToolName } +// ports.SkillFactory 接口方法实现 +// BuildTools 根据 model.ToolSkillsConfig 扫描目录下的 SKILL.md,构建技能工具列表. func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConfig) ([]ports.Tool, error) { skillType := strings.TrimSpace(config.Type) if skillType == "" { @@ -132,10 +145,15 @@ func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConf return tools, nil } +// ports.Tool 接口方法实现 +// Name 返回工具名 func (t SkillTool) Name() string { return t.ToolName } +// resolveSkillRoot +// 将配置中的技能路径解析为实际存在的根路径. +// 支持绝对路径,也支持从当前工作目录逐级向上查找多个相对路径候选. func resolveSkillRoot(skillType, rawPath string) (string, error) { if filepath.IsAbs(rawPath) { return existingPath(rawPath, rawPath) @@ -155,6 +173,8 @@ func resolveSkillRoot(skillType, rawPath string) (string, error) { return "", fmt.Errorf("skill path %q cannot be resolved", rawPath) } +// skillPathCandidates +// 从当前工作目录逐级向上生成技能路径候选,并做去重. func skillPathCandidates(cwd, skillType, rawPath string) []string { var candidates []string add := func(path string) { @@ -184,6 +204,8 @@ func skillPathCandidates(cwd, skillType, rawPath string) []string { return candidates } +// existingPath +// 校验候选路径是否存在,且必须是目录或 SKILL.md 文件. func existingPath(candidate, original string) (string, error) { info, err := os.Stat(candidate) if err != nil { @@ -195,6 +217,8 @@ func existingPath(candidate, original string) (string, error) { return candidate, nil } +// findSkillManifests +// 在技能根路径下递归查找所有 SKILL.md,并按路径排序保证结果稳定. func findSkillManifests(root string) ([]string, error) { info, err := os.Stat(root) if err != nil { @@ -224,6 +248,8 @@ func findSkillManifests(root string) ([]string, error) { return manifests, nil } +// loadSkillTool +// 读取并解析单个 SKILL.md,构建 SkillTool. func loadSkillTool(root, manifest string) (SkillTool, error) { data, err := os.ReadFile(manifest) if err != nil { @@ -250,6 +276,8 @@ func loadSkillTool(root, manifest string) (SkillTool, error) { }, nil } +// sanitizeToolName +// 清洗工具名,仅保留字母、数字、下划线和连字符,并限制长度不超过 64 个字符. func sanitizeToolName(name string) string { var b strings.Builder for _, r := range name { @@ -270,6 +298,8 @@ func sanitizeToolName(name string) string { return out } +// parseSkillFrontMatter +// 解析 SKILL.md 头部的 YAML front matter,返回元数据键值对. func parseSkillFrontMatter(content string) (map[string]string, error) { result := make(map[string]string) if !strings.HasPrefix(content, "---") { @@ -289,6 +319,8 @@ func parseSkillFrontMatter(content string) (map[string]string, error) { return result, nil } +// validateMCPConfig +// 校验 MCP 配置必须且只能指定 local、sse、stdio 中的一种,并返回其类型. func validateMCPConfig(config model.ToolMCPConfig) (string, error) { count := 0 kind := "" @@ -315,6 +347,8 @@ func validateMCPConfig(config model.ToolMCPConfig) (string, error) { } } +// buildLocalMCPTools +// 根据本地工具配置构建 MCPTool,目前仅支持内置的 echoLocalTool. func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error) { name := strings.TrimSpace(config.Name) if name == "" { @@ -329,6 +363,8 @@ func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error) } } +// buildSSEMCPTools +// 根据 SSE 配置构建 MCPTool,并规范化 base-uri 与 sse-endpoint. func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) { name := strings.TrimSpace(config.Name) if name == "" { @@ -354,6 +390,8 @@ func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) { }}, nil } +// buildStdioMCPTools +// 根据 stdio 配置构建 MCPTool,并拷贝命令参数与环境变量. func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, error) { name := strings.TrimSpace(config.Name) if name == "" { @@ -375,6 +413,8 @@ func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, erro }}, nil } +// normalizeSSETarget +// 规范化 SSE 目标地址,将 base-uri 与 endpoint 合并为 (scheme://host, path) 两部分. func normalizeSSETarget(baseURI, endpoint string) (string, string, error) { parsed, err := url.Parse(baseURI) if err != nil { @@ -411,6 +451,8 @@ func normalizeSSETarget(baseURI, endpoint string) (string, string, error) { return host, normalizeEndpoint(mergedPath), nil } +// splitPathQuery +// 将 URL 路径与查询串按第一个 '?' 拆开. func splitPathQuery(raw string) (string, string) { if idx := strings.Index(raw, "?"); idx >= 0 { return raw[:idx], raw[idx+1:] @@ -418,6 +460,8 @@ func splitPathQuery(raw string) (string, string) { return raw, "" } +// joinPaths +// 拼接 URL 路径,处理空路径、绝对路径和重复斜杠. func joinPaths(base, extra string) string { if extra == "" { if base == "" { @@ -437,6 +481,8 @@ func joinPaths(base, extra string) string { return base + "/" + extra } +// mergeQueries +// 合并两段查询串. func mergeQueries(base, extra string) string { switch { case base == "" && extra == "": @@ -450,6 +496,8 @@ func mergeQueries(base, extra string) string { } } +// normalizeEndpoint +// 确保端点以 '/' 开头,空值回退为 /sse. func normalizeEndpoint(endpoint string) string { trimmed := strings.TrimSpace(endpoint) if trimmed == "" { @@ -461,6 +509,8 @@ func normalizeEndpoint(endpoint string) string { return "/" + trimmed } +// normalizeTimeout +// 规范化超时毫秒数,非正数时返回默认值 300000(5 分钟). func normalizeTimeout(timeout int) int { if timeout > 0 { return timeout @@ -468,6 +518,8 @@ func normalizeTimeout(timeout int) int { return 300000 } +// cloneEnv +// 拷贝环境变量 map,避免运行时对象与配置共享底层数据. func cloneEnv(values map[string]string) map[string]string { if len(values) == 0 { return nil @@ -479,6 +531,8 @@ func cloneEnv(values map[string]string) map[string]string { return cloned } +// maskSecretPath +// 对 URL 查询参数中疑似密钥的值进行脱敏,用于日志输出. func maskSecretPath(raw string) string { if strings.TrimSpace(raw) == "" { return raw @@ -503,6 +557,8 @@ func maskSecretPath(raw string) string { return parsed.String() } +// mcpTimeoutString +// 将超时毫秒数规范化为字符串. func mcpTimeoutString(timeout int) string { return strconv.Itoa(normalizeTimeout(timeout)) }