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

585 lines
16 KiB
Go
Raw Normal View History

2026-05-30 23:16:49 +08:00
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"
2026-09-15 14:04:53 +08:00
2026-05-30 23:16:49 +08:00
"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
}
2026-09-15 14:04:53 +08:00
// NewToolFactory 创建 ToolFactory.
2026-10-05 21:09:39 +08:00
//
// router 用于将构建出的 MCP 工具注册并展开为 LLM 可调用的工具列表, 可为 nil.
2026-05-30 23:16:49 +08:00
func NewToolFactory(router *MCPToolRouter) *ToolFactory {
return &ToolFactory{router: router}
}
2026-09-15 14:04:53 +08:00
// NewSkillFactory 创建 SkillFactory.
2026-10-05 21:09:39 +08:00
//
// SkillFactory 是无状态的, 所有技能信息均从磁盘上的 SKILL.md 扫描获得.
2026-05-30 23:16:49 +08:00
func NewSkillFactory() *SkillFactory {
return &SkillFactory{}
}
2026-10-05 21:09:39 +08:00
// BuildTools 根据 model.ToolMCPConfig 构建工具列表, 实现 ports.MCPToolFactory 接口.
//
2026-09-15 14:04:53 +08:00
// 支持 local、sse、stdio 三种传输方式;
// SSE 工具会交由 router 动态展开为服务端真实工具列表.
2026-05-30 23:16:49 +08:00
func (f *ToolFactory) BuildTools(_ context.Context, config model.ToolMCPConfig) ([]ports.Tool, error) {
2026-10-05 21:09:39 +08:00
// 校验配置必须且只能指定一种传输方式, 并返回其类型
2026-05-30 23:16:49 +08:00
kind, err := validateMCPConfig(config)
if err != nil {
return nil, err
}
var (
tools []ports.Tool
)
2026-10-05 21:09:39 +08:00
// 按传输类型构建工具, 兼容 type 为空时直接依据非空字段判断的历史配置
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// 有 router 时注册并展开工具, 例如把 SSE 配置展开为服务端真实工具列表
2026-05-30 23:16:49 +08:00
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...)
}
2026-10-05 21:09:39 +08:00
// 展开结果为空说明注册失败, 回退到原始工具列表以保证启动不中断
2026-05-30 23:16:49 +08:00
if len(expanded) > 0 {
return expanded, nil
}
}
return tools, nil
}
2026-10-05 21:09:39 +08:00
// Name 返回工具名, 实现 ports.Tool 接口.
2026-05-30 23:16:49 +08:00
func (t MCPTool) Name() string {
return t.ToolName
}
2026-10-05 21:09:39 +08:00
// BuildTools 根据 model.ToolSkillsConfig 扫描目录下的 SKILL.md 并构建技能工具列表, 实现 ports.SkillFactory 接口.
//
// 每个 SKILL.md 会被解析为一个独立的 SkillTool, 工具名统一添加 skill_ 前缀以避免与 MCP 工具重名.
2026-05-30 23:16:49 +08:00
func (f *SkillFactory) BuildTools(_ context.Context, config model.ToolSkillsConfig) ([]ports.Tool, error) {
2026-10-05 21:09:39 +08:00
// type 为空时默认为 directory, 目前仅支持 directory 与 resource 两种取值
2026-05-30 23:16:49 +08:00
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")
}
2026-10-05 21:09:39 +08:00
// 把配置中的相对路径解析为实际存在的技能根路径
2026-05-30 23:16:49 +08:00
root, err := resolveSkillRoot(skillType, rawPath)
if err != nil {
return nil, err
}
2026-10-05 21:09:39 +08:00
// 递归查找技能根路径下的所有 SKILL.md
2026-05-30 23:16:49 +08:00
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)
}
2026-10-05 21:09:39 +08:00
// 每个 SKILL.md 解析为一个独立工具
2026-05-30 23:16:49 +08:00
tools := make([]ports.Tool, 0, len(manifests))
for _, manifest := range manifests {
2026-10-05 21:09:39 +08:00
tool, err := loadSkillTool(manifest)
2026-05-30 23:16:49 +08:00
if err != nil {
return nil, err
}
tools = append(tools, tool)
}
return tools, nil
}
2026-10-05 21:09:39 +08:00
// Name 返回工具名, 实现 ports.Tool 接口.
2026-05-30 23:16:49 +08:00
func (t SkillTool) Name() string {
return t.ToolName
}
2026-10-05 21:09:39 +08:00
// resolveSkillRoot 将配置中的技能路径解析为实际存在的根路径.
//
// 支持绝对路径, 也支持从当前工作目录逐级向上查找多个相对路径候选.
2026-05-30 23:16:49 +08:00
func resolveSkillRoot(skillType, rawPath string) (string, error) {
2026-10-05 21:09:39 +08:00
// 绝对路径直接校验
2026-05-30 23:16:49 +08:00
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)
}
2026-10-05 21:09:39 +08:00
// 依次尝试候选路径, 返回第一个真实存在的路径
2026-05-30 23:16:49 +08:00
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)
}
2026-10-05 21:09:39 +08:00
// skillPathCandidates 从当前工作目录逐级向上生成技能路径候选, 并做去重.
//
// 同时兼容直接使用原始相对路径、configs 前缀以及仓库目录名三种常见布局.
2026-05-30 23:16:49 +08:00
func skillPathCandidates(cwd, skillType, rawPath string) []string {
var candidates []string
2026-10-05 21:09:39 +08:00
// 去重后加入候选列表, 避免重复路径被多次校验
2026-05-30 23:16:49 +08:00
add := func(path string) {
clean := filepath.Clean(path)
for _, candidate := range candidates {
if candidate == clean {
return
}
}
candidates = append(candidates, clean)
}
2026-10-05 21:09:39 +08:00
// 从当前目录逐级向上尝试, 直到文件系统根目录
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// existingPath 校验候选路径是否存在, 且必须是目录或 SKILL.md 文件.
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// findSkillManifests 在技能根路径下递归查找所有 SKILL.md, 并按路径排序保证结果稳定.
2026-05-30 23:16:49 +08:00
func findSkillManifests(root string) ([]string, error) {
info, err := os.Stat(root)
if err != nil {
return nil, err
}
2026-10-05 21:09:39 +08:00
// 路径本身就是单个 SKILL.md 文件时直接返回
2026-05-30 23:16:49 +08:00
if !info.IsDir() {
return []string{root}, nil
}
2026-10-05 21:09:39 +08:00
// 递归遍历目录, 只收集文件名严格等于 SKILL.md 的文件
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// loadSkillTool 读取并解析单个 SKILL.md, 构建 SkillTool.
//
// 元数据缺少 name 时使用技能目录名, 最终工具名会经过清洗并添加 skill_ 前缀.
func loadSkillTool(manifest string) (SkillTool, error) {
2026-05-30 23:16:49 +08:00
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)
2026-10-05 21:09:39 +08:00
// name 缺失时回退为目录名
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// sanitizeToolName 清洗工具名, 仅保留字母、数字、下划线和连字符, 并限制长度不超过 64 个字符.
2026-05-30 23:16:49 +08:00
func sanitizeToolName(name string) string {
2026-10-05 21:09:39 +08:00
// 非法字符统一替换为下划线
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// parseSkillFrontMatter 解析 SKILL.md 头部的 YAML front matter, 返回元数据键值对.
//
// 文件不以 --- 开头时返回空元数据, 由调用方回退到默认命名.
2026-05-30 23:16:49 +08:00
func parseSkillFrontMatter(content string) (map[string]string, error) {
result := make(map[string]string)
2026-10-05 21:09:39 +08:00
// 没有 front matter 时直接返回空结果
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// validateMCPConfig 校验 MCP 配置必须且只能指定 local、sse、stdio 中的一种, 并返回其类型.
2026-05-30 23:16:49 +08:00
func validateMCPConfig(config model.ToolMCPConfig) (string, error) {
2026-10-05 21:09:39 +08:00
// 统计非空传输字段, 数量必须恰好为 1
2026-05-30 23:16:49 +08:00
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")
}
}
2026-10-05 21:09:39 +08:00
// buildLocalMCPTools 根据本地工具配置构建 MCPTool, 目前仅支持内置的 echoLocalTool.
2026-05-30 23:16:49 +08:00
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)
}
}
2026-10-05 21:09:39 +08:00
// buildSSEMCPTools 根据 SSE 配置构建 MCPTool, 并规范化 base-uri 与 sse-endpoint.
//
// 返回的工具只保存连接信息, 真正的工具列表由 MCPToolRouter 在注册时从服务端自动发现.
2026-05-30 23:16:49 +08:00
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)
}
2026-10-05 21:09:39 +08:00
// 把 base-uri 与 sse-endpoint 合并规范化为可复用的连接目标
2026-05-30 23:16:49 +08:00
normalizedBaseURI, endpoint, err := normalizeSSETarget(baseURI, strings.TrimSpace(config.SSEEndpoint))
if err != nil {
return nil, fmt.Errorf("sse mcp tool %q: %w", name, err)
}
2026-10-05 21:09:39 +08:00
// 超时未配置时使用默认值
2026-05-30 23:16:49 +08:00
timeout := normalizeTimeout(config.RequestTimeout)
return []ports.Tool{MCPTool{
ToolName: name,
TransportType: "sse",
BaseURI: normalizedBaseURI,
SSEEndpoint: endpoint,
RequestTimeout: timeout,
}}, nil
}
2026-10-05 21:09:39 +08:00
// buildStdioMCPTools 根据 stdio 配置构建 MCPTool, 并拷贝命令参数与环境变量.
2026-05-30 23:16:49 +08:00
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)
2026-10-05 21:09:39 +08:00
// Args 与 Env 都做拷贝, 避免运行时对象与配置共享底层数据
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// normalizeSSETarget 规范化 SSE 目标地址, 将 base-uri 与 endpoint 合并为 (scheme://host, path) 两部分.
//
// endpoint 为空时根据 base-uri 的 path 推断, 默认回退到 /sse.
2026-05-30 23:16:49 +08:00
func normalizeSSETarget(baseURI, endpoint string) (string, string, error) {
parsed, err := url.Parse(baseURI)
if err != nil {
return "", "", fmt.Errorf("invalid base-uri: %w", err)
}
2026-10-05 21:09:39 +08:00
// base-uri 必须是带 scheme 和 host 的绝对地址
2026-05-30 23:16:49 +08:00
if parsed.Scheme == "" || parsed.Host == "" {
return "", "", fmt.Errorf("base-uri must include scheme and host")
}
2026-10-05 21:09:39 +08:00
// 只保留 scheme://host, path 与 query 单独处理
2026-05-30 23:16:49 +08:00
host := strings.TrimRight(parsed.Scheme+"://"+parsed.Host, "/")
basePath := parsed.RawPath
if basePath == "" {
basePath = parsed.EscapedPath()
}
baseQuery := parsed.RawQuery
2026-10-05 21:09:39 +08:00
// endpoint 为空时从 base-uri 的 path 推断
2026-05-30 23:16:49 +08:00
if endpoint == "" {
if basePath == "" || basePath == "/" {
return host, "/sse", nil
}
merged := basePath
if baseQuery != "" {
merged += "?" + baseQuery
}
return host, normalizeEndpoint(merged), nil
}
2026-10-05 21:09:39 +08:00
// 合并 path 与 query, query 部分直接拼接
2026-05-30 23:16:49 +08:00
endpointPath, endpointQuery := splitPathQuery(endpoint)
mergedPath := joinPaths(basePath, endpointPath)
mergedQuery := mergeQueries(baseQuery, endpointQuery)
if mergedQuery != "" {
mergedPath += "?" + mergedQuery
}
return host, normalizeEndpoint(mergedPath), nil
}
2026-10-05 21:09:39 +08:00
// splitPathQuery 将 URL 路径与查询串按第一个 '?' 拆开.
2026-05-30 23:16:49 +08:00
func splitPathQuery(raw string) (string, string) {
if idx := strings.Index(raw, "?"); idx >= 0 {
return raw[:idx], raw[idx+1:]
}
return raw, ""
}
2026-10-05 21:09:39 +08:00
// joinPaths 拼接 URL 路径, 处理空路径、绝对路径和重复斜杠.
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// mergeQueries 合并两段查询串.
2026-05-30 23:16:49 +08:00
func mergeQueries(base, extra string) string {
switch {
case base == "" && extra == "":
return ""
case base == "":
return extra
case extra == "":
return base
default:
return base + "&" + extra
}
}
2026-10-05 21:09:39 +08:00
// normalizeEndpoint 确保端点以 '/' 开头, 空值回退为 /sse.
2026-05-30 23:16:49 +08:00
func normalizeEndpoint(endpoint string) string {
trimmed := strings.TrimSpace(endpoint)
if trimmed == "" {
return "/sse"
}
if strings.HasPrefix(trimmed, "/") {
return trimmed
}
return "/" + trimmed
}
2026-10-05 21:09:39 +08:00
// normalizeTimeout 规范化超时毫秒数, 非正数时返回默认值 300000(5 分钟).
2026-05-30 23:16:49 +08:00
func normalizeTimeout(timeout int) int {
if timeout > 0 {
return timeout
}
return 300000
}
2026-10-05 21:09:39 +08:00
// cloneEnv 拷贝环境变量 map, 避免运行时对象与配置共享底层数据.
2026-05-30 23:16:49 +08:00
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
}
2026-10-05 21:09:39 +08:00
// maskSecretPath 对 URL 查询参数中疑似密钥的值进行脱敏, 用于日志输出.
//
// 参数名包含 KEY、TOKEN 或 SECRET 时, 其值会被替换为 ${VAR} 形式的占位符.
2026-05-30 23:16:49 +08:00
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
}
}
2026-10-05 21:09:39 +08:00
// 没有敏感参数时原样返回
2026-05-30 23:16:49 +08:00
if !changed {
return raw
}
parsed.RawQuery = query.Encode()
return parsed.String()
}
2026-10-05 21:09:39 +08:00
// mcpTimeoutString 将超时毫秒数规范化为字符串.
2026-05-30 23:16:49 +08:00
func mcpTimeoutString(timeout int) string {
return strconv.Itoa(normalizeTimeout(timeout))
}