Files
ai-agent-scaffold-go/internal/infrastructure/ai/tools.go

585 lines
16 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package ai
import (
"context"
"fmt"
"io/fs"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"ai-agent-scaffold-go/internal/domain/agent/model"
"ai-agent-scaffold-go/internal/domain/agent/ports"
"gopkg.in/yaml.v3"
)
type ToolFactory struct {
router *MCPToolRouter
}
type SkillFactory struct{}
type MCPTool struct {
ToolName string
TransportType string
BaseURI string
SSEEndpoint string
Command string
Args []string
Env map[string]string
RequestTimeout int
}
type SkillTool struct {
ToolName string
SkillName string
Description string
Path string
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{}
}
// BuildTools 根据 model.ToolMCPConfig 构建工具列表, 实现 ports.MCPToolFactory 接口.
//
// 支持 local、sse、stdio 三种传输方式;
// SSE 工具会交由 router 动态展开为服务端真实工具列表.
func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig) ([]ports.Tool, error) {
// 校验配置必须且只能指定一种传输方式, 并返回其类型
kind, err := validateMCPConfig(config)
if err != nil {
return nil, err
}
var (
tools []ports.Tool
)
// 按传输类型构建工具, 兼容 type 为空时直接依据非空字段判断的历史配置
switch {
case kind == "local":
tools, err = buildLocalMCPTools(config.Local)
case kind == "sse":
tools, err = buildSSEMCPTools(config.SSE)
case kind == "stdio":
tools, err = buildStdioMCPTools(config.Stdio)
case config.SSE != nil:
tools, err = buildSSEMCPTools(config.SSE)
case config.Stdio != nil:
tools, err = buildStdioMCPTools(config.Stdio)
default:
return nil, fmt.Errorf("mcp tool config is empty")
}
if err != nil {
return nil, err
}
// 有 router 时注册并展开工具, 例如把 SSE 配置展开为服务端真实工具列表
if f.router != nil {
expanded := make([]ports.Tool, 0, len(tools))
for _, t := range tools {
ts := f.router.RegisterAndExpand(t)
if len(ts) == 0 {
continue
}
expanded = append(expanded, ts...)
}
// 展开结果为空说明注册失败, 回退到原始工具列表以保证启动不中断
if len(expanded) > 0 {
return expanded, nil
}
}
return tools, nil
}
// Name 返回工具名, 实现 ports.Tool 接口.
func (t MCPTool) Name() string {
return t.ToolName
}
// BuildTools 根据 model.ToolSkillsConfig 扫描目录下的 SKILL.md 并构建技能工具列表, 实现 ports.SkillFactory 接口.
//
// 每个 SKILL.md 会被解析为一个独立的 SkillTool, 工具名统一添加 skill_ 前缀以避免与 MCP 工具重名.
func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConfig) ([]ports.Tool, error) {
// type 为空时默认为 directory, 目前仅支持 directory 与 resource 两种取值
skillType := strings.TrimSpace(config.Type)
if skillType == "" {
skillType = "directory"
}
if skillType != "directory" && skillType != "resource" {
return nil, fmt.Errorf("unsupported skill type %q", config.Type)
}
rawPath := strings.TrimSpace(config.Path)
if rawPath == "" {
return nil, fmt.Errorf("skill path is required")
}
// 把配置中的相对路径解析为实际存在的技能根路径
root, err := resolveSkillRoot(skillType, rawPath)
if err != nil {
return nil, err
}
// 递归查找技能根路径下的所有 SKILL.md
manifests, err := findSkillManifests(root)
if err != nil {
return nil, err
}
if len(manifests) == 0 {
return nil, fmt.Errorf("skill path %q has no SKILL.md files", root)
}
// 每个 SKILL.md 解析为一个独立工具
tools := make([]ports.Tool, 0, len(manifests))
for _, manifest := range manifests {
tool, err := loadSkillTool(manifest)
if err != nil {
return nil, err
}
tools = append(tools, tool)
}
return tools, nil
}
// Name 返回工具名, 实现 ports.Tool 接口.
func (t SkillTool) Name() string {
return t.ToolName
}
// resolveSkillRoot 将配置中的技能路径解析为实际存在的根路径.
//
// 支持绝对路径, 也支持从当前工作目录逐级向上查找多个相对路径候选.
func resolveSkillRoot(skillType, rawPath string) (string, error) {
// 绝对路径直接校验
if filepath.IsAbs(rawPath) {
return existingPath(rawPath, rawPath)
}
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("resolve skill path %q: %w", rawPath, err)
}
// 依次尝试候选路径, 返回第一个真实存在的路径
candidates := skillPathCandidates(cwd, skillType, rawPath)
for _, candidate := range candidates {
if path, err := existingPath(candidate, rawPath); err == nil {
return path, nil
}
}
return "", fmt.Errorf("skill path %q cannot be resolved", rawPath)
}
// skillPathCandidates 从当前工作目录逐级向上生成技能路径候选, 并做去重.
//
// 同时兼容直接使用原始相对路径、configs 前缀以及仓库目录名三种常见布局.
func skillPathCandidates(cwd, skillType, rawPath string) []string {
var candidates []string
// 去重后加入候选列表, 避免重复路径被多次校验
add := func(path string) {
clean := filepath.Clean(path)
for _, candidate := range candidates {
if candidate == clean {
return
}
}
candidates = append(candidates, clean)
}
// 从当前目录逐级向上尝试, 直到文件系统根目录
for dir := cwd; ; dir = filepath.Dir(dir) {
add(filepath.Join(dir, rawPath))
add(filepath.Join(dir, "configs", rawPath))
add(filepath.Join(dir, "ai-agent-scaffold-go", rawPath))
add(filepath.Join(dir, "ai-agent-scaffold-go", "configs", rawPath))
if skillType == "resource" && strings.HasPrefix(rawPath, "agent"+string(filepath.Separator)) {
add(filepath.Join(dir, "configs", rawPath))
add(filepath.Join(dir, "ai-agent-scaffold-go", "configs", rawPath))
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
}
return candidates
}
// existingPath 校验候选路径是否存在, 且必须是目录或 SKILL.md 文件.
func existingPath(candidate, original string) (string, error) {
info, err := os.Stat(candidate)
if err != nil {
return "", fmt.Errorf("skill path %q cannot be resolved", original)
}
if !info.IsDir() && filepath.Base(candidate) != "SKILL.md" {
return "", fmt.Errorf("skill path %q is not a directory or SKILL.md file", candidate)
}
return candidate, nil
}
// findSkillManifests 在技能根路径下递归查找所有 SKILL.md, 并按路径排序保证结果稳定.
func findSkillManifests(root string) ([]string, error) {
info, err := os.Stat(root)
if err != nil {
return nil, err
}
// 路径本身就是单个 SKILL.md 文件时直接返回
if !info.IsDir() {
return []string{root}, nil
}
// 递归遍历目录, 只收集文件名严格等于 SKILL.md 的文件
var manifests []string
err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
if entry.Name() == "SKILL.md" {
manifests = append(manifests, path)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("scan skill path %q: %w", root, err)
}
sort.Strings(manifests)
return manifests, nil
}
// loadSkillTool 读取并解析单个 SKILL.md, 构建 SkillTool.
//
// 元数据缺少 name 时使用技能目录名, 最终工具名会经过清洗并添加 skill_ 前缀.
func loadSkillTool(manifest string) (SkillTool, error) {
data, err := os.ReadFile(manifest)
if err != nil {
return SkillTool{}, fmt.Errorf("read skill manifest %q: %w", manifest, err)
}
meta, err := parseSkillFrontMatter(string(data))
if err != nil {
return SkillTool{}, fmt.Errorf("parse skill manifest %q: %w", manifest, err)
}
skillDir := filepath.Dir(manifest)
// name 缺失时回退为目录名
name := strings.TrimSpace(meta["name"])
if name == "" {
name = filepath.Base(skillDir)
}
description := strings.TrimSpace(meta["description"])
return SkillTool{
ToolName: "skill_" + sanitizeToolName(name),
SkillName: name,
Description: description,
Path: skillDir,
ManifestPath: manifest,
}, nil
}
// sanitizeToolName 清洗工具名, 仅保留字母、数字、下划线和连字符, 并限制长度不超过 64 个字符.
func sanitizeToolName(name string) string {
// 非法字符统一替换为下划线
var b strings.Builder
for _, r := range name {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
b.WriteRune(r)
default:
b.WriteByte('_')
}
}
out := b.String()
if out == "" {
out = "tool"
}
if len(out) > 64 {
out = out[:64]
}
return out
}
// parseSkillFrontMatter 解析 SKILL.md 头部的 YAML front matter, 返回元数据键值对.
//
// 文件不以 --- 开头时返回空元数据, 由调用方回退到默认命名.
func parseSkillFrontMatter(content string) (map[string]string, error) {
result := make(map[string]string)
// 没有 front matter 时直接返回空结果
if !strings.HasPrefix(content, "---") {
return result, nil
}
rest := strings.TrimPrefix(content, "---")
end := strings.Index(rest, "\n---")
if end < 0 {
return result, fmt.Errorf("front matter terminator is required")
}
frontMatter := rest[:end]
if err := yaml.Unmarshal([]byte(frontMatter), &result); err != nil {
return nil, err
}
return result, nil
}
// validateMCPConfig 校验 MCP 配置必须且只能指定 local、sse、stdio 中的一种, 并返回其类型.
func validateMCPConfig(config model.ToolMCPConfig) (string, error) {
// 统计非空传输字段, 数量必须恰好为 1
count := 0
kind := ""
if config.Local != nil {
count++
kind = "local"
}
if config.SSE != nil {
count++
kind = "sse"
}
if config.Stdio != nil {
count++
kind = "stdio"
}
switch count {
case 0:
return "", fmt.Errorf("mcp config must define exactly one of local, sse, or stdio")
case 1:
return kind, nil
default:
return "", fmt.Errorf("mcp config cannot define multiple transports in one entry")
}
}
// buildLocalMCPTools 根据本地工具配置构建 MCPTool, 目前仅支持内置的 echoLocalTool.
func buildLocalMCPTools(config *model.LocalToolParameters) ([]ports.Tool, error) {
name := strings.TrimSpace(config.Name)
if name == "" {
return nil, fmt.Errorf("local mcp tool name is required")
}
switch name {
case "echoLocalTool":
return []ports.Tool{MCPTool{ToolName: name, TransportType: "local"}}, nil
default:
return nil, fmt.Errorf("local mcp tool %q is not registered in go", name)
}
}
// buildSSEMCPTools 根据 SSE 配置构建 MCPTool, 并规范化 base-uri 与 sse-endpoint.
//
// 返回的工具只保存连接信息, 真正的工具列表由 MCPToolRouter 在注册时从服务端自动发现.
func buildSSEMCPTools(config *model.SSEServerParameters) ([]ports.Tool, error) {
name := strings.TrimSpace(config.Name)
if name == "" {
return nil, fmt.Errorf("sse mcp tool name is required")
}
baseURI := strings.TrimSpace(config.BaseURI)
if baseURI == "" {
return nil, fmt.Errorf("sse mcp tool %q base-uri is required", name)
}
// 把 base-uri 与 sse-endpoint 合并规范化为可复用的连接目标
normalizedBaseURI, endpoint, err := normalizeSSETarget(baseURI, strings.TrimSpace(config.SSEEndpoint))
if err != nil {
return nil, fmt.Errorf("sse mcp tool %q: %w", name, err)
}
// 超时未配置时使用默认值
timeout := normalizeTimeout(config.RequestTimeout)
return []ports.Tool{MCPTool{
ToolName: name,
TransportType: "sse",
BaseURI: normalizedBaseURI,
SSEEndpoint: endpoint,
RequestTimeout: timeout,
}}, nil
}
// buildStdioMCPTools 根据 stdio 配置构建 MCPTool, 并拷贝命令参数与环境变量.
func buildStdioMCPTools(config *model.StdioServerParameters) ([]ports.Tool, error) {
name := strings.TrimSpace(config.Name)
if name == "" {
return nil, fmt.Errorf("stdio mcp tool name is required")
}
command := strings.TrimSpace(config.ServerParameters.Command)
if command == "" {
return nil, fmt.Errorf("stdio mcp tool %q command is required", name)
}
timeout := normalizeTimeout(config.RequestTimeout)
// Args 与 Env 都做拷贝, 避免运行时对象与配置共享底层数据
return []ports.Tool{MCPTool{
ToolName: name,
TransportType: "stdio",
Command: command,
Args: append([]string(nil), config.ServerParameters.Args...),
Env: cloneEnv(config.ServerParameters.Env),
RequestTimeout: timeout,
}}, nil
}
// normalizeSSETarget 规范化 SSE 目标地址, 将 base-uri 与 endpoint 合并为 (scheme://host, path) 两部分.
//
// endpoint 为空时根据 base-uri 的 path 推断, 默认回退到 /sse.
func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
parsed, err := url.Parse(baseURI)
if err != nil {
return "", "", fmt.Errorf("invalid base-uri: %w", err)
}
// base-uri 必须是带 scheme 和 host 的绝对地址
if parsed.Scheme == "" || parsed.Host == "" {
return "", "", fmt.Errorf("base-uri must include scheme and host")
}
// 只保留 scheme://host, path 与 query 单独处理
host := strings.TrimRight(parsed.Scheme+"://"+parsed.Host, "/")
basePath := parsed.RawPath
if basePath == "" {
basePath = parsed.EscapedPath()
}
baseQuery := parsed.RawQuery
// endpoint 为空时从 base-uri 的 path 推断
if endpoint == "" {
if basePath == "" || basePath == "/" {
return host, "/sse", nil
}
merged := basePath
if baseQuery != "" {
merged += "?" + baseQuery
}
return host, normalizeEndpoint(merged), nil
}
// 合并 path 与 query, query 部分直接拼接
endpointPath, endpointQuery := splitPathQuery(endpoint)
mergedPath := joinPaths(basePath, endpointPath)
mergedQuery := mergeQueries(baseQuery, endpointQuery)
if mergedQuery != "" {
mergedPath += "?" + mergedQuery
}
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:]
}
return raw, ""
}
// joinPaths 拼接 URL 路径, 处理空路径、绝对路径和重复斜杠.
func joinPaths(base, extra string) string {
if extra == "" {
if base == "" {
return "/"
}
return base
}
if strings.HasPrefix(extra, "/") {
return extra
}
if base == "" {
return "/" + extra
}
if strings.HasSuffix(base, "/") {
return base + extra
}
return base + "/" + extra
}
// mergeQueries 合并两段查询串.
func mergeQueries(base, extra string) string {
switch {
case base == "" && extra == "":
return ""
case base == "":
return extra
case extra == "":
return base
default:
return base + "&" + extra
}
}
// normalizeEndpoint 确保端点以 '/' 开头, 空值回退为 /sse.
func normalizeEndpoint(endpoint string) string {
trimmed := strings.TrimSpace(endpoint)
if trimmed == "" {
return "/sse"
}
if strings.HasPrefix(trimmed, "/") {
return trimmed
}
return "/" + trimmed
}
// normalizeTimeout 规范化超时毫秒数, 非正数时返回默认值 300000(5 分钟).
func normalizeTimeout(timeout int) int {
if timeout > 0 {
return timeout
}
return 300000
}
// cloneEnv 拷贝环境变量 map, 避免运行时对象与配置共享底层数据.
func cloneEnv(values map[string]string) map[string]string {
if len(values) == 0 {
return nil
}
cloned := make(map[string]string, len(values))
for key, value := range values {
cloned[key] = value
}
return cloned
}
// maskSecretPath 对 URL 查询参数中疑似密钥的值进行脱敏, 用于日志输出.
//
// 参数名包含 KEY、TOKEN 或 SECRET 时, 其值会被替换为 ${VAR} 形式的占位符.
func maskSecretPath(raw string) string {
if strings.TrimSpace(raw) == "" {
return raw
}
parsed, err := url.Parse(raw)
if err != nil {
return raw
}
query := parsed.Query()
changed := false
for key := range query {
upper := strings.ToUpper(key)
if strings.Contains(upper, "KEY") || strings.Contains(upper, "TOKEN") || strings.Contains(upper, "SECRET") {
query.Set(key, "${"+strings.ToUpper(strings.ReplaceAll(key, "-", "_"))+"}")
changed = true
}
}
// 没有敏感参数时原样返回
if !changed {
return raw
}
parsed.RawQuery = query.Encode()
return parsed.String()
}
// mcpTimeoutString 将超时毫秒数规范化为字符串.
func mcpTimeoutString(timeout int) string {
return strconv.Itoa(normalizeTimeout(timeout))
}